regexp: add partial support for \A \Z matching
[jimtcl.git] / sqlite3 / sqlite3.c
bloba7f2677ef5e5b31abc284def9063436e01668ef4
1 /******************************************************************************
2 ** This file is an amalgamation of many separate C source files from SQLite
3 ** version 3.7.9. 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 following macros are used to cast pointers to integers and
321 ** integers to pointers. The way you do this varies from one compiler
322 ** to the next, so we have developed the following set of #if statements
323 ** to generate appropriate macros for a wide range of compilers.
325 ** The correct "ANSI" way to do this is to use the intptr_t type.
326 ** Unfortunately, that typedef is not available on all compilers, or
327 ** if it is available, it requires an #include of specific headers
328 ** that vary from one machine to the next.
330 ** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on
331 ** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)).
332 ** So we have to define the macros in different ways depending on the
333 ** compiler.
335 #if defined(__PTRDIFF_TYPE__) /* This case should work for GCC */
336 # define SQLITE_INT_TO_PTR(X) ((void*)(__PTRDIFF_TYPE__)(X))
337 # define SQLITE_PTR_TO_INT(X) ((int)(__PTRDIFF_TYPE__)(X))
338 #elif !defined(__GNUC__) /* Works for compilers other than LLVM */
339 # define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X])
340 # define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0))
341 #elif defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */
342 # define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X))
343 # define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X))
344 #else /* Generates a warning - but it always works */
345 # define SQLITE_INT_TO_PTR(X) ((void*)(X))
346 # define SQLITE_PTR_TO_INT(X) ((int)(X))
347 #endif
350 ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
351 ** 0 means mutexes are permanently disable and the library is never
352 ** threadsafe. 1 means the library is serialized which is the highest
353 ** level of threadsafety. 2 means the libary is multithreaded - multiple
354 ** threads can use SQLite as long as no two threads try to use the same
355 ** database connection at the same time.
357 ** Older versions of SQLite used an optional THREADSAFE macro.
358 ** We support that for legacy.
360 #if !defined(SQLITE_THREADSAFE)
361 #if defined(THREADSAFE)
362 # define SQLITE_THREADSAFE THREADSAFE
363 #else
364 # define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
365 #endif
366 #endif
369 ** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
370 ** It determines whether or not the features related to
371 ** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
372 ** be overridden at runtime using the sqlite3_config() API.
374 #if !defined(SQLITE_DEFAULT_MEMSTATUS)
375 # define SQLITE_DEFAULT_MEMSTATUS 1
376 #endif
379 ** Exactly one of the following macros must be defined in order to
380 ** specify which memory allocation subsystem to use.
382 ** SQLITE_SYSTEM_MALLOC // Use normal system malloc()
383 ** SQLITE_WIN32_MALLOC // Use Win32 native heap API
384 ** SQLITE_MEMDEBUG // Debugging version of system malloc()
386 ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
387 ** assert() macro is enabled, each call into the Win32 native heap subsystem
388 ** will cause HeapValidate to be called. If heap validation should fail, an
389 ** assertion will be triggered.
391 ** (Historical note: There used to be several other options, but we've
392 ** pared it down to just these three.)
394 ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
395 ** the default.
397 #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_WIN32_MALLOC)+defined(SQLITE_MEMDEBUG)>1
398 # error "At most one of the following compile-time configuration options\
399 is allows: SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG"
400 #endif
401 #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_WIN32_MALLOC)+defined(SQLITE_MEMDEBUG)==0
402 # define SQLITE_SYSTEM_MALLOC 1
403 #endif
406 ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
407 ** sizes of memory allocations below this value where possible.
409 #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
410 # define SQLITE_MALLOC_SOFT_LIMIT 1024
411 #endif
414 ** We need to define _XOPEN_SOURCE as follows in order to enable
415 ** recursive mutexes on most Unix systems. But Mac OS X is different.
416 ** The _XOPEN_SOURCE define causes problems for Mac OS X we are told,
417 ** so it is omitted there. See ticket #2673.
419 ** Later we learn that _XOPEN_SOURCE is poorly or incorrectly
420 ** implemented on some systems. So we avoid defining it at all
421 ** if it is already defined or if it is unneeded because we are
422 ** not doing a threadsafe build. Ticket #2681.
424 ** See also ticket #2741.
426 #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__) && SQLITE_THREADSAFE
427 # define _XOPEN_SOURCE 500 /* Needed to enable pthread recursive mutexes */
428 #endif
431 ** The TCL headers are only needed when compiling the TCL bindings.
433 #if defined(SQLITE_TCL) || defined(TCLSH)
434 # include <tcl.h>
435 #endif
438 ** Many people are failing to set -DNDEBUG=1 when compiling SQLite.
439 ** Setting NDEBUG makes the code smaller and run faster. So the following
440 ** lines are added to automatically set NDEBUG unless the -DSQLITE_DEBUG=1
441 ** option is set. Thus NDEBUG becomes an opt-in rather than an opt-out
442 ** feature.
444 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
445 # define NDEBUG 1
446 #endif
449 ** The testcase() macro is used to aid in coverage testing. When
450 ** doing coverage testing, the condition inside the argument to
451 ** testcase() must be evaluated both true and false in order to
452 ** get full branch coverage. The testcase() macro is inserted
453 ** to help ensure adequate test coverage in places where simple
454 ** condition/decision coverage is inadequate. For example, testcase()
455 ** can be used to make sure boundary values are tested. For
456 ** bitmask tests, testcase() can be used to make sure each bit
457 ** is significant and used at least once. On switch statements
458 ** where multiple cases go to the same block of code, testcase()
459 ** can insure that all cases are evaluated.
462 #ifdef SQLITE_COVERAGE_TEST
463 SQLITE_PRIVATE void sqlite3Coverage(int);
464 # define testcase(X) if( X ){ sqlite3Coverage(__LINE__); }
465 #else
466 # define testcase(X)
467 #endif
470 ** The TESTONLY macro is used to enclose variable declarations or
471 ** other bits of code that are needed to support the arguments
472 ** within testcase() and assert() macros.
474 #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
475 # define TESTONLY(X) X
476 #else
477 # define TESTONLY(X)
478 #endif
481 ** Sometimes we need a small amount of code such as a variable initialization
482 ** to setup for a later assert() statement. We do not want this code to
483 ** appear when assert() is disabled. The following macro is therefore
484 ** used to contain that setup code. The "VVA" acronym stands for
485 ** "Verification, Validation, and Accreditation". In other words, the
486 ** code within VVA_ONLY() will only run during verification processes.
488 #ifndef NDEBUG
489 # define VVA_ONLY(X) X
490 #else
491 # define VVA_ONLY(X)
492 #endif
495 ** The ALWAYS and NEVER macros surround boolean expressions which
496 ** are intended to always be true or false, respectively. Such
497 ** expressions could be omitted from the code completely. But they
498 ** are included in a few cases in order to enhance the resilience
499 ** of SQLite to unexpected behavior - to make the code "self-healing"
500 ** or "ductile" rather than being "brittle" and crashing at the first
501 ** hint of unplanned behavior.
503 ** In other words, ALWAYS and NEVER are added for defensive code.
505 ** When doing coverage testing ALWAYS and NEVER are hard-coded to
506 ** be true and false so that the unreachable code then specify will
507 ** not be counted as untested code.
509 #if defined(SQLITE_COVERAGE_TEST)
510 # define ALWAYS(X) (1)
511 # define NEVER(X) (0)
512 #elif !defined(NDEBUG)
513 # define ALWAYS(X) ((X)?1:(assert(0),0))
514 # define NEVER(X) ((X)?(assert(0),1):0)
515 #else
516 # define ALWAYS(X) (X)
517 # define NEVER(X) (X)
518 #endif
521 ** Return true (non-zero) if the input is a integer that is too large
522 ** to fit in 32-bits. This macro is used inside of various testcase()
523 ** macros to verify that we have tested SQLite for large-file support.
525 #define IS_BIG_INT(X) (((X)&~(i64)0xffffffff)!=0)
528 ** The macro unlikely() is a hint that surrounds a boolean
529 ** expression that is usually false. Macro likely() surrounds
530 ** a boolean expression that is usually true. GCC is able to
531 ** use these hints to generate better code, sometimes.
533 #if defined(__GNUC__) && 0
534 # define likely(X) __builtin_expect((X),1)
535 # define unlikely(X) __builtin_expect((X),0)
536 #else
537 # define likely(X) !!(X)
538 # define unlikely(X) !!(X)
539 #endif
541 /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
542 /************** Begin file sqlite3.h *****************************************/
544 ** 2001 September 15
546 ** The author disclaims copyright to this source code. In place of
547 ** a legal notice, here is a blessing:
549 ** May you do good and not evil.
550 ** May you find forgiveness for yourself and forgive others.
551 ** May you share freely, never taking more than you give.
553 *************************************************************************
554 ** This header file defines the interface that the SQLite library
555 ** presents to client programs. If a C-function, structure, datatype,
556 ** or constant definition does not appear in this file, then it is
557 ** not a published API of SQLite, is subject to change without
558 ** notice, and should not be referenced by programs that use SQLite.
560 ** Some of the definitions that are in this file are marked as
561 ** "experimental". Experimental interfaces are normally new
562 ** features recently added to SQLite. We do not anticipate changes
563 ** to experimental interfaces but reserve the right to make minor changes
564 ** if experience from use "in the wild" suggest such changes are prudent.
566 ** The official C-language API documentation for SQLite is derived
567 ** from comments in this file. This file is the authoritative source
568 ** on how SQLite interfaces are suppose to operate.
570 ** The name of this file under configuration management is "sqlite.h.in".
571 ** The makefile makes some minor changes to this file (such as inserting
572 ** the version number) and changes its name to "sqlite3.h" as
573 ** part of the build process.
575 #ifndef _SQLITE3_H_
576 #define _SQLITE3_H_
577 #include <stdarg.h> /* Needed for the definition of va_list */
580 ** Make sure we can call this stuff from C++.
582 #if 0
583 extern "C" {
584 #endif
588 ** Add the ability to override 'extern'
590 #ifndef SQLITE_EXTERN
591 # define SQLITE_EXTERN extern
592 #endif
594 #ifndef SQLITE_API
595 # define SQLITE_API
596 #endif
600 ** These no-op macros are used in front of interfaces to mark those
601 ** interfaces as either deprecated or experimental. New applications
602 ** should not use deprecated interfaces - they are support for backwards
603 ** compatibility only. Application writers should be aware that
604 ** experimental interfaces are subject to change in point releases.
606 ** These macros used to resolve to various kinds of compiler magic that
607 ** would generate warning messages when they were used. But that
608 ** compiler magic ended up generating such a flurry of bug reports
609 ** that we have taken it all out and gone back to using simple
610 ** noop macros.
612 #define SQLITE_DEPRECATED
613 #define SQLITE_EXPERIMENTAL
616 ** Ensure these symbols were not defined by some previous header file.
618 #ifdef SQLITE_VERSION
619 # undef SQLITE_VERSION
620 #endif
621 #ifdef SQLITE_VERSION_NUMBER
622 # undef SQLITE_VERSION_NUMBER
623 #endif
626 ** CAPI3REF: Compile-Time Library Version Numbers
628 ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
629 ** evaluates to a string literal that is the SQLite version in the
630 ** format "X.Y.Z" where X is the major version number (always 3 for
631 ** SQLite3) and Y is the minor version number and Z is the release number.)^
632 ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
633 ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
634 ** numbers used in [SQLITE_VERSION].)^
635 ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
636 ** be larger than the release from which it is derived. Either Y will
637 ** be held constant and Z will be incremented or else Y will be incremented
638 ** and Z will be reset to zero.
640 ** Since version 3.6.18, SQLite source code has been stored in the
641 ** <a href="http://www.fossil-scm.org/">Fossil configuration management
642 ** system</a>. ^The SQLITE_SOURCE_ID macro evaluates to
643 ** a string which identifies a particular check-in of SQLite
644 ** within its configuration management system. ^The SQLITE_SOURCE_ID
645 ** string contains the date and time of the check-in (UTC) and an SHA1
646 ** hash of the entire source tree.
648 ** See also: [sqlite3_libversion()],
649 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
650 ** [sqlite_version()] and [sqlite_source_id()].
652 #define SQLITE_VERSION "3.7.9"
653 #define SQLITE_VERSION_NUMBER 3007009
654 #define SQLITE_SOURCE_ID "2011-10-29 19:25:08 5b82ec6fbbd2f4195ad06dd911de3817373ad5bf"
657 ** CAPI3REF: Run-Time Library Version Numbers
658 ** KEYWORDS: sqlite3_version, sqlite3_sourceid
660 ** These interfaces provide the same information as the [SQLITE_VERSION],
661 ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
662 ** but are associated with the library instead of the header file. ^(Cautious
663 ** programmers might include assert() statements in their application to
664 ** verify that values returned by these interfaces match the macros in
665 ** the header, and thus insure that the application is
666 ** compiled with matching library and header files.
668 ** <blockquote><pre>
669 ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
670 ** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
671 ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
672 ** </pre></blockquote>)^
674 ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
675 ** macro. ^The sqlite3_libversion() function returns a pointer to the
676 ** to the sqlite3_version[] string constant. The sqlite3_libversion()
677 ** function is provided for use in DLLs since DLL users usually do not have
678 ** direct access to string constants within the DLL. ^The
679 ** sqlite3_libversion_number() function returns an integer equal to
680 ** [SQLITE_VERSION_NUMBER]. ^The sqlite3_sourceid() function returns
681 ** a pointer to a string constant whose value is the same as the
682 ** [SQLITE_SOURCE_ID] C preprocessor macro.
684 ** See also: [sqlite_version()] and [sqlite_source_id()].
686 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
687 SQLITE_API const char *sqlite3_libversion(void);
688 SQLITE_API const char *sqlite3_sourceid(void);
689 SQLITE_API int sqlite3_libversion_number(void);
692 ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
694 ** ^The sqlite3_compileoption_used() function returns 0 or 1
695 ** indicating whether the specified option was defined at
696 ** compile time. ^The SQLITE_ prefix may be omitted from the
697 ** option name passed to sqlite3_compileoption_used().
699 ** ^The sqlite3_compileoption_get() function allows iterating
700 ** over the list of options that were defined at compile time by
701 ** returning the N-th compile time option string. ^If N is out of range,
702 ** sqlite3_compileoption_get() returns a NULL pointer. ^The SQLITE_
703 ** prefix is omitted from any strings returned by
704 ** sqlite3_compileoption_get().
706 ** ^Support for the diagnostic functions sqlite3_compileoption_used()
707 ** and sqlite3_compileoption_get() may be omitted by specifying the
708 ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
710 ** See also: SQL functions [sqlite_compileoption_used()] and
711 ** [sqlite_compileoption_get()] and the [compile_options pragma].
713 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
714 SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
715 SQLITE_API const char *sqlite3_compileoption_get(int N);
716 #endif
719 ** CAPI3REF: Test To See If The Library Is Threadsafe
721 ** ^The sqlite3_threadsafe() function returns zero if and only if
722 ** SQLite was compiled mutexing code omitted due to the
723 ** [SQLITE_THREADSAFE] compile-time option being set to 0.
725 ** SQLite can be compiled with or without mutexes. When
726 ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
727 ** are enabled and SQLite is threadsafe. When the
728 ** [SQLITE_THREADSAFE] macro is 0,
729 ** the mutexes are omitted. Without the mutexes, it is not safe
730 ** to use SQLite concurrently from more than one thread.
732 ** Enabling mutexes incurs a measurable performance penalty.
733 ** So if speed is of utmost importance, it makes sense to disable
734 ** the mutexes. But for maximum safety, mutexes should be enabled.
735 ** ^The default behavior is for mutexes to be enabled.
737 ** This interface can be used by an application to make sure that the
738 ** version of SQLite that it is linking against was compiled with
739 ** the desired setting of the [SQLITE_THREADSAFE] macro.
741 ** This interface only reports on the compile-time mutex setting
742 ** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with
743 ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
744 ** can be fully or partially disabled using a call to [sqlite3_config()]
745 ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
746 ** or [SQLITE_CONFIG_MUTEX]. ^(The return value of the
747 ** sqlite3_threadsafe() function shows only the compile-time setting of
748 ** thread safety, not any run-time changes to that setting made by
749 ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
750 ** is unchanged by calls to sqlite3_config().)^
752 ** See the [threading mode] documentation for additional information.
754 SQLITE_API int sqlite3_threadsafe(void);
757 ** CAPI3REF: Database Connection Handle
758 ** KEYWORDS: {database connection} {database connections}
760 ** Each open SQLite database is represented by a pointer to an instance of
761 ** the opaque structure named "sqlite3". It is useful to think of an sqlite3
762 ** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and
763 ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
764 ** is its destructor. There are many other interfaces (such as
765 ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
766 ** [sqlite3_busy_timeout()] to name but three) that are methods on an
767 ** sqlite3 object.
769 typedef struct sqlite3 sqlite3;
772 ** CAPI3REF: 64-Bit Integer Types
773 ** KEYWORDS: sqlite_int64 sqlite_uint64
775 ** Because there is no cross-platform way to specify 64-bit integer types
776 ** SQLite includes typedefs for 64-bit signed and unsigned integers.
778 ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
779 ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
780 ** compatibility only.
782 ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
783 ** between -9223372036854775808 and +9223372036854775807 inclusive. ^The
784 ** sqlite3_uint64 and sqlite_uint64 types can store integer values
785 ** between 0 and +18446744073709551615 inclusive.
787 #ifdef SQLITE_INT64_TYPE
788 typedef SQLITE_INT64_TYPE sqlite_int64;
789 typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
790 #elif defined(_MSC_VER) || defined(__BORLANDC__)
791 typedef __int64 sqlite_int64;
792 typedef unsigned __int64 sqlite_uint64;
793 #else
794 typedef long long int sqlite_int64;
795 typedef unsigned long long int sqlite_uint64;
796 #endif
797 typedef sqlite_int64 sqlite3_int64;
798 typedef sqlite_uint64 sqlite3_uint64;
801 ** If compiling for a processor that lacks floating point support,
802 ** substitute integer for floating-point.
804 #ifdef SQLITE_OMIT_FLOATING_POINT
805 # define double sqlite3_int64
806 #endif
809 ** CAPI3REF: Closing A Database Connection
811 ** ^The sqlite3_close() routine is the destructor for the [sqlite3] object.
812 ** ^Calls to sqlite3_close() return SQLITE_OK if the [sqlite3] object is
813 ** successfully destroyed and all associated resources are deallocated.
815 ** Applications must [sqlite3_finalize | finalize] all [prepared statements]
816 ** and [sqlite3_blob_close | close] all [BLOB handles] associated with
817 ** the [sqlite3] object prior to attempting to close the object. ^If
818 ** sqlite3_close() is called on a [database connection] that still has
819 ** outstanding [prepared statements] or [BLOB handles], then it returns
820 ** SQLITE_BUSY.
822 ** ^If [sqlite3_close()] is invoked while a transaction is open,
823 ** the transaction is automatically rolled back.
825 ** The C parameter to [sqlite3_close(C)] must be either a NULL
826 ** pointer or an [sqlite3] object pointer obtained
827 ** from [sqlite3_open()], [sqlite3_open16()], or
828 ** [sqlite3_open_v2()], and not previously closed.
829 ** ^Calling sqlite3_close() with a NULL pointer argument is a
830 ** harmless no-op.
832 SQLITE_API int sqlite3_close(sqlite3 *);
835 ** The type for a callback function.
836 ** This is legacy and deprecated. It is included for historical
837 ** compatibility and is not documented.
839 typedef int (*sqlite3_callback)(void*,int,char**, char**);
842 ** CAPI3REF: One-Step Query Execution Interface
844 ** The sqlite3_exec() interface is a convenience wrapper around
845 ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
846 ** that allows an application to run multiple statements of SQL
847 ** without having to use a lot of C code.
849 ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
850 ** semicolon-separate SQL statements passed into its 2nd argument,
851 ** in the context of the [database connection] passed in as its 1st
852 ** argument. ^If the callback function of the 3rd argument to
853 ** sqlite3_exec() is not NULL, then it is invoked for each result row
854 ** coming out of the evaluated SQL statements. ^The 4th argument to
855 ** sqlite3_exec() is relayed through to the 1st argument of each
856 ** callback invocation. ^If the callback pointer to sqlite3_exec()
857 ** is NULL, then no callback is ever invoked and result rows are
858 ** ignored.
860 ** ^If an error occurs while evaluating the SQL statements passed into
861 ** sqlite3_exec(), then execution of the current statement stops and
862 ** subsequent statements are skipped. ^If the 5th parameter to sqlite3_exec()
863 ** is not NULL then any error message is written into memory obtained
864 ** from [sqlite3_malloc()] and passed back through the 5th parameter.
865 ** To avoid memory leaks, the application should invoke [sqlite3_free()]
866 ** on error message strings returned through the 5th parameter of
867 ** of sqlite3_exec() after the error message string is no longer needed.
868 ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
869 ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
870 ** NULL before returning.
872 ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
873 ** routine returns SQLITE_ABORT without invoking the callback again and
874 ** without running any subsequent SQL statements.
876 ** ^The 2nd argument to the sqlite3_exec() callback function is the
877 ** number of columns in the result. ^The 3rd argument to the sqlite3_exec()
878 ** callback is an array of pointers to strings obtained as if from
879 ** [sqlite3_column_text()], one for each column. ^If an element of a
880 ** result row is NULL then the corresponding string pointer for the
881 ** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the
882 ** sqlite3_exec() callback is an array of pointers to strings where each
883 ** entry represents the name of corresponding result column as obtained
884 ** from [sqlite3_column_name()].
886 ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
887 ** to an empty string, or a pointer that contains only whitespace and/or
888 ** SQL comments, then no SQL statements are evaluated and the database
889 ** is not changed.
891 ** Restrictions:
893 ** <ul>
894 ** <li> The application must insure that the 1st parameter to sqlite3_exec()
895 ** is a valid and open [database connection].
896 ** <li> The application must not close [database connection] specified by
897 ** the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
898 ** <li> The application must not modify the SQL statement text passed into
899 ** the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
900 ** </ul>
902 SQLITE_API int sqlite3_exec(
903 sqlite3*, /* An open database */
904 const char *sql, /* SQL to be evaluated */
905 int (*callback)(void*,int,char**,char**), /* Callback function */
906 void *, /* 1st argument to callback */
907 char **errmsg /* Error msg written here */
911 ** CAPI3REF: Result Codes
912 ** KEYWORDS: SQLITE_OK {error code} {error codes}
913 ** KEYWORDS: {result code} {result codes}
915 ** Many SQLite functions return an integer result code from the set shown
916 ** here in order to indicates success or failure.
918 ** New error codes may be added in future versions of SQLite.
920 ** See also: [SQLITE_IOERR_READ | extended result codes],
921 ** [sqlite3_vtab_on_conflict()] [SQLITE_ROLLBACK | 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_IOERR_SHMMAP (SQLITE_IOERR | (21<<8))
999 #define SQLITE_IOERR_SEEK (SQLITE_IOERR | (22<<8))
1000 #define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8))
1001 #define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8))
1002 #define SQLITE_CANTOPEN_NOTEMPDIR (SQLITE_CANTOPEN | (1<<8))
1003 #define SQLITE_CORRUPT_VTAB (SQLITE_CORRUPT | (1<<8))
1004 #define SQLITE_READONLY_RECOVERY (SQLITE_READONLY | (1<<8))
1005 #define SQLITE_READONLY_CANTLOCK (SQLITE_READONLY | (2<<8))
1008 ** CAPI3REF: Flags For File Open Operations
1010 ** These bit values are intended for use in the
1011 ** 3rd parameter to the [sqlite3_open_v2()] interface and
1012 ** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
1014 #define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */
1015 #define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */
1016 #define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */
1017 #define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */
1018 #define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */
1019 #define SQLITE_OPEN_AUTOPROXY 0x00000020 /* VFS only */
1020 #define SQLITE_OPEN_URI 0x00000040 /* Ok for sqlite3_open_v2() */
1021 #define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */
1022 #define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */
1023 #define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */
1024 #define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */
1025 #define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */
1026 #define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */
1027 #define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */
1028 #define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */
1029 #define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */
1030 #define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for sqlite3_open_v2() */
1031 #define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for sqlite3_open_v2() */
1032 #define SQLITE_OPEN_WAL 0x00080000 /* VFS only */
1034 /* Reserved: 0x00F00000 */
1037 ** CAPI3REF: Device Characteristics
1039 ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
1040 ** object returns an integer which is a vector of the these
1041 ** bit values expressing I/O characteristics of the mass storage
1042 ** device that holds the file that the [sqlite3_io_methods]
1043 ** refers to.
1045 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
1046 ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
1047 ** mean that writes of blocks that are nnn bytes in size and
1048 ** are aligned to an address which is an integer multiple of
1049 ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
1050 ** that when data is appended to a file, the data is appended
1051 ** first then the size of the file is extended, never the other
1052 ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
1053 ** information is written to disk in the same order as calls
1054 ** to xWrite().
1056 #define SQLITE_IOCAP_ATOMIC 0x00000001
1057 #define SQLITE_IOCAP_ATOMIC512 0x00000002
1058 #define SQLITE_IOCAP_ATOMIC1K 0x00000004
1059 #define SQLITE_IOCAP_ATOMIC2K 0x00000008
1060 #define SQLITE_IOCAP_ATOMIC4K 0x00000010
1061 #define SQLITE_IOCAP_ATOMIC8K 0x00000020
1062 #define SQLITE_IOCAP_ATOMIC16K 0x00000040
1063 #define SQLITE_IOCAP_ATOMIC32K 0x00000080
1064 #define SQLITE_IOCAP_ATOMIC64K 0x00000100
1065 #define SQLITE_IOCAP_SAFE_APPEND 0x00000200
1066 #define SQLITE_IOCAP_SEQUENTIAL 0x00000400
1067 #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN 0x00000800
1070 ** CAPI3REF: File Locking Levels
1072 ** SQLite uses one of these integer values as the second
1073 ** argument to calls it makes to the xLock() and xUnlock() methods
1074 ** of an [sqlite3_io_methods] object.
1076 #define SQLITE_LOCK_NONE 0
1077 #define SQLITE_LOCK_SHARED 1
1078 #define SQLITE_LOCK_RESERVED 2
1079 #define SQLITE_LOCK_PENDING 3
1080 #define SQLITE_LOCK_EXCLUSIVE 4
1083 ** CAPI3REF: Synchronization Type Flags
1085 ** When SQLite invokes the xSync() method of an
1086 ** [sqlite3_io_methods] object it uses a combination of
1087 ** these integer values as the second argument.
1089 ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
1090 ** sync operation only needs to flush data to mass storage. Inode
1091 ** information need not be flushed. If the lower four bits of the flag
1092 ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
1093 ** If the lower four bits equal SQLITE_SYNC_FULL, that means
1094 ** to use Mac OS X style fullsync instead of fsync().
1096 ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
1097 ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
1098 ** settings. The [synchronous pragma] determines when calls to the
1099 ** xSync VFS method occur and applies uniformly across all platforms.
1100 ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
1101 ** energetic or rigorous or forceful the sync operations are and
1102 ** only make a difference on Mac OSX for the default SQLite code.
1103 ** (Third-party VFS implementations might also make the distinction
1104 ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
1105 ** operating systems natively supported by SQLite, only Mac OSX
1106 ** cares about the difference.)
1108 #define SQLITE_SYNC_NORMAL 0x00002
1109 #define SQLITE_SYNC_FULL 0x00003
1110 #define SQLITE_SYNC_DATAONLY 0x00010
1113 ** CAPI3REF: OS Interface Open File Handle
1115 ** An [sqlite3_file] object represents an open file in the
1116 ** [sqlite3_vfs | OS interface layer]. Individual OS interface
1117 ** implementations will
1118 ** want to subclass this object by appending additional fields
1119 ** for their own use. The pMethods entry is a pointer to an
1120 ** [sqlite3_io_methods] object that defines methods for performing
1121 ** I/O operations on the open file.
1123 typedef struct sqlite3_file sqlite3_file;
1124 struct sqlite3_file {
1125 const struct sqlite3_io_methods *pMethods; /* Methods for an open file */
1129 ** CAPI3REF: OS Interface File Virtual Methods Object
1131 ** Every file opened by the [sqlite3_vfs.xOpen] method populates an
1132 ** [sqlite3_file] object (or, more commonly, a subclass of the
1133 ** [sqlite3_file] object) with a pointer to an instance of this object.
1134 ** This object defines the methods used to perform various operations
1135 ** against the open file represented by the [sqlite3_file] object.
1137 ** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element
1138 ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
1139 ** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed. The
1140 ** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
1141 ** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
1142 ** to NULL.
1144 ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
1145 ** [SQLITE_SYNC_FULL]. The first choice is the normal fsync().
1146 ** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY]
1147 ** flag may be ORed in to indicate that only the data of the file
1148 ** and not its inode needs to be synced.
1150 ** The integer values to xLock() and xUnlock() are one of
1151 ** <ul>
1152 ** <li> [SQLITE_LOCK_NONE],
1153 ** <li> [SQLITE_LOCK_SHARED],
1154 ** <li> [SQLITE_LOCK_RESERVED],
1155 ** <li> [SQLITE_LOCK_PENDING], or
1156 ** <li> [SQLITE_LOCK_EXCLUSIVE].
1157 ** </ul>
1158 ** xLock() increases the lock. xUnlock() decreases the lock.
1159 ** The xCheckReservedLock() method checks whether any database connection,
1160 ** either in this process or in some other process, is holding a RESERVED,
1161 ** PENDING, or EXCLUSIVE lock on the file. It returns true
1162 ** if such a lock exists and false otherwise.
1164 ** The xFileControl() method is a generic interface that allows custom
1165 ** VFS implementations to directly control an open file using the
1166 ** [sqlite3_file_control()] interface. The second "op" argument is an
1167 ** integer opcode. The third argument is a generic pointer intended to
1168 ** point to a structure that may contain arguments or space in which to
1169 ** write return values. Potential uses for xFileControl() might be
1170 ** functions to enable blocking locks with timeouts, to change the
1171 ** locking strategy (for example to use dot-file locks), to inquire
1172 ** about the status of a lock, or to break stale locks. The SQLite
1173 ** core reserves all opcodes less than 100 for its own use.
1174 ** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
1175 ** Applications that define a custom xFileControl method should use opcodes
1176 ** greater than 100 to avoid conflicts. VFS implementations should
1177 ** return [SQLITE_NOTFOUND] for file control opcodes that they do not
1178 ** recognize.
1180 ** The xSectorSize() method returns the sector size of the
1181 ** device that underlies the file. The sector size is the
1182 ** minimum write that can be performed without disturbing
1183 ** other bytes in the file. The xDeviceCharacteristics()
1184 ** method returns a bit vector describing behaviors of the
1185 ** underlying device:
1187 ** <ul>
1188 ** <li> [SQLITE_IOCAP_ATOMIC]
1189 ** <li> [SQLITE_IOCAP_ATOMIC512]
1190 ** <li> [SQLITE_IOCAP_ATOMIC1K]
1191 ** <li> [SQLITE_IOCAP_ATOMIC2K]
1192 ** <li> [SQLITE_IOCAP_ATOMIC4K]
1193 ** <li> [SQLITE_IOCAP_ATOMIC8K]
1194 ** <li> [SQLITE_IOCAP_ATOMIC16K]
1195 ** <li> [SQLITE_IOCAP_ATOMIC32K]
1196 ** <li> [SQLITE_IOCAP_ATOMIC64K]
1197 ** <li> [SQLITE_IOCAP_SAFE_APPEND]
1198 ** <li> [SQLITE_IOCAP_SEQUENTIAL]
1199 ** </ul>
1201 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
1202 ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
1203 ** mean that writes of blocks that are nnn bytes in size and
1204 ** are aligned to an address which is an integer multiple of
1205 ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
1206 ** that when data is appended to a file, the data is appended
1207 ** first then the size of the file is extended, never the other
1208 ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
1209 ** information is written to disk in the same order as calls
1210 ** to xWrite().
1212 ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
1213 ** in the unread portions of the buffer with zeros. A VFS that
1214 ** fails to zero-fill short reads might seem to work. However,
1215 ** failure to zero-fill short reads will eventually lead to
1216 ** database corruption.
1218 typedef struct sqlite3_io_methods sqlite3_io_methods;
1219 struct sqlite3_io_methods {
1220 int iVersion;
1221 int (*xClose)(sqlite3_file*);
1222 int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
1223 int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
1224 int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
1225 int (*xSync)(sqlite3_file*, int flags);
1226 int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
1227 int (*xLock)(sqlite3_file*, int);
1228 int (*xUnlock)(sqlite3_file*, int);
1229 int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
1230 int (*xFileControl)(sqlite3_file*, int op, void *pArg);
1231 int (*xSectorSize)(sqlite3_file*);
1232 int (*xDeviceCharacteristics)(sqlite3_file*);
1233 /* Methods above are valid for version 1 */
1234 int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
1235 int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
1236 void (*xShmBarrier)(sqlite3_file*);
1237 int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
1238 /* Methods above are valid for version 2 */
1239 /* Additional methods may be added in future releases */
1243 ** CAPI3REF: Standard File Control Opcodes
1245 ** These integer constants are opcodes for the xFileControl method
1246 ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
1247 ** interface.
1249 ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This
1250 ** opcode causes the xFileControl method to write the current state of
1251 ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
1252 ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
1253 ** into an integer that the pArg argument points to. This capability
1254 ** is used during testing and only needs to be supported when SQLITE_TEST
1255 ** is defined.
1257 ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
1258 ** layer a hint of how large the database file will grow to be during the
1259 ** current transaction. This hint is not guaranteed to be accurate but it
1260 ** is often close. The underlying VFS might choose to preallocate database
1261 ** file space based on this hint in order to help writes to the database
1262 ** file run faster.
1264 ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
1265 ** extends and truncates the database file in chunks of a size specified
1266 ** by the user. The fourth argument to [sqlite3_file_control()] should
1267 ** point to an integer (type int) containing the new chunk-size to use
1268 ** for the nominated database. Allocating database file space in large
1269 ** chunks (say 1MB at a time), may reduce file-system fragmentation and
1270 ** improve performance on some systems.
1272 ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
1273 ** to the [sqlite3_file] object associated with a particular database
1274 ** connection. See the [sqlite3_file_control()] documentation for
1275 ** additional information.
1277 ** ^(The [SQLITE_FCNTL_SYNC_OMITTED] opcode is generated internally by
1278 ** SQLite and sent to all VFSes in place of a call to the xSync method
1279 ** when the database connection has [PRAGMA synchronous] set to OFF.)^
1280 ** Some specialized VFSes need this signal in order to operate correctly
1281 ** when [PRAGMA synchronous | PRAGMA synchronous=OFF] is set, but most
1282 ** VFSes do not need this signal and should silently ignore this opcode.
1283 ** Applications should not call [sqlite3_file_control()] with this
1284 ** opcode as doing so may disrupt the operation of the specialized VFSes
1285 ** that do require it.
1287 ** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
1288 ** retry counts and intervals for certain disk I/O operations for the
1289 ** windows [VFS] in order to work to provide robustness against
1290 ** anti-virus programs. By default, the windows VFS will retry file read,
1291 ** file write, and file delete opertions up to 10 times, with a delay
1292 ** of 25 milliseconds before the first retry and with the delay increasing
1293 ** by an additional 25 milliseconds with each subsequent retry. This
1294 ** opcode allows those to values (10 retries and 25 milliseconds of delay)
1295 ** to be adjusted. The values are changed for all database connections
1296 ** within the same process. The argument is a pointer to an array of two
1297 ** integers where the first integer i the new retry count and the second
1298 ** integer is the delay. If either integer is negative, then the setting
1299 ** is not changed but instead the prior value of that setting is written
1300 ** into the array entry, allowing the current retry settings to be
1301 ** interrogated. The zDbName parameter is ignored.
1303 ** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
1304 ** persistent [WAL | Write AHead Log] setting. By default, the auxiliary
1305 ** write ahead log and shared memory files used for transaction control
1306 ** are automatically deleted when the latest connection to the database
1307 ** closes. Setting persistent WAL mode causes those files to persist after
1308 ** close. Persisting the files is useful when other processes that do not
1309 ** have write permission on the directory containing the database file want
1310 ** to read the database file, as the WAL and shared memory files must exist
1311 ** in order for the database to be readable. The fourth parameter to
1312 ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
1313 ** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
1314 ** WAL mode. If the integer is -1, then it is overwritten with the current
1315 ** WAL persistence setting.
1317 ** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
1318 ** a write transaction to indicate that, unless it is rolled back for some
1319 ** reason, the entire database file will be overwritten by the current
1320 ** transaction. This is used by VACUUM operations.
1322 #define SQLITE_FCNTL_LOCKSTATE 1
1323 #define SQLITE_GET_LOCKPROXYFILE 2
1324 #define SQLITE_SET_LOCKPROXYFILE 3
1325 #define SQLITE_LAST_ERRNO 4
1326 #define SQLITE_FCNTL_SIZE_HINT 5
1327 #define SQLITE_FCNTL_CHUNK_SIZE 6
1328 #define SQLITE_FCNTL_FILE_POINTER 7
1329 #define SQLITE_FCNTL_SYNC_OMITTED 8
1330 #define SQLITE_FCNTL_WIN32_AV_RETRY 9
1331 #define SQLITE_FCNTL_PERSIST_WAL 10
1332 #define SQLITE_FCNTL_OVERWRITE 11
1335 ** CAPI3REF: Mutex Handle
1337 ** The mutex module within SQLite defines [sqlite3_mutex] to be an
1338 ** abstract type for a mutex object. The SQLite core never looks
1339 ** at the internal representation of an [sqlite3_mutex]. It only
1340 ** deals with pointers to the [sqlite3_mutex] object.
1342 ** Mutexes are created using [sqlite3_mutex_alloc()].
1344 typedef struct sqlite3_mutex sqlite3_mutex;
1347 ** CAPI3REF: OS Interface Object
1349 ** An instance of the sqlite3_vfs object defines the interface between
1350 ** the SQLite core and the underlying operating system. The "vfs"
1351 ** in the name of the object stands for "virtual file system". See
1352 ** the [VFS | VFS documentation] for further information.
1354 ** The value of the iVersion field is initially 1 but may be larger in
1355 ** future versions of SQLite. Additional fields may be appended to this
1356 ** object when the iVersion value is increased. Note that the structure
1357 ** of the sqlite3_vfs object changes in the transaction between
1358 ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
1359 ** modified.
1361 ** The szOsFile field is the size of the subclassed [sqlite3_file]
1362 ** structure used by this VFS. mxPathname is the maximum length of
1363 ** a pathname in this VFS.
1365 ** Registered sqlite3_vfs objects are kept on a linked list formed by
1366 ** the pNext pointer. The [sqlite3_vfs_register()]
1367 ** and [sqlite3_vfs_unregister()] interfaces manage this list
1368 ** in a thread-safe way. The [sqlite3_vfs_find()] interface
1369 ** searches the list. Neither the application code nor the VFS
1370 ** implementation should use the pNext pointer.
1372 ** The pNext field is the only field in the sqlite3_vfs
1373 ** structure that SQLite will ever modify. SQLite will only access
1374 ** or modify this field while holding a particular static mutex.
1375 ** The application should never modify anything within the sqlite3_vfs
1376 ** object once the object has been registered.
1378 ** The zName field holds the name of the VFS module. The name must
1379 ** be unique across all VFS modules.
1381 ** [[sqlite3_vfs.xOpen]]
1382 ** ^SQLite guarantees that the zFilename parameter to xOpen
1383 ** is either a NULL pointer or string obtained
1384 ** from xFullPathname() with an optional suffix added.
1385 ** ^If a suffix is added to the zFilename parameter, it will
1386 ** consist of a single "-" character followed by no more than
1387 ** 10 alphanumeric and/or "-" characters.
1388 ** ^SQLite further guarantees that
1389 ** the string will be valid and unchanged until xClose() is
1390 ** called. Because of the previous sentence,
1391 ** the [sqlite3_file] can safely store a pointer to the
1392 ** filename if it needs to remember the filename for some reason.
1393 ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
1394 ** must invent its own temporary name for the file. ^Whenever the
1395 ** xFilename parameter is NULL it will also be the case that the
1396 ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
1398 ** The flags argument to xOpen() includes all bits set in
1399 ** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()]
1400 ** or [sqlite3_open16()] is used, then flags includes at least
1401 ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
1402 ** If xOpen() opens a file read-only then it sets *pOutFlags to
1403 ** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set.
1405 ** ^(SQLite will also add one of the following flags to the xOpen()
1406 ** call, depending on the object being opened:
1408 ** <ul>
1409 ** <li> [SQLITE_OPEN_MAIN_DB]
1410 ** <li> [SQLITE_OPEN_MAIN_JOURNAL]
1411 ** <li> [SQLITE_OPEN_TEMP_DB]
1412 ** <li> [SQLITE_OPEN_TEMP_JOURNAL]
1413 ** <li> [SQLITE_OPEN_TRANSIENT_DB]
1414 ** <li> [SQLITE_OPEN_SUBJOURNAL]
1415 ** <li> [SQLITE_OPEN_MASTER_JOURNAL]
1416 ** <li> [SQLITE_OPEN_WAL]
1417 ** </ul>)^
1419 ** The file I/O implementation can use the object type flags to
1420 ** change the way it deals with files. For example, an application
1421 ** that does not care about crash recovery or rollback might make
1422 ** the open of a journal file a no-op. Writes to this journal would
1423 ** also be no-ops, and any attempt to read the journal would return
1424 ** SQLITE_IOERR. Or the implementation might recognize that a database
1425 ** file will be doing page-aligned sector reads and writes in a random
1426 ** order and set up its I/O subsystem accordingly.
1428 ** SQLite might also add one of the following flags to the xOpen method:
1430 ** <ul>
1431 ** <li> [SQLITE_OPEN_DELETEONCLOSE]
1432 ** <li> [SQLITE_OPEN_EXCLUSIVE]
1433 ** </ul>
1435 ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
1436 ** deleted when it is closed. ^The [SQLITE_OPEN_DELETEONCLOSE]
1437 ** will be set for TEMP databases and their journals, transient
1438 ** databases, and subjournals.
1440 ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
1441 ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
1442 ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
1443 ** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
1444 ** SQLITE_OPEN_CREATE, is used to indicate that file should always
1445 ** be created, and that it is an error if it already exists.
1446 ** It is <i>not</i> used to indicate the file should be opened
1447 ** for exclusive access.
1449 ** ^At least szOsFile bytes of memory are allocated by SQLite
1450 ** to hold the [sqlite3_file] structure passed as the third
1451 ** argument to xOpen. The xOpen method does not have to
1452 ** allocate the structure; it should just fill it in. Note that
1453 ** the xOpen method must set the sqlite3_file.pMethods to either
1454 ** a valid [sqlite3_io_methods] object or to NULL. xOpen must do
1455 ** this even if the open fails. SQLite expects that the sqlite3_file.pMethods
1456 ** element will be valid after xOpen returns regardless of the success
1457 ** or failure of the xOpen call.
1459 ** [[sqlite3_vfs.xAccess]]
1460 ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
1461 ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
1462 ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
1463 ** to test whether a file is at least readable. The file can be a
1464 ** directory.
1466 ** ^SQLite will always allocate at least mxPathname+1 bytes for the
1467 ** output buffer xFullPathname. The exact size of the output buffer
1468 ** is also passed as a parameter to both methods. If the output buffer
1469 ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
1470 ** handled as a fatal error by SQLite, vfs implementations should endeavor
1471 ** to prevent this by setting mxPathname to a sufficiently large value.
1473 ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
1474 ** interfaces are not strictly a part of the filesystem, but they are
1475 ** included in the VFS structure for completeness.
1476 ** The xRandomness() function attempts to return nBytes bytes
1477 ** of good-quality randomness into zOut. The return value is
1478 ** the actual number of bytes of randomness obtained.
1479 ** The xSleep() method causes the calling thread to sleep for at
1480 ** least the number of microseconds given. ^The xCurrentTime()
1481 ** method returns a Julian Day Number for the current date and time as
1482 ** a floating point value.
1483 ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
1484 ** Day Number multiplied by 86400000 (the number of milliseconds in
1485 ** a 24-hour day).
1486 ** ^SQLite will use the xCurrentTimeInt64() method to get the current
1487 ** date and time if that method is available (if iVersion is 2 or
1488 ** greater and the function pointer is not NULL) and will fall back
1489 ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
1491 ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
1492 ** are not used by the SQLite core. These optional interfaces are provided
1493 ** by some VFSes to facilitate testing of the VFS code. By overriding
1494 ** system calls with functions under its control, a test program can
1495 ** simulate faults and error conditions that would otherwise be difficult
1496 ** or impossible to induce. The set of system calls that can be overridden
1497 ** varies from one VFS to another, and from one version of the same VFS to the
1498 ** next. Applications that use these interfaces must be prepared for any
1499 ** or all of these interfaces to be NULL or for their behavior to change
1500 ** from one release to the next. Applications must not attempt to access
1501 ** any of these methods if the iVersion of the VFS is less than 3.
1503 typedef struct sqlite3_vfs sqlite3_vfs;
1504 typedef void (*sqlite3_syscall_ptr)(void);
1505 struct sqlite3_vfs {
1506 int iVersion; /* Structure version number (currently 3) */
1507 int szOsFile; /* Size of subclassed sqlite3_file */
1508 int mxPathname; /* Maximum file pathname length */
1509 sqlite3_vfs *pNext; /* Next registered VFS */
1510 const char *zName; /* Name of this virtual file system */
1511 void *pAppData; /* Pointer to application-specific data */
1512 int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
1513 int flags, int *pOutFlags);
1514 int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
1515 int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
1516 int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
1517 void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
1518 void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
1519 void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
1520 void (*xDlClose)(sqlite3_vfs*, void*);
1521 int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
1522 int (*xSleep)(sqlite3_vfs*, int microseconds);
1523 int (*xCurrentTime)(sqlite3_vfs*, double*);
1524 int (*xGetLastError)(sqlite3_vfs*, int, char *);
1526 ** The methods above are in version 1 of the sqlite_vfs object
1527 ** definition. Those that follow are added in version 2 or later
1529 int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
1531 ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
1532 ** Those below are for version 3 and greater.
1534 int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
1535 sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
1536 const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
1538 ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
1539 ** New fields may be appended in figure versions. The iVersion
1540 ** value will increment whenever this happens.
1545 ** CAPI3REF: Flags for the xAccess VFS method
1547 ** These integer constants can be used as the third parameter to
1548 ** the xAccess method of an [sqlite3_vfs] object. They determine
1549 ** what kind of permissions the xAccess method is looking for.
1550 ** With SQLITE_ACCESS_EXISTS, the xAccess method
1551 ** simply checks whether the file exists.
1552 ** With SQLITE_ACCESS_READWRITE, the xAccess method
1553 ** checks whether the named directory is both readable and writable
1554 ** (in other words, if files can be added, removed, and renamed within
1555 ** the directory).
1556 ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
1557 ** [temp_store_directory pragma], though this could change in a future
1558 ** release of SQLite.
1559 ** With SQLITE_ACCESS_READ, the xAccess method
1560 ** checks whether the file is readable. The SQLITE_ACCESS_READ constant is
1561 ** currently unused, though it might be used in a future release of
1562 ** SQLite.
1564 #define SQLITE_ACCESS_EXISTS 0
1565 #define SQLITE_ACCESS_READWRITE 1 /* Used by PRAGMA temp_store_directory */
1566 #define SQLITE_ACCESS_READ 2 /* Unused */
1569 ** CAPI3REF: Flags for the xShmLock VFS method
1571 ** These integer constants define the various locking operations
1572 ** allowed by the xShmLock method of [sqlite3_io_methods]. The
1573 ** following are the only legal combinations of flags to the
1574 ** xShmLock method:
1576 ** <ul>
1577 ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
1578 ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
1579 ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
1580 ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
1581 ** </ul>
1583 ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
1584 ** was given no the corresponding lock.
1586 ** The xShmLock method can transition between unlocked and SHARED or
1587 ** between unlocked and EXCLUSIVE. It cannot transition between SHARED
1588 ** and EXCLUSIVE.
1590 #define SQLITE_SHM_UNLOCK 1
1591 #define SQLITE_SHM_LOCK 2
1592 #define SQLITE_SHM_SHARED 4
1593 #define SQLITE_SHM_EXCLUSIVE 8
1596 ** CAPI3REF: Maximum xShmLock index
1598 ** The xShmLock method on [sqlite3_io_methods] may use values
1599 ** between 0 and this upper bound as its "offset" argument.
1600 ** The SQLite core will never attempt to acquire or release a
1601 ** lock outside of this range
1603 #define SQLITE_SHM_NLOCK 8
1607 ** CAPI3REF: Initialize The SQLite Library
1609 ** ^The sqlite3_initialize() routine initializes the
1610 ** SQLite library. ^The sqlite3_shutdown() routine
1611 ** deallocates any resources that were allocated by sqlite3_initialize().
1612 ** These routines are designed to aid in process initialization and
1613 ** shutdown on embedded systems. Workstation applications using
1614 ** SQLite normally do not need to invoke either of these routines.
1616 ** A call to sqlite3_initialize() is an "effective" call if it is
1617 ** the first time sqlite3_initialize() is invoked during the lifetime of
1618 ** the process, or if it is the first time sqlite3_initialize() is invoked
1619 ** following a call to sqlite3_shutdown(). ^(Only an effective call
1620 ** of sqlite3_initialize() does any initialization. All other calls
1621 ** are harmless no-ops.)^
1623 ** A call to sqlite3_shutdown() is an "effective" call if it is the first
1624 ** call to sqlite3_shutdown() since the last sqlite3_initialize(). ^(Only
1625 ** an effective call to sqlite3_shutdown() does any deinitialization.
1626 ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
1628 ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
1629 ** is not. The sqlite3_shutdown() interface must only be called from a
1630 ** single thread. All open [database connections] must be closed and all
1631 ** other SQLite resources must be deallocated prior to invoking
1632 ** sqlite3_shutdown().
1634 ** Among other things, ^sqlite3_initialize() will invoke
1635 ** sqlite3_os_init(). Similarly, ^sqlite3_shutdown()
1636 ** will invoke sqlite3_os_end().
1638 ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
1639 ** ^If for some reason, sqlite3_initialize() is unable to initialize
1640 ** the library (perhaps it is unable to allocate a needed resource such
1641 ** as a mutex) it returns an [error code] other than [SQLITE_OK].
1643 ** ^The sqlite3_initialize() routine is called internally by many other
1644 ** SQLite interfaces so that an application usually does not need to
1645 ** invoke sqlite3_initialize() directly. For example, [sqlite3_open()]
1646 ** calls sqlite3_initialize() so the SQLite library will be automatically
1647 ** initialized when [sqlite3_open()] is called if it has not be initialized
1648 ** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
1649 ** compile-time option, then the automatic calls to sqlite3_initialize()
1650 ** are omitted and the application must call sqlite3_initialize() directly
1651 ** prior to using any other SQLite interface. For maximum portability,
1652 ** it is recommended that applications always invoke sqlite3_initialize()
1653 ** directly prior to using any other SQLite interface. Future releases
1654 ** of SQLite may require this. In other words, the behavior exhibited
1655 ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
1656 ** default behavior in some future release of SQLite.
1658 ** The sqlite3_os_init() routine does operating-system specific
1659 ** initialization of the SQLite library. The sqlite3_os_end()
1660 ** routine undoes the effect of sqlite3_os_init(). Typical tasks
1661 ** performed by these routines include allocation or deallocation
1662 ** of static resources, initialization of global variables,
1663 ** setting up a default [sqlite3_vfs] module, or setting up
1664 ** a default configuration using [sqlite3_config()].
1666 ** The application should never invoke either sqlite3_os_init()
1667 ** or sqlite3_os_end() directly. The application should only invoke
1668 ** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init()
1669 ** interface is called automatically by sqlite3_initialize() and
1670 ** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate
1671 ** implementations for sqlite3_os_init() and sqlite3_os_end()
1672 ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
1673 ** When [custom builds | built for other platforms]
1674 ** (using the [SQLITE_OS_OTHER=1] compile-time
1675 ** option) the application must supply a suitable implementation for
1676 ** sqlite3_os_init() and sqlite3_os_end(). An application-supplied
1677 ** implementation of sqlite3_os_init() or sqlite3_os_end()
1678 ** must return [SQLITE_OK] on success and some other [error code] upon
1679 ** failure.
1681 SQLITE_API int sqlite3_initialize(void);
1682 SQLITE_API int sqlite3_shutdown(void);
1683 SQLITE_API int sqlite3_os_init(void);
1684 SQLITE_API int sqlite3_os_end(void);
1687 ** CAPI3REF: Configuring The SQLite Library
1689 ** The sqlite3_config() interface is used to make global configuration
1690 ** changes to SQLite in order to tune SQLite to the specific needs of
1691 ** the application. The default configuration is recommended for most
1692 ** applications and so this routine is usually not necessary. It is
1693 ** provided to support rare applications with unusual needs.
1695 ** The sqlite3_config() interface is not threadsafe. The application
1696 ** must insure that no other SQLite interfaces are invoked by other
1697 ** threads while sqlite3_config() is running. Furthermore, sqlite3_config()
1698 ** may only be invoked prior to library initialization using
1699 ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
1700 ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
1701 ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
1702 ** Note, however, that ^sqlite3_config() can be called as part of the
1703 ** implementation of an application-defined [sqlite3_os_init()].
1705 ** The first argument to sqlite3_config() is an integer
1706 ** [configuration option] that determines
1707 ** what property of SQLite is to be configured. Subsequent arguments
1708 ** vary depending on the [configuration option]
1709 ** in the first argument.
1711 ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
1712 ** ^If the option is unknown or SQLite is unable to set the option
1713 ** then this routine returns a non-zero [error code].
1715 SQLITE_API int sqlite3_config(int, ...);
1718 ** CAPI3REF: Configure database connections
1720 ** The sqlite3_db_config() interface is used to make configuration
1721 ** changes to a [database connection]. The interface is similar to
1722 ** [sqlite3_config()] except that the changes apply to a single
1723 ** [database connection] (specified in the first argument).
1725 ** The second argument to sqlite3_db_config(D,V,...) is the
1726 ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
1727 ** that indicates what aspect of the [database connection] is being configured.
1728 ** Subsequent arguments vary depending on the configuration verb.
1730 ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
1731 ** the call is considered successful.
1733 SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
1736 ** CAPI3REF: Memory Allocation Routines
1738 ** An instance of this object defines the interface between SQLite
1739 ** and low-level memory allocation routines.
1741 ** This object is used in only one place in the SQLite interface.
1742 ** A pointer to an instance of this object is the argument to
1743 ** [sqlite3_config()] when the configuration option is
1744 ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
1745 ** By creating an instance of this object
1746 ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
1747 ** during configuration, an application can specify an alternative
1748 ** memory allocation subsystem for SQLite to use for all of its
1749 ** dynamic memory needs.
1751 ** Note that SQLite comes with several [built-in memory allocators]
1752 ** that are perfectly adequate for the overwhelming majority of applications
1753 ** and that this object is only useful to a tiny minority of applications
1754 ** with specialized memory allocation requirements. This object is
1755 ** also used during testing of SQLite in order to specify an alternative
1756 ** memory allocator that simulates memory out-of-memory conditions in
1757 ** order to verify that SQLite recovers gracefully from such
1758 ** conditions.
1760 ** The xMalloc, xRealloc, and xFree methods must work like the
1761 ** malloc(), realloc() and free() functions from the standard C library.
1762 ** ^SQLite guarantees that the second argument to
1763 ** xRealloc is always a value returned by a prior call to xRoundup.
1765 ** xSize should return the allocated size of a memory allocation
1766 ** previously obtained from xMalloc or xRealloc. The allocated size
1767 ** is always at least as big as the requested size but may be larger.
1769 ** The xRoundup method returns what would be the allocated size of
1770 ** a memory allocation given a particular requested size. Most memory
1771 ** allocators round up memory allocations at least to the next multiple
1772 ** of 8. Some allocators round up to a larger multiple or to a power of 2.
1773 ** Every memory allocation request coming in through [sqlite3_malloc()]
1774 ** or [sqlite3_realloc()] first calls xRoundup. If xRoundup returns 0,
1775 ** that causes the corresponding memory allocation to fail.
1777 ** The xInit method initializes the memory allocator. (For example,
1778 ** it might allocate any require mutexes or initialize internal data
1779 ** structures. The xShutdown method is invoked (indirectly) by
1780 ** [sqlite3_shutdown()] and should deallocate any resources acquired
1781 ** by xInit. The pAppData pointer is used as the only parameter to
1782 ** xInit and xShutdown.
1784 ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
1785 ** the xInit method, so the xInit method need not be threadsafe. The
1786 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
1787 ** not need to be threadsafe either. For all other methods, SQLite
1788 ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
1789 ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
1790 ** it is by default) and so the methods are automatically serialized.
1791 ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
1792 ** methods must be threadsafe or else make their own arrangements for
1793 ** serialization.
1795 ** SQLite will never invoke xInit() more than once without an intervening
1796 ** call to xShutdown().
1798 typedef struct sqlite3_mem_methods sqlite3_mem_methods;
1799 struct sqlite3_mem_methods {
1800 void *(*xMalloc)(int); /* Memory allocation function */
1801 void (*xFree)(void*); /* Free a prior allocation */
1802 void *(*xRealloc)(void*,int); /* Resize an allocation */
1803 int (*xSize)(void*); /* Return the size of an allocation */
1804 int (*xRoundup)(int); /* Round up request size to allocation size */
1805 int (*xInit)(void*); /* Initialize the memory allocator */
1806 void (*xShutdown)(void*); /* Deinitialize the memory allocator */
1807 void *pAppData; /* Argument to xInit() and xShutdown() */
1811 ** CAPI3REF: Configuration Options
1812 ** KEYWORDS: {configuration option}
1814 ** These constants are the available integer configuration options that
1815 ** can be passed as the first argument to the [sqlite3_config()] interface.
1817 ** New configuration options may be added in future releases of SQLite.
1818 ** Existing configuration options might be discontinued. Applications
1819 ** should check the return code from [sqlite3_config()] to make sure that
1820 ** the call worked. The [sqlite3_config()] interface will return a
1821 ** non-zero [error code] if a discontinued or unsupported configuration option
1822 ** is invoked.
1824 ** <dl>
1825 ** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
1826 ** <dd>There are no arguments to this option. ^This option sets the
1827 ** [threading mode] to Single-thread. In other words, it disables
1828 ** all mutexing and puts SQLite into a mode where it can only be used
1829 ** by a single thread. ^If SQLite is compiled with
1830 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1831 ** it is not possible to change the [threading mode] from its default
1832 ** value of Single-thread and so [sqlite3_config()] will return
1833 ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
1834 ** configuration option.</dd>
1836 ** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
1837 ** <dd>There are no arguments to this option. ^This option sets the
1838 ** [threading mode] to Multi-thread. In other words, it disables
1839 ** mutexing on [database connection] and [prepared statement] objects.
1840 ** The application is responsible for serializing access to
1841 ** [database connections] and [prepared statements]. But other mutexes
1842 ** are enabled so that SQLite will be safe to use in a multi-threaded
1843 ** environment as long as no two threads attempt to use the same
1844 ** [database connection] at the same time. ^If SQLite is compiled with
1845 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1846 ** it is not possible to set the Multi-thread [threading mode] and
1847 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1848 ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
1850 ** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
1851 ** <dd>There are no arguments to this option. ^This option sets the
1852 ** [threading mode] to Serialized. In other words, this option enables
1853 ** all mutexes including the recursive
1854 ** mutexes on [database connection] and [prepared statement] objects.
1855 ** In this mode (which is the default when SQLite is compiled with
1856 ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
1857 ** to [database connections] and [prepared statements] so that the
1858 ** application is free to use the same [database connection] or the
1859 ** same [prepared statement] in different threads at the same time.
1860 ** ^If SQLite is compiled with
1861 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1862 ** it is not possible to set the Serialized [threading mode] and
1863 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1864 ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
1866 ** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
1867 ** <dd> ^(This option takes a single argument which is a pointer to an
1868 ** instance of the [sqlite3_mem_methods] structure. The argument specifies
1869 ** alternative low-level memory allocation routines to be used in place of
1870 ** the memory allocation routines built into SQLite.)^ ^SQLite makes
1871 ** its own private copy of the content of the [sqlite3_mem_methods] structure
1872 ** before the [sqlite3_config()] call returns.</dd>
1874 ** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
1875 ** <dd> ^(This option takes a single argument which is a pointer to an
1876 ** instance of the [sqlite3_mem_methods] structure. The [sqlite3_mem_methods]
1877 ** structure is filled with the currently defined memory allocation routines.)^
1878 ** This option can be used to overload the default memory allocation
1879 ** routines with a wrapper that simulations memory allocation failure or
1880 ** tracks memory usage, for example. </dd>
1882 ** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
1883 ** <dd> ^This option takes single argument of type int, interpreted as a
1884 ** boolean, which enables or disables the collection of memory allocation
1885 ** statistics. ^(When memory allocation statistics are disabled, the
1886 ** following SQLite interfaces become non-operational:
1887 ** <ul>
1888 ** <li> [sqlite3_memory_used()]
1889 ** <li> [sqlite3_memory_highwater()]
1890 ** <li> [sqlite3_soft_heap_limit64()]
1891 ** <li> [sqlite3_status()]
1892 ** </ul>)^
1893 ** ^Memory allocation statistics are enabled by default unless SQLite is
1894 ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
1895 ** allocation statistics are disabled by default.
1896 ** </dd>
1898 ** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
1899 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
1900 ** scratch memory. There are three arguments: A pointer an 8-byte
1901 ** aligned memory buffer from which the scratch allocations will be
1902 ** drawn, the size of each scratch allocation (sz),
1903 ** and the maximum number of scratch allocations (N). The sz
1904 ** argument must be a multiple of 16.
1905 ** The first argument must be a pointer to an 8-byte aligned buffer
1906 ** of at least sz*N bytes of memory.
1907 ** ^SQLite will use no more than two scratch buffers per thread. So
1908 ** N should be set to twice the expected maximum number of threads.
1909 ** ^SQLite will never require a scratch buffer that is more than 6
1910 ** times the database page size. ^If SQLite needs needs additional
1911 ** scratch memory beyond what is provided by this configuration option, then
1912 ** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>
1914 ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
1915 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
1916 ** the database page cache with the default page cache implementation.
1917 ** This configuration should not be used if an application-define page
1918 ** cache implementation is loaded using the SQLITE_CONFIG_PCACHE option.
1919 ** There are three arguments to this option: A pointer to 8-byte aligned
1920 ** memory, the size of each page buffer (sz), and the number of pages (N).
1921 ** The sz argument should be the size of the largest database page
1922 ** (a power of two between 512 and 32768) plus a little extra for each
1923 ** page header. ^The page header size is 20 to 40 bytes depending on
1924 ** the host architecture. ^It is harmless, apart from the wasted memory,
1925 ** to make sz a little too large. The first
1926 ** argument should point to an allocation of at least sz*N bytes of memory.
1927 ** ^SQLite will use the memory provided by the first argument to satisfy its
1928 ** memory needs for the first N pages that it adds to cache. ^If additional
1929 ** page cache memory is needed beyond what is provided by this option, then
1930 ** SQLite goes to [sqlite3_malloc()] for the additional storage space.
1931 ** The pointer in the first argument must
1932 ** be aligned to an 8-byte boundary or subsequent behavior of SQLite
1933 ** will be undefined.</dd>
1935 ** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
1936 ** <dd> ^This option specifies a static memory buffer that SQLite will use
1937 ** for all of its dynamic memory allocation needs beyond those provided
1938 ** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
1939 ** There are three arguments: An 8-byte aligned pointer to the memory,
1940 ** the number of bytes in the memory buffer, and the minimum allocation size.
1941 ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
1942 ** to using its default memory allocator (the system malloc() implementation),
1943 ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. ^If the
1944 ** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
1945 ** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
1946 ** allocator is engaged to handle all of SQLites memory allocation needs.
1947 ** The first pointer (the memory pointer) must be aligned to an 8-byte
1948 ** boundary or subsequent behavior of SQLite will be undefined.
1949 ** The minimum allocation size is capped at 2**12. Reasonable values
1950 ** for the minimum allocation size are 2**5 through 2**8.</dd>
1952 ** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
1953 ** <dd> ^(This option takes a single argument which is a pointer to an
1954 ** instance of the [sqlite3_mutex_methods] structure. The argument specifies
1955 ** alternative low-level mutex routines to be used in place
1956 ** the mutex routines built into SQLite.)^ ^SQLite makes a copy of the
1957 ** content of the [sqlite3_mutex_methods] structure before the call to
1958 ** [sqlite3_config()] returns. ^If SQLite is compiled with
1959 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1960 ** the entire mutexing subsystem is omitted from the build and hence calls to
1961 ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
1962 ** return [SQLITE_ERROR].</dd>
1964 ** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
1965 ** <dd> ^(This option takes a single argument which is a pointer to an
1966 ** instance of the [sqlite3_mutex_methods] structure. The
1967 ** [sqlite3_mutex_methods]
1968 ** structure is filled with the currently defined mutex routines.)^
1969 ** This option can be used to overload the default mutex allocation
1970 ** routines with a wrapper used to track mutex usage for performance
1971 ** profiling or testing, for example. ^If SQLite is compiled with
1972 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1973 ** the entire mutexing subsystem is omitted from the build and hence calls to
1974 ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
1975 ** return [SQLITE_ERROR].</dd>
1977 ** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
1978 ** <dd> ^(This option takes two arguments that determine the default
1979 ** memory allocation for the lookaside memory allocator on each
1980 ** [database connection]. The first argument is the
1981 ** size of each lookaside buffer slot and the second is the number of
1982 ** slots allocated to each database connection.)^ ^(This option sets the
1983 ** <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
1984 ** verb to [sqlite3_db_config()] can be used to change the lookaside
1985 ** configuration on individual connections.)^ </dd>
1987 ** [[SQLITE_CONFIG_PCACHE]] <dt>SQLITE_CONFIG_PCACHE</dt>
1988 ** <dd> ^(This option takes a single argument which is a pointer to
1989 ** an [sqlite3_pcache_methods] object. This object specifies the interface
1990 ** to a custom page cache implementation.)^ ^SQLite makes a copy of the
1991 ** object and uses it for page cache memory allocations.</dd>
1993 ** [[SQLITE_CONFIG_GETPCACHE]] <dt>SQLITE_CONFIG_GETPCACHE</dt>
1994 ** <dd> ^(This option takes a single argument which is a pointer to an
1995 ** [sqlite3_pcache_methods] object. SQLite copies of the current
1996 ** page cache implementation into that object.)^ </dd>
1998 ** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
1999 ** <dd> ^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
2000 ** function with a call signature of void(*)(void*,int,const char*),
2001 ** and a pointer to void. ^If the function pointer is not NULL, it is
2002 ** invoked by [sqlite3_log()] to process each logging event. ^If the
2003 ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
2004 ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
2005 ** passed through as the first parameter to the application-defined logger
2006 ** function whenever that function is invoked. ^The second parameter to
2007 ** the logger function is a copy of the first parameter to the corresponding
2008 ** [sqlite3_log()] call and is intended to be a [result code] or an
2009 ** [extended result code]. ^The third parameter passed to the logger is
2010 ** log message after formatting via [sqlite3_snprintf()].
2011 ** The SQLite logging interface is not reentrant; the logger function
2012 ** supplied by the application must not invoke any SQLite interface.
2013 ** In a multi-threaded application, the application-defined logger
2014 ** function must be threadsafe. </dd>
2016 ** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
2017 ** <dd> This option takes a single argument of type int. If non-zero, then
2018 ** URI handling is globally enabled. If the parameter is zero, then URI handling
2019 ** is globally disabled. If URI handling is globally enabled, all filenames
2020 ** passed to [sqlite3_open()], [sqlite3_open_v2()], [sqlite3_open16()] or
2021 ** specified as part of [ATTACH] commands are interpreted as URIs, regardless
2022 ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
2023 ** connection is opened. If it is globally disabled, filenames are
2024 ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
2025 ** database connection is opened. By default, URI handling is globally
2026 ** disabled. The default value may be changed by compiling with the
2027 ** [SQLITE_USE_URI] symbol defined.
2028 ** </dl>
2030 #define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */
2031 #define SQLITE_CONFIG_MULTITHREAD 2 /* nil */
2032 #define SQLITE_CONFIG_SERIALIZED 3 /* nil */
2033 #define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */
2034 #define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */
2035 #define SQLITE_CONFIG_SCRATCH 6 /* void*, int sz, int N */
2036 #define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */
2037 #define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */
2038 #define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */
2039 #define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */
2040 #define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */
2041 /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
2042 #define SQLITE_CONFIG_LOOKASIDE 13 /* int int */
2043 #define SQLITE_CONFIG_PCACHE 14 /* sqlite3_pcache_methods* */
2044 #define SQLITE_CONFIG_GETPCACHE 15 /* sqlite3_pcache_methods* */
2045 #define SQLITE_CONFIG_LOG 16 /* xFunc, void* */
2046 #define SQLITE_CONFIG_URI 17 /* int */
2049 ** CAPI3REF: Database Connection Configuration Options
2051 ** These constants are the available integer configuration options that
2052 ** can be passed as the second argument to the [sqlite3_db_config()] interface.
2054 ** New configuration options may be added in future releases of SQLite.
2055 ** Existing configuration options might be discontinued. Applications
2056 ** should check the return code from [sqlite3_db_config()] to make sure that
2057 ** the call worked. ^The [sqlite3_db_config()] interface will return a
2058 ** non-zero [error code] if a discontinued or unsupported configuration option
2059 ** is invoked.
2061 ** <dl>
2062 ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
2063 ** <dd> ^This option takes three additional arguments that determine the
2064 ** [lookaside memory allocator] configuration for the [database connection].
2065 ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
2066 ** pointer to a memory buffer to use for lookaside memory.
2067 ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
2068 ** may be NULL in which case SQLite will allocate the
2069 ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
2070 ** size of each lookaside buffer slot. ^The third argument is the number of
2071 ** slots. The size of the buffer in the first argument must be greater than
2072 ** or equal to the product of the second and third arguments. The buffer
2073 ** must be aligned to an 8-byte boundary. ^If the second argument to
2074 ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
2075 ** rounded down to the next smaller multiple of 8. ^(The lookaside memory
2076 ** configuration for a database connection can only be changed when that
2077 ** connection is not currently using lookaside memory, or in other words
2078 ** when the "current value" returned by
2079 ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
2080 ** Any attempt to change the lookaside memory configuration when lookaside
2081 ** memory is in use leaves the configuration unchanged and returns
2082 ** [SQLITE_BUSY].)^</dd>
2084 ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
2085 ** <dd> ^This option is used to enable or disable the enforcement of
2086 ** [foreign key constraints]. There should be two additional arguments.
2087 ** The first argument is an integer which is 0 to disable FK enforcement,
2088 ** positive to enable FK enforcement or negative to leave FK enforcement
2089 ** unchanged. The second parameter is a pointer to an integer into which
2090 ** is written 0 or 1 to indicate whether FK enforcement is off or on
2091 ** following this call. The second parameter may be a NULL pointer, in
2092 ** which case the FK enforcement setting is not reported back. </dd>
2094 ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
2095 ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
2096 ** There should be two additional arguments.
2097 ** The first argument is an integer which is 0 to disable triggers,
2098 ** positive to enable triggers or negative to leave the setting unchanged.
2099 ** The second parameter is a pointer to an integer into which
2100 ** is written 0 or 1 to indicate whether triggers are disabled or enabled
2101 ** following this call. The second parameter may be a NULL pointer, in
2102 ** which case the trigger setting is not reported back. </dd>
2104 ** </dl>
2106 #define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */
2107 #define SQLITE_DBCONFIG_ENABLE_FKEY 1002 /* int int* */
2108 #define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */
2112 ** CAPI3REF: Enable Or Disable Extended Result Codes
2114 ** ^The sqlite3_extended_result_codes() routine enables or disables the
2115 ** [extended result codes] feature of SQLite. ^The extended result
2116 ** codes are disabled by default for historical compatibility.
2118 SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
2121 ** CAPI3REF: Last Insert Rowid
2123 ** ^Each entry in an SQLite table has a unique 64-bit signed
2124 ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
2125 ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
2126 ** names are not also used by explicitly declared columns. ^If
2127 ** the table has a column of type [INTEGER PRIMARY KEY] then that column
2128 ** is another alias for the rowid.
2130 ** ^This routine returns the [rowid] of the most recent
2131 ** successful [INSERT] into the database from the [database connection]
2132 ** in the first argument. ^As of SQLite version 3.7.7, this routines
2133 ** records the last insert rowid of both ordinary tables and [virtual tables].
2134 ** ^If no successful [INSERT]s
2135 ** have ever occurred on that database connection, zero is returned.
2137 ** ^(If an [INSERT] occurs within a trigger or within a [virtual table]
2138 ** method, then this routine will return the [rowid] of the inserted
2139 ** row as long as the trigger or virtual table method is running.
2140 ** But once the trigger or virtual table method ends, the value returned
2141 ** by this routine reverts to what it was before the trigger or virtual
2142 ** table method began.)^
2144 ** ^An [INSERT] that fails due to a constraint violation is not a
2145 ** successful [INSERT] and does not change the value returned by this
2146 ** routine. ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
2147 ** and INSERT OR ABORT make no changes to the return value of this
2148 ** routine when their insertion fails. ^(When INSERT OR REPLACE
2149 ** encounters a constraint violation, it does not fail. The
2150 ** INSERT continues to completion after deleting rows that caused
2151 ** the constraint problem so INSERT OR REPLACE will always change
2152 ** the return value of this interface.)^
2154 ** ^For the purposes of this routine, an [INSERT] is considered to
2155 ** be successful even if it is subsequently rolled back.
2157 ** This function is accessible to SQL statements via the
2158 ** [last_insert_rowid() SQL function].
2160 ** If a separate thread performs a new [INSERT] on the same
2161 ** database connection while the [sqlite3_last_insert_rowid()]
2162 ** function is running and thus changes the last insert [rowid],
2163 ** then the value returned by [sqlite3_last_insert_rowid()] is
2164 ** unpredictable and might not equal either the old or the new
2165 ** last insert [rowid].
2167 SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
2170 ** CAPI3REF: Count The Number Of Rows Modified
2172 ** ^This function returns the number of database rows that were changed
2173 ** or inserted or deleted by the most recently completed SQL statement
2174 ** on the [database connection] specified by the first parameter.
2175 ** ^(Only changes that are directly specified by the [INSERT], [UPDATE],
2176 ** or [DELETE] statement are counted. Auxiliary changes caused by
2177 ** triggers or [foreign key actions] are not counted.)^ Use the
2178 ** [sqlite3_total_changes()] function to find the total number of changes
2179 ** including changes caused by triggers and foreign key actions.
2181 ** ^Changes to a view that are simulated by an [INSTEAD OF trigger]
2182 ** are not counted. Only real table changes are counted.
2184 ** ^(A "row change" is a change to a single row of a single table
2185 ** caused by an INSERT, DELETE, or UPDATE statement. Rows that
2186 ** are changed as side effects of [REPLACE] constraint resolution,
2187 ** rollback, ABORT processing, [DROP TABLE], or by any other
2188 ** mechanisms do not count as direct row changes.)^
2190 ** A "trigger context" is a scope of execution that begins and
2191 ** ends with the script of a [CREATE TRIGGER | trigger].
2192 ** Most SQL statements are
2193 ** evaluated outside of any trigger. This is the "top level"
2194 ** trigger context. If a trigger fires from the top level, a
2195 ** new trigger context is entered for the duration of that one
2196 ** trigger. Subtriggers create subcontexts for their duration.
2198 ** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
2199 ** not create a new trigger context.
2201 ** ^This function returns the number of direct row changes in the
2202 ** most recent INSERT, UPDATE, or DELETE statement within the same
2203 ** trigger context.
2205 ** ^Thus, when called from the top level, this function returns the
2206 ** number of changes in the most recent INSERT, UPDATE, or DELETE
2207 ** that also occurred at the top level. ^(Within the body of a trigger,
2208 ** the sqlite3_changes() interface can be called to find the number of
2209 ** changes in the most recently completed INSERT, UPDATE, or DELETE
2210 ** statement within the body of the same trigger.
2211 ** However, the number returned does not include changes
2212 ** caused by subtriggers since those have their own context.)^
2214 ** See also the [sqlite3_total_changes()] interface, the
2215 ** [count_changes pragma], and the [changes() SQL function].
2217 ** If a separate thread makes changes on the same database connection
2218 ** while [sqlite3_changes()] is running then the value returned
2219 ** is unpredictable and not meaningful.
2221 SQLITE_API int sqlite3_changes(sqlite3*);
2224 ** CAPI3REF: Total Number Of Rows Modified
2226 ** ^This function returns the number of row changes caused by [INSERT],
2227 ** [UPDATE] or [DELETE] statements since the [database connection] was opened.
2228 ** ^(The count returned by sqlite3_total_changes() includes all changes
2229 ** from all [CREATE TRIGGER | trigger] contexts and changes made by
2230 ** [foreign key actions]. However,
2231 ** the count does not include changes used to implement [REPLACE] constraints,
2232 ** do rollbacks or ABORT processing, or [DROP TABLE] processing. The
2233 ** count does not include rows of views that fire an [INSTEAD OF trigger],
2234 ** though if the INSTEAD OF trigger makes changes of its own, those changes
2235 ** are counted.)^
2236 ** ^The sqlite3_total_changes() function counts the changes as soon as
2237 ** the statement that makes them is completed (when the statement handle
2238 ** is passed to [sqlite3_reset()] or [sqlite3_finalize()]).
2240 ** See also the [sqlite3_changes()] interface, the
2241 ** [count_changes pragma], and the [total_changes() SQL function].
2243 ** If a separate thread makes changes on the same database connection
2244 ** while [sqlite3_total_changes()] is running then the value
2245 ** returned is unpredictable and not meaningful.
2247 SQLITE_API int sqlite3_total_changes(sqlite3*);
2250 ** CAPI3REF: Interrupt A Long-Running Query
2252 ** ^This function causes any pending database operation to abort and
2253 ** return at its earliest opportunity. This routine is typically
2254 ** called in response to a user action such as pressing "Cancel"
2255 ** or Ctrl-C where the user wants a long query operation to halt
2256 ** immediately.
2258 ** ^It is safe to call this routine from a thread different from the
2259 ** thread that is currently running the database operation. But it
2260 ** is not safe to call this routine with a [database connection] that
2261 ** is closed or might close before sqlite3_interrupt() returns.
2263 ** ^If an SQL operation is very nearly finished at the time when
2264 ** sqlite3_interrupt() is called, then it might not have an opportunity
2265 ** to be interrupted and might continue to completion.
2267 ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
2268 ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
2269 ** that is inside an explicit transaction, then the entire transaction
2270 ** will be rolled back automatically.
2272 ** ^The sqlite3_interrupt(D) call is in effect until all currently running
2273 ** SQL statements on [database connection] D complete. ^Any new SQL statements
2274 ** that are started after the sqlite3_interrupt() call and before the
2275 ** running statements reaches zero are interrupted as if they had been
2276 ** running prior to the sqlite3_interrupt() call. ^New SQL statements
2277 ** that are started after the running statement count reaches zero are
2278 ** not effected by the sqlite3_interrupt().
2279 ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
2280 ** SQL statements is a no-op and has no effect on SQL statements
2281 ** that are started after the sqlite3_interrupt() call returns.
2283 ** If the database connection closes while [sqlite3_interrupt()]
2284 ** is running then bad things will likely happen.
2286 SQLITE_API void sqlite3_interrupt(sqlite3*);
2289 ** CAPI3REF: Determine If An SQL Statement Is Complete
2291 ** These routines are useful during command-line input to determine if the
2292 ** currently entered text seems to form a complete SQL statement or
2293 ** if additional input is needed before sending the text into
2294 ** SQLite for parsing. ^These routines return 1 if the input string
2295 ** appears to be a complete SQL statement. ^A statement is judged to be
2296 ** complete if it ends with a semicolon token and is not a prefix of a
2297 ** well-formed CREATE TRIGGER statement. ^Semicolons that are embedded within
2298 ** string literals or quoted identifier names or comments are not
2299 ** independent tokens (they are part of the token in which they are
2300 ** embedded) and thus do not count as a statement terminator. ^Whitespace
2301 ** and comments that follow the final semicolon are ignored.
2303 ** ^These routines return 0 if the statement is incomplete. ^If a
2304 ** memory allocation fails, then SQLITE_NOMEM is returned.
2306 ** ^These routines do not parse the SQL statements thus
2307 ** will not detect syntactically incorrect SQL.
2309 ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
2310 ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
2311 ** automatically by sqlite3_complete16(). If that initialization fails,
2312 ** then the return value from sqlite3_complete16() will be non-zero
2313 ** regardless of whether or not the input SQL is complete.)^
2315 ** The input to [sqlite3_complete()] must be a zero-terminated
2316 ** UTF-8 string.
2318 ** The input to [sqlite3_complete16()] must be a zero-terminated
2319 ** UTF-16 string in native byte order.
2321 SQLITE_API int sqlite3_complete(const char *sql);
2322 SQLITE_API int sqlite3_complete16(const void *sql);
2325 ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
2327 ** ^This routine sets a callback function that might be invoked whenever
2328 ** an attempt is made to open a database table that another thread
2329 ** or process has locked.
2331 ** ^If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]
2332 ** is returned immediately upon encountering the lock. ^If the busy callback
2333 ** is not NULL, then the callback might be invoked with two arguments.
2335 ** ^The first argument to the busy handler is a copy of the void* pointer which
2336 ** is the third argument to sqlite3_busy_handler(). ^The second argument to
2337 ** the busy handler callback is the number of times that the busy handler has
2338 ** been invoked for this locking event. ^If the
2339 ** busy callback returns 0, then no additional attempts are made to
2340 ** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
2341 ** ^If the callback returns non-zero, then another attempt
2342 ** is made to open the database for reading and the cycle repeats.
2344 ** The presence of a busy handler does not guarantee that it will be invoked
2345 ** when there is lock contention. ^If SQLite determines that invoking the busy
2346 ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
2347 ** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler.
2348 ** Consider a scenario where one process is holding a read lock that
2349 ** it is trying to promote to a reserved lock and
2350 ** a second process is holding a reserved lock that it is trying
2351 ** to promote to an exclusive lock. The first process cannot proceed
2352 ** because it is blocked by the second and the second process cannot
2353 ** proceed because it is blocked by the first. If both processes
2354 ** invoke the busy handlers, neither will make any progress. Therefore,
2355 ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
2356 ** will induce the first process to release its read lock and allow
2357 ** the second process to proceed.
2359 ** ^The default busy callback is NULL.
2361 ** ^The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
2362 ** when SQLite is in the middle of a large transaction where all the
2363 ** changes will not fit into the in-memory cache. SQLite will
2364 ** already hold a RESERVED lock on the database file, but it needs
2365 ** to promote this lock to EXCLUSIVE so that it can spill cache
2366 ** pages into the database file without harm to concurrent
2367 ** readers. ^If it is unable to promote the lock, then the in-memory
2368 ** cache will be left in an inconsistent state and so the error
2369 ** code is promoted from the relatively benign [SQLITE_BUSY] to
2370 ** the more severe [SQLITE_IOERR_BLOCKED]. ^This error code promotion
2371 ** forces an automatic rollback of the changes. See the
2372 ** <a href="/cvstrac/wiki?p=CorruptionFollowingBusyError">
2373 ** CorruptionFollowingBusyError</a> wiki page for a discussion of why
2374 ** this is important.
2376 ** ^(There can only be a single busy handler defined for each
2377 ** [database connection]. Setting a new busy handler clears any
2378 ** previously set handler.)^ ^Note that calling [sqlite3_busy_timeout()]
2379 ** will also set or clear the busy handler.
2381 ** The busy callback should not take any actions which modify the
2382 ** database connection that invoked the busy handler. Any such actions
2383 ** result in undefined behavior.
2385 ** A busy handler must not close the database connection
2386 ** or [prepared statement] that invoked the busy handler.
2388 SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
2391 ** CAPI3REF: Set A Busy Timeout
2393 ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
2394 ** for a specified amount of time when a table is locked. ^The handler
2395 ** will sleep multiple times until at least "ms" milliseconds of sleeping
2396 ** have accumulated. ^After at least "ms" milliseconds of sleeping,
2397 ** the handler returns 0 which causes [sqlite3_step()] to return
2398 ** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
2400 ** ^Calling this routine with an argument less than or equal to zero
2401 ** turns off all busy handlers.
2403 ** ^(There can only be a single busy handler for a particular
2404 ** [database connection] any any given moment. If another busy handler
2405 ** was defined (using [sqlite3_busy_handler()]) prior to calling
2406 ** this routine, that other busy handler is cleared.)^
2408 SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
2411 ** CAPI3REF: Convenience Routines For Running Queries
2413 ** This is a legacy interface that is preserved for backwards compatibility.
2414 ** Use of this interface is not recommended.
2416 ** Definition: A <b>result table</b> is memory data structure created by the
2417 ** [sqlite3_get_table()] interface. A result table records the
2418 ** complete query results from one or more queries.
2420 ** The table conceptually has a number of rows and columns. But
2421 ** these numbers are not part of the result table itself. These
2422 ** numbers are obtained separately. Let N be the number of rows
2423 ** and M be the number of columns.
2425 ** A result table is an array of pointers to zero-terminated UTF-8 strings.
2426 ** There are (N+1)*M elements in the array. The first M pointers point
2427 ** to zero-terminated strings that contain the names of the columns.
2428 ** The remaining entries all point to query results. NULL values result
2429 ** in NULL pointers. All other values are in their UTF-8 zero-terminated
2430 ** string representation as returned by [sqlite3_column_text()].
2432 ** A result table might consist of one or more memory allocations.
2433 ** It is not safe to pass a result table directly to [sqlite3_free()].
2434 ** A result table should be deallocated using [sqlite3_free_table()].
2436 ** ^(As an example of the result table format, suppose a query result
2437 ** is as follows:
2439 ** <blockquote><pre>
2440 ** Name | Age
2441 ** -----------------------
2442 ** Alice | 43
2443 ** Bob | 28
2444 ** Cindy | 21
2445 ** </pre></blockquote>
2447 ** There are two column (M==2) and three rows (N==3). Thus the
2448 ** result table has 8 entries. Suppose the result table is stored
2449 ** in an array names azResult. Then azResult holds this content:
2451 ** <blockquote><pre>
2452 ** azResult&#91;0] = "Name";
2453 ** azResult&#91;1] = "Age";
2454 ** azResult&#91;2] = "Alice";
2455 ** azResult&#91;3] = "43";
2456 ** azResult&#91;4] = "Bob";
2457 ** azResult&#91;5] = "28";
2458 ** azResult&#91;6] = "Cindy";
2459 ** azResult&#91;7] = "21";
2460 ** </pre></blockquote>)^
2462 ** ^The sqlite3_get_table() function evaluates one or more
2463 ** semicolon-separated SQL statements in the zero-terminated UTF-8
2464 ** string of its 2nd parameter and returns a result table to the
2465 ** pointer given in its 3rd parameter.
2467 ** After the application has finished with the result from sqlite3_get_table(),
2468 ** it must pass the result table pointer to sqlite3_free_table() in order to
2469 ** release the memory that was malloced. Because of the way the
2470 ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
2471 ** function must not try to call [sqlite3_free()] directly. Only
2472 ** [sqlite3_free_table()] is able to release the memory properly and safely.
2474 ** The sqlite3_get_table() interface is implemented as a wrapper around
2475 ** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access
2476 ** to any internal data structures of SQLite. It uses only the public
2477 ** interface defined here. As a consequence, errors that occur in the
2478 ** wrapper layer outside of the internal [sqlite3_exec()] call are not
2479 ** reflected in subsequent calls to [sqlite3_errcode()] or
2480 ** [sqlite3_errmsg()].
2482 SQLITE_API int sqlite3_get_table(
2483 sqlite3 *db, /* An open database */
2484 const char *zSql, /* SQL to be evaluated */
2485 char ***pazResult, /* Results of the query */
2486 int *pnRow, /* Number of result rows written here */
2487 int *pnColumn, /* Number of result columns written here */
2488 char **pzErrmsg /* Error msg written here */
2490 SQLITE_API void sqlite3_free_table(char **result);
2493 ** CAPI3REF: Formatted String Printing Functions
2495 ** These routines are work-alikes of the "printf()" family of functions
2496 ** from the standard C library.
2498 ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
2499 ** results into memory obtained from [sqlite3_malloc()].
2500 ** The strings returned by these two routines should be
2501 ** released by [sqlite3_free()]. ^Both routines return a
2502 ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
2503 ** memory to hold the resulting string.
2505 ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
2506 ** the standard C library. The result is written into the
2507 ** buffer supplied as the second parameter whose size is given by
2508 ** the first parameter. Note that the order of the
2509 ** first two parameters is reversed from snprintf().)^ This is an
2510 ** historical accident that cannot be fixed without breaking
2511 ** backwards compatibility. ^(Note also that sqlite3_snprintf()
2512 ** returns a pointer to its buffer instead of the number of
2513 ** characters actually written into the buffer.)^ We admit that
2514 ** the number of characters written would be a more useful return
2515 ** value but we cannot change the implementation of sqlite3_snprintf()
2516 ** now without breaking compatibility.
2518 ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
2519 ** guarantees that the buffer is always zero-terminated. ^The first
2520 ** parameter "n" is the total size of the buffer, including space for
2521 ** the zero terminator. So the longest string that can be completely
2522 ** written will be n-1 characters.
2524 ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
2526 ** These routines all implement some additional formatting
2527 ** options that are useful for constructing SQL statements.
2528 ** All of the usual printf() formatting options apply. In addition, there
2529 ** is are "%q", "%Q", and "%z" options.
2531 ** ^(The %q option works like %s in that it substitutes a null-terminated
2532 ** string from the argument list. But %q also doubles every '\'' character.
2533 ** %q is designed for use inside a string literal.)^ By doubling each '\''
2534 ** character it escapes that character and allows it to be inserted into
2535 ** the string.
2537 ** For example, assume the string variable zText contains text as follows:
2539 ** <blockquote><pre>
2540 ** char *zText = "It's a happy day!";
2541 ** </pre></blockquote>
2543 ** One can use this text in an SQL statement as follows:
2545 ** <blockquote><pre>
2546 ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
2547 ** sqlite3_exec(db, zSQL, 0, 0, 0);
2548 ** sqlite3_free(zSQL);
2549 ** </pre></blockquote>
2551 ** Because the %q format string is used, the '\'' character in zText
2552 ** is escaped and the SQL generated is as follows:
2554 ** <blockquote><pre>
2555 ** INSERT INTO table1 VALUES('It''s a happy day!')
2556 ** </pre></blockquote>
2558 ** This is correct. Had we used %s instead of %q, the generated SQL
2559 ** would have looked like this:
2561 ** <blockquote><pre>
2562 ** INSERT INTO table1 VALUES('It's a happy day!');
2563 ** </pre></blockquote>
2565 ** This second example is an SQL syntax error. As a general rule you should
2566 ** always use %q instead of %s when inserting text into a string literal.
2568 ** ^(The %Q option works like %q except it also adds single quotes around
2569 ** the outside of the total string. Additionally, if the parameter in the
2570 ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
2571 ** single quotes).)^ So, for example, one could say:
2573 ** <blockquote><pre>
2574 ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
2575 ** sqlite3_exec(db, zSQL, 0, 0, 0);
2576 ** sqlite3_free(zSQL);
2577 ** </pre></blockquote>
2579 ** The code above will render a correct SQL statement in the zSQL
2580 ** variable even if the zText variable is a NULL pointer.
2582 ** ^(The "%z" formatting option works like "%s" but with the
2583 ** addition that after the string has been read and copied into
2584 ** the result, [sqlite3_free()] is called on the input string.)^
2586 SQLITE_API char *sqlite3_mprintf(const char*,...);
2587 SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
2588 SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
2589 SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
2592 ** CAPI3REF: Memory Allocation Subsystem
2594 ** The SQLite core uses these three routines for all of its own
2595 ** internal memory allocation needs. "Core" in the previous sentence
2596 ** does not include operating-system specific VFS implementation. The
2597 ** Windows VFS uses native malloc() and free() for some operations.
2599 ** ^The sqlite3_malloc() routine returns a pointer to a block
2600 ** of memory at least N bytes in length, where N is the parameter.
2601 ** ^If sqlite3_malloc() is unable to obtain sufficient free
2602 ** memory, it returns a NULL pointer. ^If the parameter N to
2603 ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
2604 ** a NULL pointer.
2606 ** ^Calling sqlite3_free() with a pointer previously returned
2607 ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
2608 ** that it might be reused. ^The sqlite3_free() routine is
2609 ** a no-op if is called with a NULL pointer. Passing a NULL pointer
2610 ** to sqlite3_free() is harmless. After being freed, memory
2611 ** should neither be read nor written. Even reading previously freed
2612 ** memory might result in a segmentation fault or other severe error.
2613 ** Memory corruption, a segmentation fault, or other severe error
2614 ** might result if sqlite3_free() is called with a non-NULL pointer that
2615 ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
2617 ** ^(The sqlite3_realloc() interface attempts to resize a
2618 ** prior memory allocation to be at least N bytes, where N is the
2619 ** second parameter. The memory allocation to be resized is the first
2620 ** parameter.)^ ^ If the first parameter to sqlite3_realloc()
2621 ** is a NULL pointer then its behavior is identical to calling
2622 ** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
2623 ** ^If the second parameter to sqlite3_realloc() is zero or
2624 ** negative then the behavior is exactly the same as calling
2625 ** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
2626 ** ^sqlite3_realloc() returns a pointer to a memory allocation
2627 ** of at least N bytes in size or NULL if sufficient memory is unavailable.
2628 ** ^If M is the size of the prior allocation, then min(N,M) bytes
2629 ** of the prior allocation are copied into the beginning of buffer returned
2630 ** by sqlite3_realloc() and the prior allocation is freed.
2631 ** ^If sqlite3_realloc() returns NULL, then the prior allocation
2632 ** is not freed.
2634 ** ^The memory returned by sqlite3_malloc() and sqlite3_realloc()
2635 ** is always aligned to at least an 8 byte boundary, or to a
2636 ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
2637 ** option is used.
2639 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
2640 ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
2641 ** implementation of these routines to be omitted. That capability
2642 ** is no longer provided. Only built-in memory allocators can be used.
2644 ** The Windows OS interface layer calls
2645 ** the system malloc() and free() directly when converting
2646 ** filenames between the UTF-8 encoding used by SQLite
2647 ** and whatever filename encoding is used by the particular Windows
2648 ** installation. Memory allocation errors are detected, but
2649 ** they are reported back as [SQLITE_CANTOPEN] or
2650 ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
2652 ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
2653 ** must be either NULL or else pointers obtained from a prior
2654 ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
2655 ** not yet been released.
2657 ** The application must not read or write any part of
2658 ** a block of memory after it has been released using
2659 ** [sqlite3_free()] or [sqlite3_realloc()].
2661 SQLITE_API void *sqlite3_malloc(int);
2662 SQLITE_API void *sqlite3_realloc(void*, int);
2663 SQLITE_API void sqlite3_free(void*);
2666 ** CAPI3REF: Memory Allocator Statistics
2668 ** SQLite provides these two interfaces for reporting on the status
2669 ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
2670 ** routines, which form the built-in memory allocation subsystem.
2672 ** ^The [sqlite3_memory_used()] routine returns the number of bytes
2673 ** of memory currently outstanding (malloced but not freed).
2674 ** ^The [sqlite3_memory_highwater()] routine returns the maximum
2675 ** value of [sqlite3_memory_used()] since the high-water mark
2676 ** was last reset. ^The values returned by [sqlite3_memory_used()] and
2677 ** [sqlite3_memory_highwater()] include any overhead
2678 ** added by SQLite in its implementation of [sqlite3_malloc()],
2679 ** but not overhead added by the any underlying system library
2680 ** routines that [sqlite3_malloc()] may call.
2682 ** ^The memory high-water mark is reset to the current value of
2683 ** [sqlite3_memory_used()] if and only if the parameter to
2684 ** [sqlite3_memory_highwater()] is true. ^The value returned
2685 ** by [sqlite3_memory_highwater(1)] is the high-water mark
2686 ** prior to the reset.
2688 SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
2689 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
2692 ** CAPI3REF: Pseudo-Random Number Generator
2694 ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
2695 ** select random [ROWID | ROWIDs] when inserting new records into a table that
2696 ** already uses the largest possible [ROWID]. The PRNG is also used for
2697 ** the build-in random() and randomblob() SQL functions. This interface allows
2698 ** applications to access the same PRNG for other purposes.
2700 ** ^A call to this routine stores N bytes of randomness into buffer P.
2702 ** ^The first time this routine is invoked (either internally or by
2703 ** the application) the PRNG is seeded using randomness obtained
2704 ** from the xRandomness method of the default [sqlite3_vfs] object.
2705 ** ^On all subsequent invocations, the pseudo-randomness is generated
2706 ** internally and without recourse to the [sqlite3_vfs] xRandomness
2707 ** method.
2709 SQLITE_API void sqlite3_randomness(int N, void *P);
2712 ** CAPI3REF: Compile-Time Authorization Callbacks
2714 ** ^This routine registers an authorizer callback with a particular
2715 ** [database connection], supplied in the first argument.
2716 ** ^The authorizer callback is invoked as SQL statements are being compiled
2717 ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
2718 ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. ^At various
2719 ** points during the compilation process, as logic is being created
2720 ** to perform various actions, the authorizer callback is invoked to
2721 ** see if those actions are allowed. ^The authorizer callback should
2722 ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
2723 ** specific action but allow the SQL statement to continue to be
2724 ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
2725 ** rejected with an error. ^If the authorizer callback returns
2726 ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
2727 ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
2728 ** the authorizer will fail with an error message.
2730 ** When the callback returns [SQLITE_OK], that means the operation
2731 ** requested is ok. ^When the callback returns [SQLITE_DENY], the
2732 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
2733 ** authorizer will fail with an error message explaining that
2734 ** access is denied.
2736 ** ^The first parameter to the authorizer callback is a copy of the third
2737 ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
2738 ** to the callback is an integer [SQLITE_COPY | action code] that specifies
2739 ** the particular action to be authorized. ^The third through sixth parameters
2740 ** to the callback are zero-terminated strings that contain additional
2741 ** details about the action to be authorized.
2743 ** ^If the action code is [SQLITE_READ]
2744 ** and the callback returns [SQLITE_IGNORE] then the
2745 ** [prepared statement] statement is constructed to substitute
2746 ** a NULL value in place of the table column that would have
2747 ** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE]
2748 ** return can be used to deny an untrusted user access to individual
2749 ** columns of a table.
2750 ** ^If the action code is [SQLITE_DELETE] and the callback returns
2751 ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
2752 ** [truncate optimization] is disabled and all rows are deleted individually.
2754 ** An authorizer is used when [sqlite3_prepare | preparing]
2755 ** SQL statements from an untrusted source, to ensure that the SQL statements
2756 ** do not try to access data they are not allowed to see, or that they do not
2757 ** try to execute malicious statements that damage the database. For
2758 ** example, an application may allow a user to enter arbitrary
2759 ** SQL queries for evaluation by a database. But the application does
2760 ** not want the user to be able to make arbitrary changes to the
2761 ** database. An authorizer could then be put in place while the
2762 ** user-entered SQL is being [sqlite3_prepare | prepared] that
2763 ** disallows everything except [SELECT] statements.
2765 ** Applications that need to process SQL from untrusted sources
2766 ** might also consider lowering resource limits using [sqlite3_limit()]
2767 ** and limiting database size using the [max_page_count] [PRAGMA]
2768 ** in addition to using an authorizer.
2770 ** ^(Only a single authorizer can be in place on a database connection
2771 ** at a time. Each call to sqlite3_set_authorizer overrides the
2772 ** previous call.)^ ^Disable the authorizer by installing a NULL callback.
2773 ** The authorizer is disabled by default.
2775 ** The authorizer callback must not do anything that will modify
2776 ** the database connection that invoked the authorizer callback.
2777 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2778 ** database connections for the meaning of "modify" in this paragraph.
2780 ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
2781 ** statement might be re-prepared during [sqlite3_step()] due to a
2782 ** schema change. Hence, the application should ensure that the
2783 ** correct authorizer callback remains in place during the [sqlite3_step()].
2785 ** ^Note that the authorizer callback is invoked only during
2786 ** [sqlite3_prepare()] or its variants. Authorization is not
2787 ** performed during statement evaluation in [sqlite3_step()], unless
2788 ** as stated in the previous paragraph, sqlite3_step() invokes
2789 ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
2791 SQLITE_API int sqlite3_set_authorizer(
2792 sqlite3*,
2793 int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
2794 void *pUserData
2798 ** CAPI3REF: Authorizer Return Codes
2800 ** The [sqlite3_set_authorizer | authorizer callback function] must
2801 ** return either [SQLITE_OK] or one of these two constants in order
2802 ** to signal SQLite whether or not the action is permitted. See the
2803 ** [sqlite3_set_authorizer | authorizer documentation] for additional
2804 ** information.
2806 ** Note that SQLITE_IGNORE is also used as a [SQLITE_ROLLBACK | return code]
2807 ** from the [sqlite3_vtab_on_conflict()] interface.
2809 #define SQLITE_DENY 1 /* Abort the SQL statement with an error */
2810 #define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */
2813 ** CAPI3REF: Authorizer Action Codes
2815 ** The [sqlite3_set_authorizer()] interface registers a callback function
2816 ** that is invoked to authorize certain SQL statement actions. The
2817 ** second parameter to the callback is an integer code that specifies
2818 ** what action is being authorized. These are the integer action codes that
2819 ** the authorizer callback may be passed.
2821 ** These action code values signify what kind of operation is to be
2822 ** authorized. The 3rd and 4th parameters to the authorization
2823 ** callback function will be parameters or NULL depending on which of these
2824 ** codes is used as the second parameter. ^(The 5th parameter to the
2825 ** authorizer callback is the name of the database ("main", "temp",
2826 ** etc.) if applicable.)^ ^The 6th parameter to the authorizer callback
2827 ** is the name of the inner-most trigger or view that is responsible for
2828 ** the access attempt or NULL if this access attempt is directly from
2829 ** top-level SQL code.
2831 /******************************************* 3rd ************ 4th ***********/
2832 #define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */
2833 #define SQLITE_CREATE_TABLE 2 /* Table Name NULL */
2834 #define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */
2835 #define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */
2836 #define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */
2837 #define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */
2838 #define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */
2839 #define SQLITE_CREATE_VIEW 8 /* View Name NULL */
2840 #define SQLITE_DELETE 9 /* Table Name NULL */
2841 #define SQLITE_DROP_INDEX 10 /* Index Name Table Name */
2842 #define SQLITE_DROP_TABLE 11 /* Table Name NULL */
2843 #define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */
2844 #define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */
2845 #define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */
2846 #define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */
2847 #define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */
2848 #define SQLITE_DROP_VIEW 17 /* View Name NULL */
2849 #define SQLITE_INSERT 18 /* Table Name NULL */
2850 #define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */
2851 #define SQLITE_READ 20 /* Table Name Column Name */
2852 #define SQLITE_SELECT 21 /* NULL NULL */
2853 #define SQLITE_TRANSACTION 22 /* Operation NULL */
2854 #define SQLITE_UPDATE 23 /* Table Name Column Name */
2855 #define SQLITE_ATTACH 24 /* Filename NULL */
2856 #define SQLITE_DETACH 25 /* Database Name NULL */
2857 #define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */
2858 #define SQLITE_REINDEX 27 /* Index Name NULL */
2859 #define SQLITE_ANALYZE 28 /* Table Name NULL */
2860 #define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */
2861 #define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */
2862 #define SQLITE_FUNCTION 31 /* NULL Function Name */
2863 #define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */
2864 #define SQLITE_COPY 0 /* No longer used */
2867 ** CAPI3REF: Tracing And Profiling Functions
2869 ** These routines register callback functions that can be used for
2870 ** tracing and profiling the execution of SQL statements.
2872 ** ^The callback function registered by sqlite3_trace() is invoked at
2873 ** various times when an SQL statement is being run by [sqlite3_step()].
2874 ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
2875 ** SQL statement text as the statement first begins executing.
2876 ** ^(Additional sqlite3_trace() callbacks might occur
2877 ** as each triggered subprogram is entered. The callbacks for triggers
2878 ** contain a UTF-8 SQL comment that identifies the trigger.)^
2880 ** ^The callback function registered by sqlite3_profile() is invoked
2881 ** as each SQL statement finishes. ^The profile callback contains
2882 ** the original statement text and an estimate of wall-clock time
2883 ** of how long that statement took to run. ^The profile callback
2884 ** time is in units of nanoseconds, however the current implementation
2885 ** is only capable of millisecond resolution so the six least significant
2886 ** digits in the time are meaningless. Future versions of SQLite
2887 ** might provide greater resolution on the profiler callback. The
2888 ** sqlite3_profile() function is considered experimental and is
2889 ** subject to change in future versions of SQLite.
2891 SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
2892 SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
2893 void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
2896 ** CAPI3REF: Query Progress Callbacks
2898 ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
2899 ** function X to be invoked periodically during long running calls to
2900 ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
2901 ** database connection D. An example use for this
2902 ** interface is to keep a GUI updated during a large query.
2904 ** ^The parameter P is passed through as the only parameter to the
2905 ** callback function X. ^The parameter N is the number of
2906 ** [virtual machine instructions] that are evaluated between successive
2907 ** invocations of the callback X.
2909 ** ^Only a single progress handler may be defined at one time per
2910 ** [database connection]; setting a new progress handler cancels the
2911 ** old one. ^Setting parameter X to NULL disables the progress handler.
2912 ** ^The progress handler is also disabled by setting N to a value less
2913 ** than 1.
2915 ** ^If the progress callback returns non-zero, the operation is
2916 ** interrupted. This feature can be used to implement a
2917 ** "Cancel" button on a GUI progress dialog box.
2919 ** The progress handler callback must not do anything that will modify
2920 ** the database connection that invoked the progress handler.
2921 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2922 ** database connections for the meaning of "modify" in this paragraph.
2925 SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
2928 ** CAPI3REF: Opening A New Database Connection
2930 ** ^These routines open an SQLite database file as specified by the
2931 ** filename argument. ^The filename argument is interpreted as UTF-8 for
2932 ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
2933 ** order for sqlite3_open16(). ^(A [database connection] handle is usually
2934 ** returned in *ppDb, even if an error occurs. The only exception is that
2935 ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
2936 ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
2937 ** object.)^ ^(If the database is opened (and/or created) successfully, then
2938 ** [SQLITE_OK] is returned. Otherwise an [error code] is returned.)^ ^The
2939 ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
2940 ** an English language description of the error following a failure of any
2941 ** of the sqlite3_open() routines.
2943 ** ^The default encoding for the database will be UTF-8 if
2944 ** sqlite3_open() or sqlite3_open_v2() is called and
2945 ** UTF-16 in the native byte order if sqlite3_open16() is used.
2947 ** Whether or not an error occurs when it is opened, resources
2948 ** associated with the [database connection] handle should be released by
2949 ** passing it to [sqlite3_close()] when it is no longer required.
2951 ** The sqlite3_open_v2() interface works like sqlite3_open()
2952 ** except that it accepts two additional parameters for additional control
2953 ** over the new database connection. ^(The flags parameter to
2954 ** sqlite3_open_v2() can take one of
2955 ** the following three values, optionally combined with the
2956 ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
2957 ** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
2959 ** <dl>
2960 ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
2961 ** <dd>The database is opened in read-only mode. If the database does not
2962 ** already exist, an error is returned.</dd>)^
2964 ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
2965 ** <dd>The database is opened for reading and writing if possible, or reading
2966 ** only if the file is write protected by the operating system. In either
2967 ** case the database must already exist, otherwise an error is returned.</dd>)^
2969 ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
2970 ** <dd>The database is opened for reading and writing, and is created if
2971 ** it does not already exist. This is the behavior that is always used for
2972 ** sqlite3_open() and sqlite3_open16().</dd>)^
2973 ** </dl>
2975 ** If the 3rd parameter to sqlite3_open_v2() is not one of the
2976 ** combinations shown above optionally combined with other
2977 ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
2978 ** then the behavior is undefined.
2980 ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
2981 ** opens in the multi-thread [threading mode] as long as the single-thread
2982 ** mode has not been set at compile-time or start-time. ^If the
2983 ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
2984 ** in the serialized [threading mode] unless single-thread was
2985 ** previously selected at compile-time or start-time.
2986 ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
2987 ** eligible to use [shared cache mode], regardless of whether or not shared
2988 ** cache is enabled using [sqlite3_enable_shared_cache()]. ^The
2989 ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
2990 ** participate in [shared cache mode] even if it is enabled.
2992 ** ^The fourth parameter to sqlite3_open_v2() is the name of the
2993 ** [sqlite3_vfs] object that defines the operating system interface that
2994 ** the new database connection should use. ^If the fourth parameter is
2995 ** a NULL pointer then the default [sqlite3_vfs] object is used.
2997 ** ^If the filename is ":memory:", then a private, temporary in-memory database
2998 ** is created for the connection. ^This in-memory database will vanish when
2999 ** the database connection is closed. Future versions of SQLite might
3000 ** make use of additional special filenames that begin with the ":" character.
3001 ** It is recommended that when a database filename actually does begin with
3002 ** a ":" character you should prefix the filename with a pathname such as
3003 ** "./" to avoid ambiguity.
3005 ** ^If the filename is an empty string, then a private, temporary
3006 ** on-disk database will be created. ^This private database will be
3007 ** automatically deleted as soon as the database connection is closed.
3009 ** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
3011 ** ^If [URI filename] interpretation is enabled, and the filename argument
3012 ** begins with "file:", then the filename is interpreted as a URI. ^URI
3013 ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
3014 ** set in the fourth argument to sqlite3_open_v2(), or if it has
3015 ** been enabled globally using the [SQLITE_CONFIG_URI] option with the
3016 ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
3017 ** As of SQLite version 3.7.7, URI filename interpretation is turned off
3018 ** by default, but future releases of SQLite might enable URI filename
3019 ** interpretation by default. See "[URI filenames]" for additional
3020 ** information.
3022 ** URI filenames are parsed according to RFC 3986. ^If the URI contains an
3023 ** authority, then it must be either an empty string or the string
3024 ** "localhost". ^If the authority is not an empty string or "localhost", an
3025 ** error is returned to the caller. ^The fragment component of a URI, if
3026 ** present, is ignored.
3028 ** ^SQLite uses the path component of the URI as the name of the disk file
3029 ** which contains the database. ^If the path begins with a '/' character,
3030 ** then it is interpreted as an absolute path. ^If the path does not begin
3031 ** with a '/' (meaning that the authority section is omitted from the URI)
3032 ** then the path is interpreted as a relative path.
3033 ** ^On windows, the first component of an absolute path
3034 ** is a drive specification (e.g. "C:").
3036 ** [[core URI query parameters]]
3037 ** The query component of a URI may contain parameters that are interpreted
3038 ** either by SQLite itself, or by a [VFS | custom VFS implementation].
3039 ** SQLite interprets the following three query parameters:
3041 ** <ul>
3042 ** <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
3043 ** a VFS object that provides the operating system interface that should
3044 ** be used to access the database file on disk. ^If this option is set to
3045 ** an empty string the default VFS object is used. ^Specifying an unknown
3046 ** VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
3047 ** present, then the VFS specified by the option takes precedence over
3048 ** the value passed as the fourth parameter to sqlite3_open_v2().
3050 ** <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw" or
3051 ** "rwc". Attempting to set it to any other value is an error)^.
3052 ** ^If "ro" is specified, then the database is opened for read-only
3053 ** access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the
3054 ** third argument to sqlite3_prepare_v2(). ^If the mode option is set to
3055 ** "rw", then the database is opened for read-write (but not create)
3056 ** access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had
3057 ** been set. ^Value "rwc" is equivalent to setting both
3058 ** SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. ^If sqlite3_open_v2() is
3059 ** used, it is an error to specify a value for the mode parameter that is
3060 ** less restrictive than that specified by the flags passed as the third
3061 ** parameter.
3063 ** <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
3064 ** "private". ^Setting it to "shared" is equivalent to setting the
3065 ** SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
3066 ** sqlite3_open_v2(). ^Setting the cache parameter to "private" is
3067 ** equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
3068 ** ^If sqlite3_open_v2() is used and the "cache" parameter is present in
3069 ** a URI filename, its value overrides any behaviour requested by setting
3070 ** SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
3071 ** </ul>
3073 ** ^Specifying an unknown parameter in the query component of a URI is not an
3074 ** error. Future versions of SQLite might understand additional query
3075 ** parameters. See "[query parameters with special meaning to SQLite]" for
3076 ** additional information.
3078 ** [[URI filename examples]] <h3>URI filename examples</h3>
3080 ** <table border="1" align=center cellpadding=5>
3081 ** <tr><th> URI filenames <th> Results
3082 ** <tr><td> file:data.db <td>
3083 ** Open the file "data.db" in the current directory.
3084 ** <tr><td> file:/home/fred/data.db<br>
3085 ** file:///home/fred/data.db <br>
3086 ** file://localhost/home/fred/data.db <br> <td>
3087 ** Open the database file "/home/fred/data.db".
3088 ** <tr><td> file://darkstar/home/fred/data.db <td>
3089 ** An error. "darkstar" is not a recognized authority.
3090 ** <tr><td style="white-space:nowrap">
3091 ** file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
3092 ** <td> Windows only: Open the file "data.db" on fred's desktop on drive
3093 ** C:. Note that the %20 escaping in this example is not strictly
3094 ** necessary - space characters can be used literally
3095 ** in URI filenames.
3096 ** <tr><td> file:data.db?mode=ro&cache=private <td>
3097 ** Open file "data.db" in the current directory for read-only access.
3098 ** Regardless of whether or not shared-cache mode is enabled by
3099 ** default, use a private cache.
3100 ** <tr><td> file:/home/fred/data.db?vfs=unix-nolock <td>
3101 ** Open file "/home/fred/data.db". Use the special VFS "unix-nolock".
3102 ** <tr><td> file:data.db?mode=readonly <td>
3103 ** An error. "readonly" is not a valid option for the "mode" parameter.
3104 ** </table>
3106 ** ^URI hexadecimal escape sequences (%HH) are supported within the path and
3107 ** query components of a URI. A hexadecimal escape sequence consists of a
3108 ** percent sign - "%" - followed by exactly two hexadecimal digits
3109 ** specifying an octet value. ^Before the path or query components of a
3110 ** URI filename are interpreted, they are encoded using UTF-8 and all
3111 ** hexadecimal escape sequences replaced by a single byte containing the
3112 ** corresponding octet. If this process generates an invalid UTF-8 encoding,
3113 ** the results are undefined.
3115 ** <b>Note to Windows users:</b> The encoding used for the filename argument
3116 ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
3117 ** codepage is currently defined. Filenames containing international
3118 ** characters must be converted to UTF-8 prior to passing them into
3119 ** sqlite3_open() or sqlite3_open_v2().
3121 SQLITE_API int sqlite3_open(
3122 const char *filename, /* Database filename (UTF-8) */
3123 sqlite3 **ppDb /* OUT: SQLite db handle */
3125 SQLITE_API int sqlite3_open16(
3126 const void *filename, /* Database filename (UTF-16) */
3127 sqlite3 **ppDb /* OUT: SQLite db handle */
3129 SQLITE_API int sqlite3_open_v2(
3130 const char *filename, /* Database filename (UTF-8) */
3131 sqlite3 **ppDb, /* OUT: SQLite db handle */
3132 int flags, /* Flags */
3133 const char *zVfs /* Name of VFS module to use */
3137 ** CAPI3REF: Obtain Values For URI Parameters
3139 ** This is a utility routine, useful to VFS implementations, that checks
3140 ** to see if a database file was a URI that contained a specific query
3141 ** parameter, and if so obtains the value of the query parameter.
3143 ** The zFilename argument is the filename pointer passed into the xOpen()
3144 ** method of a VFS implementation. The zParam argument is the name of the
3145 ** query parameter we seek. This routine returns the value of the zParam
3146 ** parameter if it exists. If the parameter does not exist, this routine
3147 ** returns a NULL pointer.
3149 ** If the zFilename argument to this function is not a pointer that SQLite
3150 ** passed into the xOpen VFS method, then the behavior of this routine
3151 ** is undefined and probably undesirable.
3153 SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);
3157 ** CAPI3REF: Error Codes And Messages
3159 ** ^The sqlite3_errcode() interface returns the numeric [result code] or
3160 ** [extended result code] for the most recent failed sqlite3_* API call
3161 ** associated with a [database connection]. If a prior API call failed
3162 ** but the most recent API call succeeded, the return value from
3163 ** sqlite3_errcode() is undefined. ^The sqlite3_extended_errcode()
3164 ** interface is the same except that it always returns the
3165 ** [extended result code] even when extended result codes are
3166 ** disabled.
3168 ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
3169 ** text that describes the error, as either UTF-8 or UTF-16 respectively.
3170 ** ^(Memory to hold the error message string is managed internally.
3171 ** The application does not need to worry about freeing the result.
3172 ** However, the error string might be overwritten or deallocated by
3173 ** subsequent calls to other SQLite interface functions.)^
3175 ** When the serialized [threading mode] is in use, it might be the
3176 ** case that a second error occurs on a separate thread in between
3177 ** the time of the first error and the call to these interfaces.
3178 ** When that happens, the second error will be reported since these
3179 ** interfaces always report the most recent result. To avoid
3180 ** this, each thread can obtain exclusive use of the [database connection] D
3181 ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
3182 ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
3183 ** all calls to the interfaces listed here are completed.
3185 ** If an interface fails with SQLITE_MISUSE, that means the interface
3186 ** was invoked incorrectly by the application. In that case, the
3187 ** error code and message may or may not be set.
3189 SQLITE_API int sqlite3_errcode(sqlite3 *db);
3190 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
3191 SQLITE_API const char *sqlite3_errmsg(sqlite3*);
3192 SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
3195 ** CAPI3REF: SQL Statement Object
3196 ** KEYWORDS: {prepared statement} {prepared statements}
3198 ** An instance of this object represents a single SQL statement.
3199 ** This object is variously known as a "prepared statement" or a
3200 ** "compiled SQL statement" or simply as a "statement".
3202 ** The life of a statement object goes something like this:
3204 ** <ol>
3205 ** <li> Create the object using [sqlite3_prepare_v2()] or a related
3206 ** function.
3207 ** <li> Bind values to [host parameters] using the sqlite3_bind_*()
3208 ** interfaces.
3209 ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
3210 ** <li> Reset the statement using [sqlite3_reset()] then go back
3211 ** to step 2. Do this zero or more times.
3212 ** <li> Destroy the object using [sqlite3_finalize()].
3213 ** </ol>
3215 ** Refer to documentation on individual methods above for additional
3216 ** information.
3218 typedef struct sqlite3_stmt sqlite3_stmt;
3221 ** CAPI3REF: Run-time Limits
3223 ** ^(This interface allows the size of various constructs to be limited
3224 ** on a connection by connection basis. The first parameter is the
3225 ** [database connection] whose limit is to be set or queried. The
3226 ** second parameter is one of the [limit categories] that define a
3227 ** class of constructs to be size limited. The third parameter is the
3228 ** new limit for that construct.)^
3230 ** ^If the new limit is a negative number, the limit is unchanged.
3231 ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
3232 ** [limits | hard upper bound]
3233 ** set at compile-time by a C preprocessor macro called
3234 ** [limits | SQLITE_MAX_<i>NAME</i>].
3235 ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
3236 ** ^Attempts to increase a limit above its hard upper bound are
3237 ** silently truncated to the hard upper bound.
3239 ** ^Regardless of whether or not the limit was changed, the
3240 ** [sqlite3_limit()] interface returns the prior value of the limit.
3241 ** ^Hence, to find the current value of a limit without changing it,
3242 ** simply invoke this interface with the third parameter set to -1.
3244 ** Run-time limits are intended for use in applications that manage
3245 ** both their own internal database and also databases that are controlled
3246 ** by untrusted external sources. An example application might be a
3247 ** web browser that has its own databases for storing history and
3248 ** separate databases controlled by JavaScript applications downloaded
3249 ** off the Internet. The internal databases can be given the
3250 ** large, default limits. Databases managed by external sources can
3251 ** be given much smaller limits designed to prevent a denial of service
3252 ** attack. Developers might also want to use the [sqlite3_set_authorizer()]
3253 ** interface to further control untrusted SQL. The size of the database
3254 ** created by an untrusted script can be contained using the
3255 ** [max_page_count] [PRAGMA].
3257 ** New run-time limit categories may be added in future releases.
3259 SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
3262 ** CAPI3REF: Run-Time Limit Categories
3263 ** KEYWORDS: {limit category} {*limit categories}
3265 ** These constants define various performance limits
3266 ** that can be lowered at run-time using [sqlite3_limit()].
3267 ** The synopsis of the meanings of the various limits is shown below.
3268 ** Additional information is available at [limits | Limits in SQLite].
3270 ** <dl>
3271 ** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
3272 ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
3274 ** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
3275 ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
3277 ** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
3278 ** <dd>The maximum number of columns in a table definition or in the
3279 ** result set of a [SELECT] or the maximum number of columns in an index
3280 ** or in an ORDER BY or GROUP BY clause.</dd>)^
3282 ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
3283 ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
3285 ** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
3286 ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
3288 ** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
3289 ** <dd>The maximum number of instructions in a virtual machine program
3290 ** used to implement an SQL statement. This limit is not currently
3291 ** enforced, though that might be added in some future release of
3292 ** SQLite.</dd>)^
3294 ** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
3295 ** <dd>The maximum number of arguments on a function.</dd>)^
3297 ** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
3298 ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
3300 ** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
3301 ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
3302 ** <dd>The maximum length of the pattern argument to the [LIKE] or
3303 ** [GLOB] operators.</dd>)^
3305 ** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
3306 ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
3307 ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
3309 ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
3310 ** <dd>The maximum depth of recursion for triggers.</dd>)^
3311 ** </dl>
3313 #define SQLITE_LIMIT_LENGTH 0
3314 #define SQLITE_LIMIT_SQL_LENGTH 1
3315 #define SQLITE_LIMIT_COLUMN 2
3316 #define SQLITE_LIMIT_EXPR_DEPTH 3
3317 #define SQLITE_LIMIT_COMPOUND_SELECT 4
3318 #define SQLITE_LIMIT_VDBE_OP 5
3319 #define SQLITE_LIMIT_FUNCTION_ARG 6
3320 #define SQLITE_LIMIT_ATTACHED 7
3321 #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8
3322 #define SQLITE_LIMIT_VARIABLE_NUMBER 9
3323 #define SQLITE_LIMIT_TRIGGER_DEPTH 10
3326 ** CAPI3REF: Compiling An SQL Statement
3327 ** KEYWORDS: {SQL statement compiler}
3329 ** To execute an SQL query, it must first be compiled into a byte-code
3330 ** program using one of these routines.
3332 ** The first argument, "db", is a [database connection] obtained from a
3333 ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
3334 ** [sqlite3_open16()]. The database connection must not have been closed.
3336 ** The second argument, "zSql", is the statement to be compiled, encoded
3337 ** as either UTF-8 or UTF-16. The sqlite3_prepare() and sqlite3_prepare_v2()
3338 ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
3339 ** use UTF-16.
3341 ** ^If the nByte argument is less than zero, then zSql is read up to the
3342 ** first zero terminator. ^If nByte is non-negative, then it is the maximum
3343 ** number of bytes read from zSql. ^When nByte is non-negative, the
3344 ** zSql string ends at either the first '\000' or '\u0000' character or
3345 ** the nByte-th byte, whichever comes first. If the caller knows
3346 ** that the supplied string is nul-terminated, then there is a small
3347 ** performance advantage to be gained by passing an nByte parameter that
3348 ** is equal to the number of bytes in the input string <i>including</i>
3349 ** the nul-terminator bytes as this saves SQLite from having to
3350 ** make a copy of the input string.
3352 ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
3353 ** past the end of the first SQL statement in zSql. These routines only
3354 ** compile the first statement in zSql, so *pzTail is left pointing to
3355 ** what remains uncompiled.
3357 ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
3358 ** executed using [sqlite3_step()]. ^If there is an error, *ppStmt is set
3359 ** to NULL. ^If the input text contains no SQL (if the input is an empty
3360 ** string or a comment) then *ppStmt is set to NULL.
3361 ** The calling procedure is responsible for deleting the compiled
3362 ** SQL statement using [sqlite3_finalize()] after it has finished with it.
3363 ** ppStmt may not be NULL.
3365 ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
3366 ** otherwise an [error code] is returned.
3368 ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
3369 ** recommended for all new programs. The two older interfaces are retained
3370 ** for backwards compatibility, but their use is discouraged.
3371 ** ^In the "v2" interfaces, the prepared statement
3372 ** that is returned (the [sqlite3_stmt] object) contains a copy of the
3373 ** original SQL text. This causes the [sqlite3_step()] interface to
3374 ** behave differently in three ways:
3376 ** <ol>
3377 ** <li>
3378 ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
3379 ** always used to do, [sqlite3_step()] will automatically recompile the SQL
3380 ** statement and try to run it again.
3381 ** </li>
3383 ** <li>
3384 ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
3385 ** [error codes] or [extended error codes]. ^The legacy behavior was that
3386 ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
3387 ** and the application would have to make a second call to [sqlite3_reset()]
3388 ** in order to find the underlying cause of the problem. With the "v2" prepare
3389 ** interfaces, the underlying reason for the error is returned immediately.
3390 ** </li>
3392 ** <li>
3393 ** ^If the specific value bound to [parameter | host parameter] in the
3394 ** WHERE clause might influence the choice of query plan for a statement,
3395 ** then the statement will be automatically recompiled, as if there had been
3396 ** a schema change, on the first [sqlite3_step()] call following any change
3397 ** to the [sqlite3_bind_text | bindings] of that [parameter].
3398 ** ^The specific value of WHERE-clause [parameter] might influence the
3399 ** choice of query plan if the parameter is the left-hand side of a [LIKE]
3400 ** or [GLOB] operator or if the parameter is compared to an indexed column
3401 ** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.
3402 ** the
3403 ** </li>
3404 ** </ol>
3406 SQLITE_API int sqlite3_prepare(
3407 sqlite3 *db, /* Database handle */
3408 const char *zSql, /* SQL statement, UTF-8 encoded */
3409 int nByte, /* Maximum length of zSql in bytes. */
3410 sqlite3_stmt **ppStmt, /* OUT: Statement handle */
3411 const char **pzTail /* OUT: Pointer to unused portion of zSql */
3413 SQLITE_API int sqlite3_prepare_v2(
3414 sqlite3 *db, /* Database handle */
3415 const char *zSql, /* SQL statement, UTF-8 encoded */
3416 int nByte, /* Maximum length of zSql in bytes. */
3417 sqlite3_stmt **ppStmt, /* OUT: Statement handle */
3418 const char **pzTail /* OUT: Pointer to unused portion of zSql */
3420 SQLITE_API int sqlite3_prepare16(
3421 sqlite3 *db, /* Database handle */
3422 const void *zSql, /* SQL statement, UTF-16 encoded */
3423 int nByte, /* Maximum length of zSql in bytes. */
3424 sqlite3_stmt **ppStmt, /* OUT: Statement handle */
3425 const void **pzTail /* OUT: Pointer to unused portion of zSql */
3427 SQLITE_API int sqlite3_prepare16_v2(
3428 sqlite3 *db, /* Database handle */
3429 const void *zSql, /* SQL statement, UTF-16 encoded */
3430 int nByte, /* Maximum length of zSql in bytes. */
3431 sqlite3_stmt **ppStmt, /* OUT: Statement handle */
3432 const void **pzTail /* OUT: Pointer to unused portion of zSql */
3436 ** CAPI3REF: Retrieving Statement SQL
3438 ** ^This interface can be used to retrieve a saved copy of the original
3439 ** SQL text used to create a [prepared statement] if that statement was
3440 ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
3442 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
3445 ** CAPI3REF: Determine If An SQL Statement Writes The Database
3447 ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
3448 ** and only if the [prepared statement] X makes no direct changes to
3449 ** the content of the database file.
3451 ** Note that [application-defined SQL functions] or
3452 ** [virtual tables] might change the database indirectly as a side effect.
3453 ** ^(For example, if an application defines a function "eval()" that
3454 ** calls [sqlite3_exec()], then the following SQL statement would
3455 ** change the database file through side-effects:
3457 ** <blockquote><pre>
3458 ** SELECT eval('DELETE FROM t1') FROM t2;
3459 ** </pre></blockquote>
3461 ** But because the [SELECT] statement does not change the database file
3462 ** directly, sqlite3_stmt_readonly() would still return true.)^
3464 ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
3465 ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
3466 ** since the statements themselves do not actually modify the database but
3467 ** rather they control the timing of when other statements modify the
3468 ** database. ^The [ATTACH] and [DETACH] statements also cause
3469 ** sqlite3_stmt_readonly() to return true since, while those statements
3470 ** change the configuration of a database connection, they do not make
3471 ** changes to the content of the database files on disk.
3473 SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
3476 ** CAPI3REF: Dynamically Typed Value Object
3477 ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
3479 ** SQLite uses the sqlite3_value object to represent all values
3480 ** that can be stored in a database table. SQLite uses dynamic typing
3481 ** for the values it stores. ^Values stored in sqlite3_value objects
3482 ** can be integers, floating point values, strings, BLOBs, or NULL.
3484 ** An sqlite3_value object may be either "protected" or "unprotected".
3485 ** Some interfaces require a protected sqlite3_value. Other interfaces
3486 ** will accept either a protected or an unprotected sqlite3_value.
3487 ** Every interface that accepts sqlite3_value arguments specifies
3488 ** whether or not it requires a protected sqlite3_value.
3490 ** The terms "protected" and "unprotected" refer to whether or not
3491 ** a mutex is held. An internal mutex is held for a protected
3492 ** sqlite3_value object but no mutex is held for an unprotected
3493 ** sqlite3_value object. If SQLite is compiled to be single-threaded
3494 ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
3495 ** or if SQLite is run in one of reduced mutex modes
3496 ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
3497 ** then there is no distinction between protected and unprotected
3498 ** sqlite3_value objects and they can be used interchangeably. However,
3499 ** for maximum code portability it is recommended that applications
3500 ** still make the distinction between protected and unprotected
3501 ** sqlite3_value objects even when not strictly required.
3503 ** ^The sqlite3_value objects that are passed as parameters into the
3504 ** implementation of [application-defined SQL functions] are protected.
3505 ** ^The sqlite3_value object returned by
3506 ** [sqlite3_column_value()] is unprotected.
3507 ** Unprotected sqlite3_value objects may only be used with
3508 ** [sqlite3_result_value()] and [sqlite3_bind_value()].
3509 ** The [sqlite3_value_blob | sqlite3_value_type()] family of
3510 ** interfaces require protected sqlite3_value objects.
3512 typedef struct Mem sqlite3_value;
3515 ** CAPI3REF: SQL Function Context Object
3517 ** The context in which an SQL function executes is stored in an
3518 ** sqlite3_context object. ^A pointer to an sqlite3_context object
3519 ** is always first parameter to [application-defined SQL functions].
3520 ** The application-defined SQL function implementation will pass this
3521 ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
3522 ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
3523 ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
3524 ** and/or [sqlite3_set_auxdata()].
3526 typedef struct sqlite3_context sqlite3_context;
3529 ** CAPI3REF: Binding Values To Prepared Statements
3530 ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
3531 ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
3533 ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
3534 ** literals may be replaced by a [parameter] that matches one of following
3535 ** templates:
3537 ** <ul>
3538 ** <li> ?
3539 ** <li> ?NNN
3540 ** <li> :VVV
3541 ** <li> @VVV
3542 ** <li> $VVV
3543 ** </ul>
3545 ** In the templates above, NNN represents an integer literal,
3546 ** and VVV represents an alphanumeric identifier.)^ ^The values of these
3547 ** parameters (also called "host parameter names" or "SQL parameters")
3548 ** can be set using the sqlite3_bind_*() routines defined here.
3550 ** ^The first argument to the sqlite3_bind_*() routines is always
3551 ** a pointer to the [sqlite3_stmt] object returned from
3552 ** [sqlite3_prepare_v2()] or its variants.
3554 ** ^The second argument is the index of the SQL parameter to be set.
3555 ** ^The leftmost SQL parameter has an index of 1. ^When the same named
3556 ** SQL parameter is used more than once, second and subsequent
3557 ** occurrences have the same index as the first occurrence.
3558 ** ^The index for named parameters can be looked up using the
3559 ** [sqlite3_bind_parameter_index()] API if desired. ^The index
3560 ** for "?NNN" parameters is the value of NNN.
3561 ** ^The NNN value must be between 1 and the [sqlite3_limit()]
3562 ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
3564 ** ^The third argument is the value to bind to the parameter.
3566 ** ^(In those routines that have a fourth argument, its value is the
3567 ** number of bytes in the parameter. To be clear: the value is the
3568 ** number of <u>bytes</u> in the value, not the number of characters.)^
3569 ** ^If the fourth parameter is negative, the length of the string is
3570 ** the number of bytes up to the first zero terminator.
3571 ** If a non-negative fourth parameter is provided to sqlite3_bind_text()
3572 ** or sqlite3_bind_text16() then that parameter must be the byte offset
3573 ** where the NUL terminator would occur assuming the string were NUL
3574 ** terminated. If any NUL characters occur at byte offsets less than
3575 ** the value of the fourth parameter then the resulting string value will
3576 ** contain embedded NULs. The result of expressions involving strings
3577 ** with embedded NULs is undefined.
3579 ** ^The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
3580 ** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
3581 ** string after SQLite has finished with it. ^The destructor is called
3582 ** to dispose of the BLOB or string even if the call to sqlite3_bind_blob(),
3583 ** sqlite3_bind_text(), or sqlite3_bind_text16() fails.
3584 ** ^If the fifth argument is
3585 ** the special value [SQLITE_STATIC], then SQLite assumes that the
3586 ** information is in static, unmanaged space and does not need to be freed.
3587 ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
3588 ** SQLite makes its own private copy of the data immediately, before
3589 ** the sqlite3_bind_*() routine returns.
3591 ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
3592 ** is filled with zeroes. ^A zeroblob uses a fixed amount of memory
3593 ** (just an integer to hold its size) while it is being processed.
3594 ** Zeroblobs are intended to serve as placeholders for BLOBs whose
3595 ** content is later written using
3596 ** [sqlite3_blob_open | incremental BLOB I/O] routines.
3597 ** ^A negative value for the zeroblob results in a zero-length BLOB.
3599 ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
3600 ** for the [prepared statement] or with a prepared statement for which
3601 ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
3602 ** then the call will return [SQLITE_MISUSE]. If any sqlite3_bind_()
3603 ** routine is passed a [prepared statement] that has been finalized, the
3604 ** result is undefined and probably harmful.
3606 ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
3607 ** ^Unbound parameters are interpreted as NULL.
3609 ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
3610 ** [error code] if anything goes wrong.
3611 ** ^[SQLITE_RANGE] is returned if the parameter
3612 ** index is out of range. ^[SQLITE_NOMEM] is returned if malloc() fails.
3614 ** See also: [sqlite3_bind_parameter_count()],
3615 ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
3617 SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
3618 SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
3619 SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
3620 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
3621 SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
3622 SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
3623 SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
3624 SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
3625 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
3628 ** CAPI3REF: Number Of SQL Parameters
3630 ** ^This routine can be used to find the number of [SQL parameters]
3631 ** in a [prepared statement]. SQL parameters are tokens of the
3632 ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
3633 ** placeholders for values that are [sqlite3_bind_blob | bound]
3634 ** to the parameters at a later time.
3636 ** ^(This routine actually returns the index of the largest (rightmost)
3637 ** parameter. For all forms except ?NNN, this will correspond to the
3638 ** number of unique parameters. If parameters of the ?NNN form are used,
3639 ** there may be gaps in the list.)^
3641 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3642 ** [sqlite3_bind_parameter_name()], and
3643 ** [sqlite3_bind_parameter_index()].
3645 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
3648 ** CAPI3REF: Name Of A Host Parameter
3650 ** ^The sqlite3_bind_parameter_name(P,N) interface returns
3651 ** the name of the N-th [SQL parameter] in the [prepared statement] P.
3652 ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
3653 ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
3654 ** respectively.
3655 ** In other words, the initial ":" or "$" or "@" or "?"
3656 ** is included as part of the name.)^
3657 ** ^Parameters of the form "?" without a following integer have no name
3658 ** and are referred to as "nameless" or "anonymous parameters".
3660 ** ^The first host parameter has an index of 1, not 0.
3662 ** ^If the value N is out of range or if the N-th parameter is
3663 ** nameless, then NULL is returned. ^The returned string is
3664 ** always in UTF-8 encoding even if the named parameter was
3665 ** originally specified as UTF-16 in [sqlite3_prepare16()] or
3666 ** [sqlite3_prepare16_v2()].
3668 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3669 ** [sqlite3_bind_parameter_count()], and
3670 ** [sqlite3_bind_parameter_index()].
3672 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
3675 ** CAPI3REF: Index Of A Parameter With A Given Name
3677 ** ^Return the index of an SQL parameter given its name. ^The
3678 ** index value returned is suitable for use as the second
3679 ** parameter to [sqlite3_bind_blob|sqlite3_bind()]. ^A zero
3680 ** is returned if no matching parameter is found. ^The parameter
3681 ** name must be given in UTF-8 even if the original statement
3682 ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
3684 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3685 ** [sqlite3_bind_parameter_count()], and
3686 ** [sqlite3_bind_parameter_index()].
3688 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
3691 ** CAPI3REF: Reset All Bindings On A Prepared Statement
3693 ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
3694 ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
3695 ** ^Use this routine to reset all host parameters to NULL.
3697 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
3700 ** CAPI3REF: Number Of Columns In A Result Set
3702 ** ^Return the number of columns in the result set returned by the
3703 ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
3704 ** statement that does not return data (for example an [UPDATE]).
3706 ** See also: [sqlite3_data_count()]
3708 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
3711 ** CAPI3REF: Column Names In A Result Set
3713 ** ^These routines return the name assigned to a particular column
3714 ** in the result set of a [SELECT] statement. ^The sqlite3_column_name()
3715 ** interface returns a pointer to a zero-terminated UTF-8 string
3716 ** and sqlite3_column_name16() returns a pointer to a zero-terminated
3717 ** UTF-16 string. ^The first parameter is the [prepared statement]
3718 ** that implements the [SELECT] statement. ^The second parameter is the
3719 ** column number. ^The leftmost column is number 0.
3721 ** ^The returned string pointer is valid until either the [prepared statement]
3722 ** is destroyed by [sqlite3_finalize()] or until the statement is automatically
3723 ** reprepared by the first call to [sqlite3_step()] for a particular run
3724 ** or until the next call to
3725 ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
3727 ** ^If sqlite3_malloc() fails during the processing of either routine
3728 ** (for example during a conversion from UTF-8 to UTF-16) then a
3729 ** NULL pointer is returned.
3731 ** ^The name of a result column is the value of the "AS" clause for
3732 ** that column, if there is an AS clause. If there is no AS clause
3733 ** then the name of the column is unspecified and may change from
3734 ** one release of SQLite to the next.
3736 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
3737 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
3740 ** CAPI3REF: Source Of Data In A Query Result
3742 ** ^These routines provide a means to determine the database, table, and
3743 ** table column that is the origin of a particular result column in
3744 ** [SELECT] statement.
3745 ** ^The name of the database or table or column can be returned as
3746 ** either a UTF-8 or UTF-16 string. ^The _database_ routines return
3747 ** the database name, the _table_ routines return the table name, and
3748 ** the origin_ routines return the column name.
3749 ** ^The returned string is valid until the [prepared statement] is destroyed
3750 ** using [sqlite3_finalize()] or until the statement is automatically
3751 ** reprepared by the first call to [sqlite3_step()] for a particular run
3752 ** or until the same information is requested
3753 ** again in a different encoding.
3755 ** ^The names returned are the original un-aliased names of the
3756 ** database, table, and column.
3758 ** ^The first argument to these interfaces is a [prepared statement].
3759 ** ^These functions return information about the Nth result column returned by
3760 ** the statement, where N is the second function argument.
3761 ** ^The left-most column is column 0 for these routines.
3763 ** ^If the Nth column returned by the statement is an expression or
3764 ** subquery and is not a column value, then all of these functions return
3765 ** NULL. ^These routine might also return NULL if a memory allocation error
3766 ** occurs. ^Otherwise, they return the name of the attached database, table,
3767 ** or column that query result column was extracted from.
3769 ** ^As with all other SQLite APIs, those whose names end with "16" return
3770 ** UTF-16 encoded strings and the other functions return UTF-8.
3772 ** ^These APIs are only available if the library was compiled with the
3773 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
3775 ** If two or more threads call one or more of these routines against the same
3776 ** prepared statement and column at the same time then the results are
3777 ** undefined.
3779 ** If two or more threads call one or more
3780 ** [sqlite3_column_database_name | column metadata interfaces]
3781 ** for the same [prepared statement] and result column
3782 ** at the same time then the results are undefined.
3784 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
3785 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
3786 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
3787 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
3788 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
3789 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
3792 ** CAPI3REF: Declared Datatype Of A Query Result
3794 ** ^(The first parameter is a [prepared statement].
3795 ** If this statement is a [SELECT] statement and the Nth column of the
3796 ** returned result set of that [SELECT] is a table column (not an
3797 ** expression or subquery) then the declared type of the table
3798 ** column is returned.)^ ^If the Nth column of the result set is an
3799 ** expression or subquery, then a NULL pointer is returned.
3800 ** ^The returned string is always UTF-8 encoded.
3802 ** ^(For example, given the database schema:
3804 ** CREATE TABLE t1(c1 VARIANT);
3806 ** and the following statement to be compiled:
3808 ** SELECT c1 + 1, c1 FROM t1;
3810 ** this routine would return the string "VARIANT" for the second result
3811 ** column (i==1), and a NULL pointer for the first result column (i==0).)^
3813 ** ^SQLite uses dynamic run-time typing. ^So just because a column
3814 ** is declared to contain a particular type does not mean that the
3815 ** data stored in that column is of the declared type. SQLite is
3816 ** strongly typed, but the typing is dynamic not static. ^Type
3817 ** is associated with individual values, not with the containers
3818 ** used to hold those values.
3820 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
3821 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
3824 ** CAPI3REF: Evaluate An SQL Statement
3826 ** After a [prepared statement] has been prepared using either
3827 ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
3828 ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
3829 ** must be called one or more times to evaluate the statement.
3831 ** The details of the behavior of the sqlite3_step() interface depend
3832 ** on whether the statement was prepared using the newer "v2" interface
3833 ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
3834 ** interface [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the
3835 ** new "v2" interface is recommended for new applications but the legacy
3836 ** interface will continue to be supported.
3838 ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
3839 ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
3840 ** ^With the "v2" interface, any of the other [result codes] or
3841 ** [extended result codes] might be returned as well.
3843 ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
3844 ** database locks it needs to do its job. ^If the statement is a [COMMIT]
3845 ** or occurs outside of an explicit transaction, then you can retry the
3846 ** statement. If the statement is not a [COMMIT] and occurs within an
3847 ** explicit transaction then you should rollback the transaction before
3848 ** continuing.
3850 ** ^[SQLITE_DONE] means that the statement has finished executing
3851 ** successfully. sqlite3_step() should not be called again on this virtual
3852 ** machine without first calling [sqlite3_reset()] to reset the virtual
3853 ** machine back to its initial state.
3855 ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
3856 ** is returned each time a new row of data is ready for processing by the
3857 ** caller. The values may be accessed using the [column access functions].
3858 ** sqlite3_step() is called again to retrieve the next row of data.
3860 ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
3861 ** violation) has occurred. sqlite3_step() should not be called again on
3862 ** the VM. More information may be found by calling [sqlite3_errmsg()].
3863 ** ^With the legacy interface, a more specific error code (for example,
3864 ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
3865 ** can be obtained by calling [sqlite3_reset()] on the
3866 ** [prepared statement]. ^In the "v2" interface,
3867 ** the more specific error code is returned directly by sqlite3_step().
3869 ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
3870 ** Perhaps it was called on a [prepared statement] that has
3871 ** already been [sqlite3_finalize | finalized] or on one that had
3872 ** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could
3873 ** be the case that the same database connection is being used by two or
3874 ** more threads at the same moment in time.
3876 ** For all versions of SQLite up to and including 3.6.23.1, a call to
3877 ** [sqlite3_reset()] was required after sqlite3_step() returned anything
3878 ** other than [SQLITE_ROW] before any subsequent invocation of
3879 ** sqlite3_step(). Failure to reset the prepared statement using
3880 ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
3881 ** sqlite3_step(). But after version 3.6.23.1, sqlite3_step() began
3882 ** calling [sqlite3_reset()] automatically in this circumstance rather
3883 ** than returning [SQLITE_MISUSE]. This is not considered a compatibility
3884 ** break because any application that ever receives an SQLITE_MISUSE error
3885 ** is broken by definition. The [SQLITE_OMIT_AUTORESET] compile-time option
3886 ** can be used to restore the legacy behavior.
3888 ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
3889 ** API always returns a generic error code, [SQLITE_ERROR], following any
3890 ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call
3891 ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
3892 ** specific [error codes] that better describes the error.
3893 ** We admit that this is a goofy design. The problem has been fixed
3894 ** with the "v2" interface. If you prepare all of your SQL statements
3895 ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
3896 ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
3897 ** then the more specific [error codes] are returned directly
3898 ** by sqlite3_step(). The use of the "v2" interface is recommended.
3900 SQLITE_API int sqlite3_step(sqlite3_stmt*);
3903 ** CAPI3REF: Number of columns in a result set
3905 ** ^The sqlite3_data_count(P) interface returns the number of columns in the
3906 ** current row of the result set of [prepared statement] P.
3907 ** ^If prepared statement P does not have results ready to return
3908 ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
3909 ** interfaces) then sqlite3_data_count(P) returns 0.
3910 ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
3911 ** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
3912 ** [sqlite3_step](P) returned [SQLITE_DONE]. ^The sqlite3_data_count(P)
3913 ** will return non-zero if previous call to [sqlite3_step](P) returned
3914 ** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
3915 ** where it always returns zero since each step of that multi-step
3916 ** pragma returns 0 columns of data.
3918 ** See also: [sqlite3_column_count()]
3920 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
3923 ** CAPI3REF: Fundamental Datatypes
3924 ** KEYWORDS: SQLITE_TEXT
3926 ** ^(Every value in SQLite has one of five fundamental datatypes:
3928 ** <ul>
3929 ** <li> 64-bit signed integer
3930 ** <li> 64-bit IEEE floating point number
3931 ** <li> string
3932 ** <li> BLOB
3933 ** <li> NULL
3934 ** </ul>)^
3936 ** These constants are codes for each of those types.
3938 ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
3939 ** for a completely different meaning. Software that links against both
3940 ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
3941 ** SQLITE_TEXT.
3943 #define SQLITE_INTEGER 1
3944 #define SQLITE_FLOAT 2
3945 #define SQLITE_BLOB 4
3946 #define SQLITE_NULL 5
3947 #ifdef SQLITE_TEXT
3948 # undef SQLITE_TEXT
3949 #else
3950 # define SQLITE_TEXT 3
3951 #endif
3952 #define SQLITE3_TEXT 3
3955 ** CAPI3REF: Result Values From A Query
3956 ** KEYWORDS: {column access functions}
3958 ** These routines form the "result set" interface.
3960 ** ^These routines return information about a single column of the current
3961 ** result row of a query. ^In every case the first argument is a pointer
3962 ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
3963 ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
3964 ** and the second argument is the index of the column for which information
3965 ** should be returned. ^The leftmost column of the result set has the index 0.
3966 ** ^The number of columns in the result can be determined using
3967 ** [sqlite3_column_count()].
3969 ** If the SQL statement does not currently point to a valid row, or if the
3970 ** column index is out of range, the result is undefined.
3971 ** These routines may only be called when the most recent call to
3972 ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
3973 ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
3974 ** If any of these routines are called after [sqlite3_reset()] or
3975 ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
3976 ** something other than [SQLITE_ROW], the results are undefined.
3977 ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
3978 ** are called from a different thread while any of these routines
3979 ** are pending, then the results are undefined.
3981 ** ^The sqlite3_column_type() routine returns the
3982 ** [SQLITE_INTEGER | datatype code] for the initial data type
3983 ** of the result column. ^The returned value is one of [SQLITE_INTEGER],
3984 ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. The value
3985 ** returned by sqlite3_column_type() is only meaningful if no type
3986 ** conversions have occurred as described below. After a type conversion,
3987 ** the value returned by sqlite3_column_type() is undefined. Future
3988 ** versions of SQLite may change the behavior of sqlite3_column_type()
3989 ** following a type conversion.
3991 ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
3992 ** routine returns the number of bytes in that BLOB or string.
3993 ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
3994 ** the string to UTF-8 and then returns the number of bytes.
3995 ** ^If the result is a numeric value then sqlite3_column_bytes() uses
3996 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
3997 ** the number of bytes in that string.
3998 ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
4000 ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
4001 ** routine returns the number of bytes in that BLOB or string.
4002 ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
4003 ** the string to UTF-16 and then returns the number of bytes.
4004 ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
4005 ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
4006 ** the number of bytes in that string.
4007 ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
4009 ** ^The values returned by [sqlite3_column_bytes()] and
4010 ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
4011 ** of the string. ^For clarity: the values returned by
4012 ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
4013 ** bytes in the string, not the number of characters.
4015 ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
4016 ** even empty strings, are always zero terminated. ^The return
4017 ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
4019 ** ^The object returned by [sqlite3_column_value()] is an
4020 ** [unprotected sqlite3_value] object. An unprotected sqlite3_value object
4021 ** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
4022 ** If the [unprotected sqlite3_value] object returned by
4023 ** [sqlite3_column_value()] is used in any other way, including calls
4024 ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
4025 ** or [sqlite3_value_bytes()], then the behavior is undefined.
4027 ** These routines attempt to convert the value where appropriate. ^For
4028 ** example, if the internal representation is FLOAT and a text result
4029 ** is requested, [sqlite3_snprintf()] is used internally to perform the
4030 ** conversion automatically. ^(The following table details the conversions
4031 ** that are applied:
4033 ** <blockquote>
4034 ** <table border="1">
4035 ** <tr><th> Internal<br>Type <th> Requested<br>Type <th> Conversion
4037 ** <tr><td> NULL <td> INTEGER <td> Result is 0
4038 ** <tr><td> NULL <td> FLOAT <td> Result is 0.0
4039 ** <tr><td> NULL <td> TEXT <td> Result is NULL pointer
4040 ** <tr><td> NULL <td> BLOB <td> Result is NULL pointer
4041 ** <tr><td> INTEGER <td> FLOAT <td> Convert from integer to float
4042 ** <tr><td> INTEGER <td> TEXT <td> ASCII rendering of the integer
4043 ** <tr><td> INTEGER <td> BLOB <td> Same as INTEGER->TEXT
4044 ** <tr><td> FLOAT <td> INTEGER <td> Convert from float to integer
4045 ** <tr><td> FLOAT <td> TEXT <td> ASCII rendering of the float
4046 ** <tr><td> FLOAT <td> BLOB <td> Same as FLOAT->TEXT
4047 ** <tr><td> TEXT <td> INTEGER <td> Use atoi()
4048 ** <tr><td> TEXT <td> FLOAT <td> Use atof()
4049 ** <tr><td> TEXT <td> BLOB <td> No change
4050 ** <tr><td> BLOB <td> INTEGER <td> Convert to TEXT then use atoi()
4051 ** <tr><td> BLOB <td> FLOAT <td> Convert to TEXT then use atof()
4052 ** <tr><td> BLOB <td> TEXT <td> Add a zero terminator if needed
4053 ** </table>
4054 ** </blockquote>)^
4056 ** The table above makes reference to standard C library functions atoi()
4057 ** and atof(). SQLite does not really use these functions. It has its
4058 ** own equivalent internal routines. The atoi() and atof() names are
4059 ** used in the table for brevity and because they are familiar to most
4060 ** C programmers.
4062 ** Note that when type conversions occur, pointers returned by prior
4063 ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
4064 ** sqlite3_column_text16() may be invalidated.
4065 ** Type conversions and pointer invalidations might occur
4066 ** in the following cases:
4068 ** <ul>
4069 ** <li> The initial content is a BLOB and sqlite3_column_text() or
4070 ** sqlite3_column_text16() is called. A zero-terminator might
4071 ** need to be added to the string.</li>
4072 ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
4073 ** sqlite3_column_text16() is called. The content must be converted
4074 ** to UTF-16.</li>
4075 ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
4076 ** sqlite3_column_text() is called. The content must be converted
4077 ** to UTF-8.</li>
4078 ** </ul>
4080 ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
4081 ** not invalidate a prior pointer, though of course the content of the buffer
4082 ** that the prior pointer references will have been modified. Other kinds
4083 ** of conversion are done in place when it is possible, but sometimes they
4084 ** are not possible and in those cases prior pointers are invalidated.
4086 ** The safest and easiest to remember policy is to invoke these routines
4087 ** in one of the following ways:
4089 ** <ul>
4090 ** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
4091 ** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
4092 ** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
4093 ** </ul>
4095 ** In other words, you should call sqlite3_column_text(),
4096 ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
4097 ** into the desired format, then invoke sqlite3_column_bytes() or
4098 ** sqlite3_column_bytes16() to find the size of the result. Do not mix calls
4099 ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
4100 ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
4101 ** with calls to sqlite3_column_bytes().
4103 ** ^The pointers returned are valid until a type conversion occurs as
4104 ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
4105 ** [sqlite3_finalize()] is called. ^The memory space used to hold strings
4106 ** and BLOBs is freed automatically. Do <b>not</b> pass the pointers returned
4107 ** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
4108 ** [sqlite3_free()].
4110 ** ^(If a memory allocation error occurs during the evaluation of any
4111 ** of these routines, a default value is returned. The default value
4112 ** is either the integer 0, the floating point number 0.0, or a NULL
4113 ** pointer. Subsequent calls to [sqlite3_errcode()] will return
4114 ** [SQLITE_NOMEM].)^
4116 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
4117 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
4118 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
4119 SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
4120 SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
4121 SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
4122 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
4123 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
4124 SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
4125 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
4128 ** CAPI3REF: Destroy A Prepared Statement Object
4130 ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
4131 ** ^If the most recent evaluation of the statement encountered no errors
4132 ** or if the statement is never been evaluated, then sqlite3_finalize() returns
4133 ** SQLITE_OK. ^If the most recent evaluation of statement S failed, then
4134 ** sqlite3_finalize(S) returns the appropriate [error code] or
4135 ** [extended error code].
4137 ** ^The sqlite3_finalize(S) routine can be called at any point during
4138 ** the life cycle of [prepared statement] S:
4139 ** before statement S is ever evaluated, after
4140 ** one or more calls to [sqlite3_reset()], or after any call
4141 ** to [sqlite3_step()] regardless of whether or not the statement has
4142 ** completed execution.
4144 ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
4146 ** The application must finalize every [prepared statement] in order to avoid
4147 ** resource leaks. It is a grievous error for the application to try to use
4148 ** a prepared statement after it has been finalized. Any use of a prepared
4149 ** statement after it has been finalized can result in undefined and
4150 ** undesirable behavior such as segfaults and heap corruption.
4152 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
4155 ** CAPI3REF: Reset A Prepared Statement Object
4157 ** The sqlite3_reset() function is called to reset a [prepared statement]
4158 ** object back to its initial state, ready to be re-executed.
4159 ** ^Any SQL statement variables that had values bound to them using
4160 ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
4161 ** Use [sqlite3_clear_bindings()] to reset the bindings.
4163 ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
4164 ** back to the beginning of its program.
4166 ** ^If the most recent call to [sqlite3_step(S)] for the
4167 ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
4168 ** or if [sqlite3_step(S)] has never before been called on S,
4169 ** then [sqlite3_reset(S)] returns [SQLITE_OK].
4171 ** ^If the most recent call to [sqlite3_step(S)] for the
4172 ** [prepared statement] S indicated an error, then
4173 ** [sqlite3_reset(S)] returns an appropriate [error code].
4175 ** ^The [sqlite3_reset(S)] interface does not change the values
4176 ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
4178 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
4181 ** CAPI3REF: Create Or Redefine SQL Functions
4182 ** KEYWORDS: {function creation routines}
4183 ** KEYWORDS: {application-defined SQL function}
4184 ** KEYWORDS: {application-defined SQL functions}
4186 ** ^These functions (collectively known as "function creation routines")
4187 ** are used to add SQL functions or aggregates or to redefine the behavior
4188 ** of existing SQL functions or aggregates. The only differences between
4189 ** these routines are the text encoding expected for
4190 ** the second parameter (the name of the function being created)
4191 ** and the presence or absence of a destructor callback for
4192 ** the application data pointer.
4194 ** ^The first parameter is the [database connection] to which the SQL
4195 ** function is to be added. ^If an application uses more than one database
4196 ** connection then application-defined SQL functions must be added
4197 ** to each database connection separately.
4199 ** ^The second parameter is the name of the SQL function to be created or
4200 ** redefined. ^The length of the name is limited to 255 bytes in a UTF-8
4201 ** representation, exclusive of the zero-terminator. ^Note that the name
4202 ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
4203 ** ^Any attempt to create a function with a longer name
4204 ** will result in [SQLITE_MISUSE] being returned.
4206 ** ^The third parameter (nArg)
4207 ** is the number of arguments that the SQL function or
4208 ** aggregate takes. ^If this parameter is -1, then the SQL function or
4209 ** aggregate may take any number of arguments between 0 and the limit
4210 ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third
4211 ** parameter is less than -1 or greater than 127 then the behavior is
4212 ** undefined.
4214 ** ^The fourth parameter, eTextRep, specifies what
4215 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
4216 ** its parameters. Every SQL function implementation must be able to work
4217 ** with UTF-8, UTF-16le, or UTF-16be. But some implementations may be
4218 ** more efficient with one encoding than another. ^An application may
4219 ** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
4220 ** times with the same function but with different values of eTextRep.
4221 ** ^When multiple implementations of the same function are available, SQLite
4222 ** will pick the one that involves the least amount of data conversion.
4223 ** If there is only a single implementation which does not care what text
4224 ** encoding is used, then the fourth argument should be [SQLITE_ANY].
4226 ** ^(The fifth parameter is an arbitrary pointer. The implementation of the
4227 ** function can gain access to this pointer using [sqlite3_user_data()].)^
4229 ** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
4230 ** pointers to C-language functions that implement the SQL function or
4231 ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
4232 ** callback only; NULL pointers must be passed as the xStep and xFinal
4233 ** parameters. ^An aggregate SQL function requires an implementation of xStep
4234 ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
4235 ** SQL function or aggregate, pass NULL pointers for all three function
4236 ** callbacks.
4238 ** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
4239 ** then it is destructor for the application data pointer.
4240 ** The destructor is invoked when the function is deleted, either by being
4241 ** overloaded or when the database connection closes.)^
4242 ** ^The destructor is also invoked if the call to
4243 ** sqlite3_create_function_v2() fails.
4244 ** ^When the destructor callback of the tenth parameter is invoked, it
4245 ** is passed a single argument which is a copy of the application data
4246 ** pointer which was the fifth parameter to sqlite3_create_function_v2().
4248 ** ^It is permitted to register multiple implementations of the same
4249 ** functions with the same name but with either differing numbers of
4250 ** arguments or differing preferred text encodings. ^SQLite will use
4251 ** the implementation that most closely matches the way in which the
4252 ** SQL function is used. ^A function implementation with a non-negative
4253 ** nArg parameter is a better match than a function implementation with
4254 ** a negative nArg. ^A function where the preferred text encoding
4255 ** matches the database encoding is a better
4256 ** match than a function where the encoding is different.
4257 ** ^A function where the encoding difference is between UTF16le and UTF16be
4258 ** is a closer match than a function where the encoding difference is
4259 ** between UTF8 and UTF16.
4261 ** ^Built-in functions may be overloaded by new application-defined functions.
4263 ** ^An application-defined function is permitted to call other
4264 ** SQLite interfaces. However, such calls must not
4265 ** close the database connection nor finalize or reset the prepared
4266 ** statement in which the function is running.
4268 SQLITE_API int sqlite3_create_function(
4269 sqlite3 *db,
4270 const char *zFunctionName,
4271 int nArg,
4272 int eTextRep,
4273 void *pApp,
4274 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4275 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4276 void (*xFinal)(sqlite3_context*)
4278 SQLITE_API int sqlite3_create_function16(
4279 sqlite3 *db,
4280 const void *zFunctionName,
4281 int nArg,
4282 int eTextRep,
4283 void *pApp,
4284 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4285 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4286 void (*xFinal)(sqlite3_context*)
4288 SQLITE_API int sqlite3_create_function_v2(
4289 sqlite3 *db,
4290 const char *zFunctionName,
4291 int nArg,
4292 int eTextRep,
4293 void *pApp,
4294 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4295 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4296 void (*xFinal)(sqlite3_context*),
4297 void(*xDestroy)(void*)
4301 ** CAPI3REF: Text Encodings
4303 ** These constant define integer codes that represent the various
4304 ** text encodings supported by SQLite.
4306 #define SQLITE_UTF8 1
4307 #define SQLITE_UTF16LE 2
4308 #define SQLITE_UTF16BE 3
4309 #define SQLITE_UTF16 4 /* Use native byte order */
4310 #define SQLITE_ANY 5 /* sqlite3_create_function only */
4311 #define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */
4314 ** CAPI3REF: Deprecated Functions
4315 ** DEPRECATED
4317 ** These functions are [deprecated]. In order to maintain
4318 ** backwards compatibility with older code, these functions continue
4319 ** to be supported. However, new applications should avoid
4320 ** the use of these functions. To help encourage people to avoid
4321 ** using these functions, we are not going to tell you what they do.
4323 #ifndef SQLITE_OMIT_DEPRECATED
4324 SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
4325 SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
4326 SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
4327 SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
4328 SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
4329 SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64);
4330 #endif
4333 ** CAPI3REF: Obtaining SQL Function Parameter Values
4335 ** The C-language implementation of SQL functions and aggregates uses
4336 ** this set of interface routines to access the parameter values on
4337 ** the function or aggregate.
4339 ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
4340 ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
4341 ** define callbacks that implement the SQL functions and aggregates.
4342 ** The 3rd parameter to these callbacks is an array of pointers to
4343 ** [protected sqlite3_value] objects. There is one [sqlite3_value] object for
4344 ** each parameter to the SQL function. These routines are used to
4345 ** extract values from the [sqlite3_value] objects.
4347 ** These routines work only with [protected sqlite3_value] objects.
4348 ** Any attempt to use these routines on an [unprotected sqlite3_value]
4349 ** object results in undefined behavior.
4351 ** ^These routines work just like the corresponding [column access functions]
4352 ** except that these routines take a single [protected sqlite3_value] object
4353 ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
4355 ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
4356 ** in the native byte-order of the host machine. ^The
4357 ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
4358 ** extract UTF-16 strings as big-endian and little-endian respectively.
4360 ** ^(The sqlite3_value_numeric_type() interface attempts to apply
4361 ** numeric affinity to the value. This means that an attempt is
4362 ** made to convert the value to an integer or floating point. If
4363 ** such a conversion is possible without loss of information (in other
4364 ** words, if the value is a string that looks like a number)
4365 ** then the conversion is performed. Otherwise no conversion occurs.
4366 ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
4368 ** Please pay particular attention to the fact that the pointer returned
4369 ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
4370 ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
4371 ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
4372 ** or [sqlite3_value_text16()].
4374 ** These routines must be called from the same thread as
4375 ** the SQL function that supplied the [sqlite3_value*] parameters.
4377 SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
4378 SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
4379 SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
4380 SQLITE_API double sqlite3_value_double(sqlite3_value*);
4381 SQLITE_API int sqlite3_value_int(sqlite3_value*);
4382 SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
4383 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
4384 SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
4385 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
4386 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
4387 SQLITE_API int sqlite3_value_type(sqlite3_value*);
4388 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
4391 ** CAPI3REF: Obtain Aggregate Function Context
4393 ** Implementations of aggregate SQL functions use this
4394 ** routine to allocate memory for storing their state.
4396 ** ^The first time the sqlite3_aggregate_context(C,N) routine is called
4397 ** for a particular aggregate function, SQLite
4398 ** allocates N of memory, zeroes out that memory, and returns a pointer
4399 ** to the new memory. ^On second and subsequent calls to
4400 ** sqlite3_aggregate_context() for the same aggregate function instance,
4401 ** the same buffer is returned. Sqlite3_aggregate_context() is normally
4402 ** called once for each invocation of the xStep callback and then one
4403 ** last time when the xFinal callback is invoked. ^(When no rows match
4404 ** an aggregate query, the xStep() callback of the aggregate function
4405 ** implementation is never called and xFinal() is called exactly once.
4406 ** In those cases, sqlite3_aggregate_context() might be called for the
4407 ** first time from within xFinal().)^
4409 ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer if N is
4410 ** less than or equal to zero or if a memory allocate error occurs.
4412 ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
4413 ** determined by the N parameter on first successful call. Changing the
4414 ** value of N in subsequent call to sqlite3_aggregate_context() within
4415 ** the same aggregate function instance will not resize the memory
4416 ** allocation.)^
4418 ** ^SQLite automatically frees the memory allocated by
4419 ** sqlite3_aggregate_context() when the aggregate query concludes.
4421 ** The first parameter must be a copy of the
4422 ** [sqlite3_context | SQL function context] that is the first parameter
4423 ** to the xStep or xFinal callback routine that implements the aggregate
4424 ** function.
4426 ** This routine must be called from the same thread in which
4427 ** the aggregate SQL function is running.
4429 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
4432 ** CAPI3REF: User Data For Functions
4434 ** ^The sqlite3_user_data() interface returns a copy of
4435 ** the pointer that was the pUserData parameter (the 5th parameter)
4436 ** of the [sqlite3_create_function()]
4437 ** and [sqlite3_create_function16()] routines that originally
4438 ** registered the application defined function.
4440 ** This routine must be called from the same thread in which
4441 ** the application-defined function is running.
4443 SQLITE_API void *sqlite3_user_data(sqlite3_context*);
4446 ** CAPI3REF: Database Connection For Functions
4448 ** ^The sqlite3_context_db_handle() interface returns a copy of
4449 ** the pointer to the [database connection] (the 1st parameter)
4450 ** of the [sqlite3_create_function()]
4451 ** and [sqlite3_create_function16()] routines that originally
4452 ** registered the application defined function.
4454 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
4457 ** CAPI3REF: Function Auxiliary Data
4459 ** The following two functions may be used by scalar SQL functions to
4460 ** associate metadata with argument values. If the same value is passed to
4461 ** multiple invocations of the same SQL function during query execution, under
4462 ** some circumstances the associated metadata may be preserved. This may
4463 ** be used, for example, to add a regular-expression matching scalar
4464 ** function. The compiled version of the regular expression is stored as
4465 ** metadata associated with the SQL value passed as the regular expression
4466 ** pattern. The compiled regular expression can be reused on multiple
4467 ** invocations of the same function so that the original pattern string
4468 ** does not need to be recompiled on each invocation.
4470 ** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
4471 ** associated by the sqlite3_set_auxdata() function with the Nth argument
4472 ** value to the application-defined function. ^If no metadata has been ever
4473 ** been set for the Nth argument of the function, or if the corresponding
4474 ** function parameter has changed since the meta-data was set,
4475 ** then sqlite3_get_auxdata() returns a NULL pointer.
4477 ** ^The sqlite3_set_auxdata() interface saves the metadata
4478 ** pointed to by its 3rd parameter as the metadata for the N-th
4479 ** argument of the application-defined function. Subsequent
4480 ** calls to sqlite3_get_auxdata() might return this data, if it has
4481 ** not been destroyed.
4482 ** ^If it is not NULL, SQLite will invoke the destructor
4483 ** function given by the 4th parameter to sqlite3_set_auxdata() on
4484 ** the metadata when the corresponding function parameter changes
4485 ** or when the SQL statement completes, whichever comes first.
4487 ** SQLite is free to call the destructor and drop metadata on any
4488 ** parameter of any function at any time. ^The only guarantee is that
4489 ** the destructor will be called before the metadata is dropped.
4491 ** ^(In practice, metadata is preserved between function calls for
4492 ** expressions that are constant at compile time. This includes literal
4493 ** values and [parameters].)^
4495 ** These routines must be called from the same thread in which
4496 ** the SQL function is running.
4498 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
4499 SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
4503 ** CAPI3REF: Constants Defining Special Destructor Behavior
4505 ** These are special values for the destructor that is passed in as the
4506 ** final argument to routines like [sqlite3_result_blob()]. ^If the destructor
4507 ** argument is SQLITE_STATIC, it means that the content pointer is constant
4508 ** and will never change. It does not need to be destroyed. ^The
4509 ** SQLITE_TRANSIENT value means that the content will likely change in
4510 ** the near future and that SQLite should make its own private copy of
4511 ** the content before returning.
4513 ** The typedef is necessary to work around problems in certain
4514 ** C++ compilers. See ticket #2191.
4516 typedef void (*sqlite3_destructor_type)(void*);
4517 #define SQLITE_STATIC ((sqlite3_destructor_type)0)
4518 #define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1)
4521 ** CAPI3REF: Setting The Result Of An SQL Function
4523 ** These routines are used by the xFunc or xFinal callbacks that
4524 ** implement SQL functions and aggregates. See
4525 ** [sqlite3_create_function()] and [sqlite3_create_function16()]
4526 ** for additional information.
4528 ** These functions work very much like the [parameter binding] family of
4529 ** functions used to bind values to host parameters in prepared statements.
4530 ** Refer to the [SQL parameter] documentation for additional information.
4532 ** ^The sqlite3_result_blob() interface sets the result from
4533 ** an application-defined function to be the BLOB whose content is pointed
4534 ** to by the second parameter and which is N bytes long where N is the
4535 ** third parameter.
4537 ** ^The sqlite3_result_zeroblob() interfaces set the result of
4538 ** the application-defined function to be a BLOB containing all zero
4539 ** bytes and N bytes in size, where N is the value of the 2nd parameter.
4541 ** ^The sqlite3_result_double() interface sets the result from
4542 ** an application-defined function to be a floating point value specified
4543 ** by its 2nd argument.
4545 ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
4546 ** cause the implemented SQL function to throw an exception.
4547 ** ^SQLite uses the string pointed to by the
4548 ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
4549 ** as the text of an error message. ^SQLite interprets the error
4550 ** message string from sqlite3_result_error() as UTF-8. ^SQLite
4551 ** interprets the string from sqlite3_result_error16() as UTF-16 in native
4552 ** byte order. ^If the third parameter to sqlite3_result_error()
4553 ** or sqlite3_result_error16() is negative then SQLite takes as the error
4554 ** message all text up through the first zero character.
4555 ** ^If the third parameter to sqlite3_result_error() or
4556 ** sqlite3_result_error16() is non-negative then SQLite takes that many
4557 ** bytes (not characters) from the 2nd parameter as the error message.
4558 ** ^The sqlite3_result_error() and sqlite3_result_error16()
4559 ** routines make a private copy of the error message text before
4560 ** they return. Hence, the calling function can deallocate or
4561 ** modify the text after they return without harm.
4562 ** ^The sqlite3_result_error_code() function changes the error code
4563 ** returned by SQLite as a result of an error in a function. ^By default,
4564 ** the error code is SQLITE_ERROR. ^A subsequent call to sqlite3_result_error()
4565 ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
4567 ** ^The sqlite3_result_toobig() interface causes SQLite to throw an error
4568 ** indicating that a string or BLOB is too long to represent.
4570 ** ^The sqlite3_result_nomem() interface causes SQLite to throw an error
4571 ** indicating that a memory allocation failed.
4573 ** ^The sqlite3_result_int() interface sets the return value
4574 ** of the application-defined function to be the 32-bit signed integer
4575 ** value given in the 2nd argument.
4576 ** ^The sqlite3_result_int64() interface sets the return value
4577 ** of the application-defined function to be the 64-bit signed integer
4578 ** value given in the 2nd argument.
4580 ** ^The sqlite3_result_null() interface sets the return value
4581 ** of the application-defined function to be NULL.
4583 ** ^The sqlite3_result_text(), sqlite3_result_text16(),
4584 ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
4585 ** set the return value of the application-defined function to be
4586 ** a text string which is represented as UTF-8, UTF-16 native byte order,
4587 ** UTF-16 little endian, or UTF-16 big endian, respectively.
4588 ** ^SQLite takes the text result from the application from
4589 ** the 2nd parameter of the sqlite3_result_text* interfaces.
4590 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4591 ** is negative, then SQLite takes result text from the 2nd parameter
4592 ** through the first zero character.
4593 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4594 ** is non-negative, then as many bytes (not characters) of the text
4595 ** pointed to by the 2nd parameter are taken as the application-defined
4596 ** function result. If the 3rd parameter is non-negative, then it
4597 ** must be the byte offset into the string where the NUL terminator would
4598 ** appear if the string where NUL terminated. If any NUL characters occur
4599 ** in the string at a byte offset that is less than the value of the 3rd
4600 ** parameter, then the resulting string will contain embedded NULs and the
4601 ** result of expressions operating on strings with embedded NULs is undefined.
4602 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
4603 ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
4604 ** function as the destructor on the text or BLOB result when it has
4605 ** finished using that result.
4606 ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
4607 ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
4608 ** assumes that the text or BLOB result is in constant space and does not
4609 ** copy the content of the parameter nor call a destructor on the content
4610 ** when it has finished using that result.
4611 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
4612 ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
4613 ** then SQLite makes a copy of the result into space obtained from
4614 ** from [sqlite3_malloc()] before it returns.
4616 ** ^The sqlite3_result_value() interface sets the result of
4617 ** the application-defined function to be a copy the
4618 ** [unprotected sqlite3_value] object specified by the 2nd parameter. ^The
4619 ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
4620 ** so that the [sqlite3_value] specified in the parameter may change or
4621 ** be deallocated after sqlite3_result_value() returns without harm.
4622 ** ^A [protected sqlite3_value] object may always be used where an
4623 ** [unprotected sqlite3_value] object is required, so either
4624 ** kind of [sqlite3_value] object can be used with this interface.
4626 ** If these routines are called from within the different thread
4627 ** than the one containing the application-defined function that received
4628 ** the [sqlite3_context] pointer, the results are undefined.
4630 SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
4631 SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
4632 SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
4633 SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
4634 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
4635 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
4636 SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
4637 SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
4638 SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
4639 SQLITE_API void sqlite3_result_null(sqlite3_context*);
4640 SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
4641 SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
4642 SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
4643 SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
4644 SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
4645 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
4648 ** CAPI3REF: Define New Collating Sequences
4650 ** ^These functions add, remove, or modify a [collation] associated
4651 ** with the [database connection] specified as the first argument.
4653 ** ^The name of the collation is a UTF-8 string
4654 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
4655 ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
4656 ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
4657 ** considered to be the same name.
4659 ** ^(The third argument (eTextRep) must be one of the constants:
4660 ** <ul>
4661 ** <li> [SQLITE_UTF8],
4662 ** <li> [SQLITE_UTF16LE],
4663 ** <li> [SQLITE_UTF16BE],
4664 ** <li> [SQLITE_UTF16], or
4665 ** <li> [SQLITE_UTF16_ALIGNED].
4666 ** </ul>)^
4667 ** ^The eTextRep argument determines the encoding of strings passed
4668 ** to the collating function callback, xCallback.
4669 ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
4670 ** force strings to be UTF16 with native byte order.
4671 ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
4672 ** on an even byte address.
4674 ** ^The fourth argument, pArg, is an application data pointer that is passed
4675 ** through as the first argument to the collating function callback.
4677 ** ^The fifth argument, xCallback, is a pointer to the collating function.
4678 ** ^Multiple collating functions can be registered using the same name but
4679 ** with different eTextRep parameters and SQLite will use whichever
4680 ** function requires the least amount of data transformation.
4681 ** ^If the xCallback argument is NULL then the collating function is
4682 ** deleted. ^When all collating functions having the same name are deleted,
4683 ** that collation is no longer usable.
4685 ** ^The collating function callback is invoked with a copy of the pArg
4686 ** application data pointer and with two strings in the encoding specified
4687 ** by the eTextRep argument. The collating function must return an
4688 ** integer that is negative, zero, or positive
4689 ** if the first string is less than, equal to, or greater than the second,
4690 ** respectively. A collating function must always return the same answer
4691 ** given the same inputs. If two or more collating functions are registered
4692 ** to the same collation name (using different eTextRep values) then all
4693 ** must give an equivalent answer when invoked with equivalent strings.
4694 ** The collating function must obey the following properties for all
4695 ** strings A, B, and C:
4697 ** <ol>
4698 ** <li> If A==B then B==A.
4699 ** <li> If A==B and B==C then A==C.
4700 ** <li> If A&lt;B THEN B&gt;A.
4701 ** <li> If A&lt;B and B&lt;C then A&lt;C.
4702 ** </ol>
4704 ** If a collating function fails any of the above constraints and that
4705 ** collating function is registered and used, then the behavior of SQLite
4706 ** is undefined.
4708 ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
4709 ** with the addition that the xDestroy callback is invoked on pArg when
4710 ** the collating function is deleted.
4711 ** ^Collating functions are deleted when they are overridden by later
4712 ** calls to the collation creation functions or when the
4713 ** [database connection] is closed using [sqlite3_close()].
4715 ** ^The xDestroy callback is <u>not</u> called if the
4716 ** sqlite3_create_collation_v2() function fails. Applications that invoke
4717 ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
4718 ** check the return code and dispose of the application data pointer
4719 ** themselves rather than expecting SQLite to deal with it for them.
4720 ** This is different from every other SQLite interface. The inconsistency
4721 ** is unfortunate but cannot be changed without breaking backwards
4722 ** compatibility.
4724 ** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
4726 SQLITE_API int sqlite3_create_collation(
4727 sqlite3*,
4728 const char *zName,
4729 int eTextRep,
4730 void *pArg,
4731 int(*xCompare)(void*,int,const void*,int,const void*)
4733 SQLITE_API int sqlite3_create_collation_v2(
4734 sqlite3*,
4735 const char *zName,
4736 int eTextRep,
4737 void *pArg,
4738 int(*xCompare)(void*,int,const void*,int,const void*),
4739 void(*xDestroy)(void*)
4741 SQLITE_API int sqlite3_create_collation16(
4742 sqlite3*,
4743 const void *zName,
4744 int eTextRep,
4745 void *pArg,
4746 int(*xCompare)(void*,int,const void*,int,const void*)
4750 ** CAPI3REF: Collation Needed Callbacks
4752 ** ^To avoid having to register all collation sequences before a database
4753 ** can be used, a single callback function may be registered with the
4754 ** [database connection] to be invoked whenever an undefined collation
4755 ** sequence is required.
4757 ** ^If the function is registered using the sqlite3_collation_needed() API,
4758 ** then it is passed the names of undefined collation sequences as strings
4759 ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
4760 ** the names are passed as UTF-16 in machine native byte order.
4761 ** ^A call to either function replaces the existing collation-needed callback.
4763 ** ^(When the callback is invoked, the first argument passed is a copy
4764 ** of the second argument to sqlite3_collation_needed() or
4765 ** sqlite3_collation_needed16(). The second argument is the database
4766 ** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
4767 ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
4768 ** sequence function required. The fourth parameter is the name of the
4769 ** required collation sequence.)^
4771 ** The callback function should register the desired collation using
4772 ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
4773 ** [sqlite3_create_collation_v2()].
4775 SQLITE_API int sqlite3_collation_needed(
4776 sqlite3*,
4777 void*,
4778 void(*)(void*,sqlite3*,int eTextRep,const char*)
4780 SQLITE_API int sqlite3_collation_needed16(
4781 sqlite3*,
4782 void*,
4783 void(*)(void*,sqlite3*,int eTextRep,const void*)
4786 #ifdef SQLITE_HAS_CODEC
4788 ** Specify the key for an encrypted database. This routine should be
4789 ** called right after sqlite3_open().
4791 ** The code to implement this API is not available in the public release
4792 ** of SQLite.
4794 SQLITE_API int sqlite3_key(
4795 sqlite3 *db, /* Database to be rekeyed */
4796 const void *pKey, int nKey /* The key */
4800 ** Change the key on an open database. If the current database is not
4801 ** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the
4802 ** database is decrypted.
4804 ** The code to implement this API is not available in the public release
4805 ** of SQLite.
4807 SQLITE_API int sqlite3_rekey(
4808 sqlite3 *db, /* Database to be rekeyed */
4809 const void *pKey, int nKey /* The new key */
4813 ** Specify the activation key for a SEE database. Unless
4814 ** activated, none of the SEE routines will work.
4816 SQLITE_API void sqlite3_activate_see(
4817 const char *zPassPhrase /* Activation phrase */
4819 #endif
4821 #ifdef SQLITE_ENABLE_CEROD
4823 ** Specify the activation key for a CEROD database. Unless
4824 ** activated, none of the CEROD routines will work.
4826 SQLITE_API void sqlite3_activate_cerod(
4827 const char *zPassPhrase /* Activation phrase */
4829 #endif
4832 ** CAPI3REF: Suspend Execution For A Short Time
4834 ** The sqlite3_sleep() function causes the current thread to suspend execution
4835 ** for at least a number of milliseconds specified in its parameter.
4837 ** If the operating system does not support sleep requests with
4838 ** millisecond time resolution, then the time will be rounded up to
4839 ** the nearest second. The number of milliseconds of sleep actually
4840 ** requested from the operating system is returned.
4842 ** ^SQLite implements this interface by calling the xSleep()
4843 ** method of the default [sqlite3_vfs] object. If the xSleep() method
4844 ** of the default VFS is not implemented correctly, or not implemented at
4845 ** all, then the behavior of sqlite3_sleep() may deviate from the description
4846 ** in the previous paragraphs.
4848 SQLITE_API int sqlite3_sleep(int);
4851 ** CAPI3REF: Name Of The Folder Holding Temporary Files
4853 ** ^(If this global variable is made to point to a string which is
4854 ** the name of a folder (a.k.a. directory), then all temporary files
4855 ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
4856 ** will be placed in that directory.)^ ^If this variable
4857 ** is a NULL pointer, then SQLite performs a search for an appropriate
4858 ** temporary file directory.
4860 ** It is not safe to read or modify this variable in more than one
4861 ** thread at a time. It is not safe to read or modify this variable
4862 ** if a [database connection] is being used at the same time in a separate
4863 ** thread.
4864 ** It is intended that this variable be set once
4865 ** as part of process initialization and before any SQLite interface
4866 ** routines have been called and that this variable remain unchanged
4867 ** thereafter.
4869 ** ^The [temp_store_directory pragma] may modify this variable and cause
4870 ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
4871 ** the [temp_store_directory pragma] always assumes that any string
4872 ** that this variable points to is held in memory obtained from
4873 ** [sqlite3_malloc] and the pragma may attempt to free that memory
4874 ** using [sqlite3_free].
4875 ** Hence, if this variable is modified directly, either it should be
4876 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
4877 ** or else the use of the [temp_store_directory pragma] should be avoided.
4879 SQLITE_API char *sqlite3_temp_directory;
4882 ** CAPI3REF: Test For Auto-Commit Mode
4883 ** KEYWORDS: {autocommit mode}
4885 ** ^The sqlite3_get_autocommit() interface returns non-zero or
4886 ** zero if the given database connection is or is not in autocommit mode,
4887 ** respectively. ^Autocommit mode is on by default.
4888 ** ^Autocommit mode is disabled by a [BEGIN] statement.
4889 ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
4891 ** If certain kinds of errors occur on a statement within a multi-statement
4892 ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
4893 ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
4894 ** transaction might be rolled back automatically. The only way to
4895 ** find out whether SQLite automatically rolled back the transaction after
4896 ** an error is to use this function.
4898 ** If another thread changes the autocommit status of the database
4899 ** connection while this routine is running, then the return value
4900 ** is undefined.
4902 SQLITE_API int sqlite3_get_autocommit(sqlite3*);
4905 ** CAPI3REF: Find The Database Handle Of A Prepared Statement
4907 ** ^The sqlite3_db_handle interface returns the [database connection] handle
4908 ** to which a [prepared statement] belongs. ^The [database connection]
4909 ** returned by sqlite3_db_handle is the same [database connection]
4910 ** that was the first argument
4911 ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
4912 ** create the statement in the first place.
4914 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
4917 ** CAPI3REF: Find the next prepared statement
4919 ** ^This interface returns a pointer to the next [prepared statement] after
4920 ** pStmt associated with the [database connection] pDb. ^If pStmt is NULL
4921 ** then this interface returns a pointer to the first prepared statement
4922 ** associated with the database connection pDb. ^If no prepared statement
4923 ** satisfies the conditions of this routine, it returns NULL.
4925 ** The [database connection] pointer D in a call to
4926 ** [sqlite3_next_stmt(D,S)] must refer to an open database
4927 ** connection and in particular must not be a NULL pointer.
4929 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
4932 ** CAPI3REF: Commit And Rollback Notification Callbacks
4934 ** ^The sqlite3_commit_hook() interface registers a callback
4935 ** function to be invoked whenever a transaction is [COMMIT | committed].
4936 ** ^Any callback set by a previous call to sqlite3_commit_hook()
4937 ** for the same database connection is overridden.
4938 ** ^The sqlite3_rollback_hook() interface registers a callback
4939 ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
4940 ** ^Any callback set by a previous call to sqlite3_rollback_hook()
4941 ** for the same database connection is overridden.
4942 ** ^The pArg argument is passed through to the callback.
4943 ** ^If the callback on a commit hook function returns non-zero,
4944 ** then the commit is converted into a rollback.
4946 ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
4947 ** return the P argument from the previous call of the same function
4948 ** on the same [database connection] D, or NULL for
4949 ** the first call for each function on D.
4951 ** The callback implementation must not do anything that will modify
4952 ** the database connection that invoked the callback. Any actions
4953 ** to modify the database connection must be deferred until after the
4954 ** completion of the [sqlite3_step()] call that triggered the commit
4955 ** or rollback hook in the first place.
4956 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
4957 ** database connections for the meaning of "modify" in this paragraph.
4959 ** ^Registering a NULL function disables the callback.
4961 ** ^When the commit hook callback routine returns zero, the [COMMIT]
4962 ** operation is allowed to continue normally. ^If the commit hook
4963 ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
4964 ** ^The rollback hook is invoked on a rollback that results from a commit
4965 ** hook returning non-zero, just as it would be with any other rollback.
4967 ** ^For the purposes of this API, a transaction is said to have been
4968 ** rolled back if an explicit "ROLLBACK" statement is executed, or
4969 ** an error or constraint causes an implicit rollback to occur.
4970 ** ^The rollback callback is not invoked if a transaction is
4971 ** automatically rolled back because the database connection is closed.
4973 ** See also the [sqlite3_update_hook()] interface.
4975 SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
4976 SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
4979 ** CAPI3REF: Data Change Notification Callbacks
4981 ** ^The sqlite3_update_hook() interface registers a callback function
4982 ** with the [database connection] identified by the first argument
4983 ** to be invoked whenever a row is updated, inserted or deleted.
4984 ** ^Any callback set by a previous call to this function
4985 ** for the same database connection is overridden.
4987 ** ^The second argument is a pointer to the function to invoke when a
4988 ** row is updated, inserted or deleted.
4989 ** ^The first argument to the callback is a copy of the third argument
4990 ** to sqlite3_update_hook().
4991 ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
4992 ** or [SQLITE_UPDATE], depending on the operation that caused the callback
4993 ** to be invoked.
4994 ** ^The third and fourth arguments to the callback contain pointers to the
4995 ** database and table name containing the affected row.
4996 ** ^The final callback parameter is the [rowid] of the row.
4997 ** ^In the case of an update, this is the [rowid] after the update takes place.
4999 ** ^(The update hook is not invoked when internal system tables are
5000 ** modified (i.e. sqlite_master and sqlite_sequence).)^
5002 ** ^In the current implementation, the update hook
5003 ** is not invoked when duplication rows are deleted because of an
5004 ** [ON CONFLICT | ON CONFLICT REPLACE] clause. ^Nor is the update hook
5005 ** invoked when rows are deleted using the [truncate optimization].
5006 ** The exceptions defined in this paragraph might change in a future
5007 ** release of SQLite.
5009 ** The update hook implementation must not do anything that will modify
5010 ** the database connection that invoked the update hook. Any actions
5011 ** to modify the database connection must be deferred until after the
5012 ** completion of the [sqlite3_step()] call that triggered the update hook.
5013 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
5014 ** database connections for the meaning of "modify" in this paragraph.
5016 ** ^The sqlite3_update_hook(D,C,P) function
5017 ** returns the P argument from the previous call
5018 ** on the same [database connection] D, or NULL for
5019 ** the first call on D.
5021 ** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
5022 ** interfaces.
5024 SQLITE_API void *sqlite3_update_hook(
5025 sqlite3*,
5026 void(*)(void *,int ,char const *,char const *,sqlite3_int64),
5027 void*
5031 ** CAPI3REF: Enable Or Disable Shared Pager Cache
5032 ** KEYWORDS: {shared cache}
5034 ** ^(This routine enables or disables the sharing of the database cache
5035 ** and schema data structures between [database connection | connections]
5036 ** to the same database. Sharing is enabled if the argument is true
5037 ** and disabled if the argument is false.)^
5039 ** ^Cache sharing is enabled and disabled for an entire process.
5040 ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
5041 ** sharing was enabled or disabled for each thread separately.
5043 ** ^(The cache sharing mode set by this interface effects all subsequent
5044 ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
5045 ** Existing database connections continue use the sharing mode
5046 ** that was in effect at the time they were opened.)^
5048 ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
5049 ** successfully. An [error code] is returned otherwise.)^
5051 ** ^Shared cache is disabled by default. But this might change in
5052 ** future releases of SQLite. Applications that care about shared
5053 ** cache setting should set it explicitly.
5055 ** See Also: [SQLite Shared-Cache Mode]
5057 SQLITE_API int sqlite3_enable_shared_cache(int);
5060 ** CAPI3REF: Attempt To Free Heap Memory
5062 ** ^The sqlite3_release_memory() interface attempts to free N bytes
5063 ** of heap memory by deallocating non-essential memory allocations
5064 ** held by the database library. Memory used to cache database
5065 ** pages to improve performance is an example of non-essential memory.
5066 ** ^sqlite3_release_memory() returns the number of bytes actually freed,
5067 ** which might be more or less than the amount requested.
5068 ** ^The sqlite3_release_memory() routine is a no-op returning zero
5069 ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
5071 SQLITE_API int sqlite3_release_memory(int);
5074 ** CAPI3REF: Impose A Limit On Heap Size
5076 ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
5077 ** soft limit on the amount of heap memory that may be allocated by SQLite.
5078 ** ^SQLite strives to keep heap memory utilization below the soft heap
5079 ** limit by reducing the number of pages held in the page cache
5080 ** as heap memory usages approaches the limit.
5081 ** ^The soft heap limit is "soft" because even though SQLite strives to stay
5082 ** below the limit, it will exceed the limit rather than generate
5083 ** an [SQLITE_NOMEM] error. In other words, the soft heap limit
5084 ** is advisory only.
5086 ** ^The return value from sqlite3_soft_heap_limit64() is the size of
5087 ** the soft heap limit prior to the call. ^If the argument N is negative
5088 ** then no change is made to the soft heap limit. Hence, the current
5089 ** size of the soft heap limit can be determined by invoking
5090 ** sqlite3_soft_heap_limit64() with a negative argument.
5092 ** ^If the argument N is zero then the soft heap limit is disabled.
5094 ** ^(The soft heap limit is not enforced in the current implementation
5095 ** if one or more of following conditions are true:
5097 ** <ul>
5098 ** <li> The soft heap limit is set to zero.
5099 ** <li> Memory accounting is disabled using a combination of the
5100 ** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
5101 ** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
5102 ** <li> An alternative page cache implementation is specified using
5103 ** [sqlite3_config]([SQLITE_CONFIG_PCACHE],...).
5104 ** <li> The page cache allocates from its own memory pool supplied
5105 ** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
5106 ** from the heap.
5107 ** </ul>)^
5109 ** Beginning with SQLite version 3.7.3, the soft heap limit is enforced
5110 ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
5111 ** compile-time option is invoked. With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
5112 ** the soft heap limit is enforced on every memory allocation. Without
5113 ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
5114 ** when memory is allocated by the page cache. Testing suggests that because
5115 ** the page cache is the predominate memory user in SQLite, most
5116 ** applications will achieve adequate soft heap limit enforcement without
5117 ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
5119 ** The circumstances under which SQLite will enforce the soft heap limit may
5120 ** changes in future releases of SQLite.
5122 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
5125 ** CAPI3REF: Deprecated Soft Heap Limit Interface
5126 ** DEPRECATED
5128 ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
5129 ** interface. This routine is provided for historical compatibility
5130 ** only. All new applications should use the
5131 ** [sqlite3_soft_heap_limit64()] interface rather than this one.
5133 SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
5137 ** CAPI3REF: Extract Metadata About A Column Of A Table
5139 ** ^This routine returns metadata about a specific column of a specific
5140 ** database table accessible using the [database connection] handle
5141 ** passed as the first function argument.
5143 ** ^The column is identified by the second, third and fourth parameters to
5144 ** this function. ^The second parameter is either the name of the database
5145 ** (i.e. "main", "temp", or an attached database) containing the specified
5146 ** table or NULL. ^If it is NULL, then all attached databases are searched
5147 ** for the table using the same algorithm used by the database engine to
5148 ** resolve unqualified table references.
5150 ** ^The third and fourth parameters to this function are the table and column
5151 ** name of the desired column, respectively. Neither of these parameters
5152 ** may be NULL.
5154 ** ^Metadata is returned by writing to the memory locations passed as the 5th
5155 ** and subsequent parameters to this function. ^Any of these arguments may be
5156 ** NULL, in which case the corresponding element of metadata is omitted.
5158 ** ^(<blockquote>
5159 ** <table border="1">
5160 ** <tr><th> Parameter <th> Output<br>Type <th> Description
5162 ** <tr><td> 5th <td> const char* <td> Data type
5163 ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
5164 ** <tr><td> 7th <td> int <td> True if column has a NOT NULL constraint
5165 ** <tr><td> 8th <td> int <td> True if column is part of the PRIMARY KEY
5166 ** <tr><td> 9th <td> int <td> True if column is [AUTOINCREMENT]
5167 ** </table>
5168 ** </blockquote>)^
5170 ** ^The memory pointed to by the character pointers returned for the
5171 ** declaration type and collation sequence is valid only until the next
5172 ** call to any SQLite API function.
5174 ** ^If the specified table is actually a view, an [error code] is returned.
5176 ** ^If the specified column is "rowid", "oid" or "_rowid_" and an
5177 ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
5178 ** parameters are set for the explicitly declared column. ^(If there is no
5179 ** explicitly declared [INTEGER PRIMARY KEY] column, then the output
5180 ** parameters are set as follows:
5182 ** <pre>
5183 ** data type: "INTEGER"
5184 ** collation sequence: "BINARY"
5185 ** not null: 0
5186 ** primary key: 1
5187 ** auto increment: 0
5188 ** </pre>)^
5190 ** ^(This function may load one or more schemas from database files. If an
5191 ** error occurs during this process, or if the requested table or column
5192 ** cannot be found, an [error code] is returned and an error message left
5193 ** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^
5195 ** ^This API is only available if the library was compiled with the
5196 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
5198 SQLITE_API int sqlite3_table_column_metadata(
5199 sqlite3 *db, /* Connection handle */
5200 const char *zDbName, /* Database name or NULL */
5201 const char *zTableName, /* Table name */
5202 const char *zColumnName, /* Column name */
5203 char const **pzDataType, /* OUTPUT: Declared data type */
5204 char const **pzCollSeq, /* OUTPUT: Collation sequence name */
5205 int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
5206 int *pPrimaryKey, /* OUTPUT: True if column part of PK */
5207 int *pAutoinc /* OUTPUT: True if column is auto-increment */
5211 ** CAPI3REF: Load An Extension
5213 ** ^This interface loads an SQLite extension library from the named file.
5215 ** ^The sqlite3_load_extension() interface attempts to load an
5216 ** SQLite extension library contained in the file zFile.
5218 ** ^The entry point is zProc.
5219 ** ^zProc may be 0, in which case the name of the entry point
5220 ** defaults to "sqlite3_extension_init".
5221 ** ^The sqlite3_load_extension() interface returns
5222 ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
5223 ** ^If an error occurs and pzErrMsg is not 0, then the
5224 ** [sqlite3_load_extension()] interface shall attempt to
5225 ** fill *pzErrMsg with error message text stored in memory
5226 ** obtained from [sqlite3_malloc()]. The calling function
5227 ** should free this memory by calling [sqlite3_free()].
5229 ** ^Extension loading must be enabled using
5230 ** [sqlite3_enable_load_extension()] prior to calling this API,
5231 ** otherwise an error will be returned.
5233 ** See also the [load_extension() SQL function].
5235 SQLITE_API int sqlite3_load_extension(
5236 sqlite3 *db, /* Load the extension into this database connection */
5237 const char *zFile, /* Name of the shared library containing extension */
5238 const char *zProc, /* Entry point. Derived from zFile if 0 */
5239 char **pzErrMsg /* Put error message here if not 0 */
5243 ** CAPI3REF: Enable Or Disable Extension Loading
5245 ** ^So as not to open security holes in older applications that are
5246 ** unprepared to deal with extension loading, and as a means of disabling
5247 ** extension loading while evaluating user-entered SQL, the following API
5248 ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
5250 ** ^Extension loading is off by default. See ticket #1863.
5251 ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
5252 ** to turn extension loading on and call it with onoff==0 to turn
5253 ** it back off again.
5255 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
5258 ** CAPI3REF: Automatically Load Statically Linked Extensions
5260 ** ^This interface causes the xEntryPoint() function to be invoked for
5261 ** each new [database connection] that is created. The idea here is that
5262 ** xEntryPoint() is the entry point for a statically linked SQLite extension
5263 ** that is to be automatically loaded into all new database connections.
5265 ** ^(Even though the function prototype shows that xEntryPoint() takes
5266 ** no arguments and returns void, SQLite invokes xEntryPoint() with three
5267 ** arguments and expects and integer result as if the signature of the
5268 ** entry point where as follows:
5270 ** <blockquote><pre>
5271 ** &nbsp; int xEntryPoint(
5272 ** &nbsp; sqlite3 *db,
5273 ** &nbsp; const char **pzErrMsg,
5274 ** &nbsp; const struct sqlite3_api_routines *pThunk
5275 ** &nbsp; );
5276 ** </pre></blockquote>)^
5278 ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
5279 ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
5280 ** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg
5281 ** is NULL before calling the xEntryPoint(). ^SQLite will invoke
5282 ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any
5283 ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
5284 ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
5286 ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
5287 ** on the list of automatic extensions is a harmless no-op. ^No entry point
5288 ** will be called more than once for each database connection that is opened.
5290 ** See also: [sqlite3_reset_auto_extension()].
5292 SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
5295 ** CAPI3REF: Reset Automatic Extension Loading
5297 ** ^This interface disables all automatic extensions previously
5298 ** registered using [sqlite3_auto_extension()].
5300 SQLITE_API void sqlite3_reset_auto_extension(void);
5303 ** The interface to the virtual-table mechanism is currently considered
5304 ** to be experimental. The interface might change in incompatible ways.
5305 ** If this is a problem for you, do not use the interface at this time.
5307 ** When the virtual-table mechanism stabilizes, we will declare the
5308 ** interface fixed, support it indefinitely, and remove this comment.
5312 ** Structures used by the virtual table interface
5314 typedef struct sqlite3_vtab sqlite3_vtab;
5315 typedef struct sqlite3_index_info sqlite3_index_info;
5316 typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
5317 typedef struct sqlite3_module sqlite3_module;
5320 ** CAPI3REF: Virtual Table Object
5321 ** KEYWORDS: sqlite3_module {virtual table module}
5323 ** This structure, sometimes called a "virtual table module",
5324 ** defines the implementation of a [virtual tables].
5325 ** This structure consists mostly of methods for the module.
5327 ** ^A virtual table module is created by filling in a persistent
5328 ** instance of this structure and passing a pointer to that instance
5329 ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
5330 ** ^The registration remains valid until it is replaced by a different
5331 ** module or until the [database connection] closes. The content
5332 ** of this structure must not change while it is registered with
5333 ** any database connection.
5335 struct sqlite3_module {
5336 int iVersion;
5337 int (*xCreate)(sqlite3*, void *pAux,
5338 int argc, const char *const*argv,
5339 sqlite3_vtab **ppVTab, char**);
5340 int (*xConnect)(sqlite3*, void *pAux,
5341 int argc, const char *const*argv,
5342 sqlite3_vtab **ppVTab, char**);
5343 int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
5344 int (*xDisconnect)(sqlite3_vtab *pVTab);
5345 int (*xDestroy)(sqlite3_vtab *pVTab);
5346 int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
5347 int (*xClose)(sqlite3_vtab_cursor*);
5348 int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
5349 int argc, sqlite3_value **argv);
5350 int (*xNext)(sqlite3_vtab_cursor*);
5351 int (*xEof)(sqlite3_vtab_cursor*);
5352 int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
5353 int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
5354 int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
5355 int (*xBegin)(sqlite3_vtab *pVTab);
5356 int (*xSync)(sqlite3_vtab *pVTab);
5357 int (*xCommit)(sqlite3_vtab *pVTab);
5358 int (*xRollback)(sqlite3_vtab *pVTab);
5359 int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
5360 void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
5361 void **ppArg);
5362 int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
5363 /* The methods above are in version 1 of the sqlite_module object. Those
5364 ** below are for version 2 and greater. */
5365 int (*xSavepoint)(sqlite3_vtab *pVTab, int);
5366 int (*xRelease)(sqlite3_vtab *pVTab, int);
5367 int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
5371 ** CAPI3REF: Virtual Table Indexing Information
5372 ** KEYWORDS: sqlite3_index_info
5374 ** The sqlite3_index_info structure and its substructures is used as part
5375 ** of the [virtual table] interface to
5376 ** pass information into and receive the reply from the [xBestIndex]
5377 ** method of a [virtual table module]. The fields under **Inputs** are the
5378 ** inputs to xBestIndex and are read-only. xBestIndex inserts its
5379 ** results into the **Outputs** fields.
5381 ** ^(The aConstraint[] array records WHERE clause constraints of the form:
5383 ** <blockquote>column OP expr</blockquote>
5385 ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^ ^(The particular operator is
5386 ** stored in aConstraint[].op using one of the
5387 ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
5388 ** ^(The index of the column is stored in
5389 ** aConstraint[].iColumn.)^ ^(aConstraint[].usable is TRUE if the
5390 ** expr on the right-hand side can be evaluated (and thus the constraint
5391 ** is usable) and false if it cannot.)^
5393 ** ^The optimizer automatically inverts terms of the form "expr OP column"
5394 ** and makes other simplifications to the WHERE clause in an attempt to
5395 ** get as many WHERE clause terms into the form shown above as possible.
5396 ** ^The aConstraint[] array only reports WHERE clause terms that are
5397 ** relevant to the particular virtual table being queried.
5399 ** ^Information about the ORDER BY clause is stored in aOrderBy[].
5400 ** ^Each term of aOrderBy records a column of the ORDER BY clause.
5402 ** The [xBestIndex] method must fill aConstraintUsage[] with information
5403 ** about what parameters to pass to xFilter. ^If argvIndex>0 then
5404 ** the right-hand side of the corresponding aConstraint[] is evaluated
5405 ** and becomes the argvIndex-th entry in argv. ^(If aConstraintUsage[].omit
5406 ** is true, then the constraint is assumed to be fully handled by the
5407 ** virtual table and is not checked again by SQLite.)^
5409 ** ^The idxNum and idxPtr values are recorded and passed into the
5410 ** [xFilter] method.
5411 ** ^[sqlite3_free()] is used to free idxPtr if and only if
5412 ** needToFreeIdxPtr is true.
5414 ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
5415 ** the correct order to satisfy the ORDER BY clause so that no separate
5416 ** sorting step is required.
5418 ** ^The estimatedCost value is an estimate of the cost of doing the
5419 ** particular lookup. A full scan of a table with N entries should have
5420 ** a cost of N. A binary search of a table of N entries should have a
5421 ** cost of approximately log(N).
5423 struct sqlite3_index_info {
5424 /* Inputs */
5425 int nConstraint; /* Number of entries in aConstraint */
5426 struct sqlite3_index_constraint {
5427 int iColumn; /* Column on left-hand side of constraint */
5428 unsigned char op; /* Constraint operator */
5429 unsigned char usable; /* True if this constraint is usable */
5430 int iTermOffset; /* Used internally - xBestIndex should ignore */
5431 } *aConstraint; /* Table of WHERE clause constraints */
5432 int nOrderBy; /* Number of terms in the ORDER BY clause */
5433 struct sqlite3_index_orderby {
5434 int iColumn; /* Column number */
5435 unsigned char desc; /* True for DESC. False for ASC. */
5436 } *aOrderBy; /* The ORDER BY clause */
5437 /* Outputs */
5438 struct sqlite3_index_constraint_usage {
5439 int argvIndex; /* if >0, constraint is part of argv to xFilter */
5440 unsigned char omit; /* Do not code a test for this constraint */
5441 } *aConstraintUsage;
5442 int idxNum; /* Number used to identify the index */
5443 char *idxStr; /* String, possibly obtained from sqlite3_malloc */
5444 int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */
5445 int orderByConsumed; /* True if output is already ordered */
5446 double estimatedCost; /* Estimated cost of using this index */
5450 ** CAPI3REF: Virtual Table Constraint Operator Codes
5452 ** These macros defined the allowed values for the
5453 ** [sqlite3_index_info].aConstraint[].op field. Each value represents
5454 ** an operator that is part of a constraint term in the wHERE clause of
5455 ** a query that uses a [virtual table].
5457 #define SQLITE_INDEX_CONSTRAINT_EQ 2
5458 #define SQLITE_INDEX_CONSTRAINT_GT 4
5459 #define SQLITE_INDEX_CONSTRAINT_LE 8
5460 #define SQLITE_INDEX_CONSTRAINT_LT 16
5461 #define SQLITE_INDEX_CONSTRAINT_GE 32
5462 #define SQLITE_INDEX_CONSTRAINT_MATCH 64
5465 ** CAPI3REF: Register A Virtual Table Implementation
5467 ** ^These routines are used to register a new [virtual table module] name.
5468 ** ^Module names must be registered before
5469 ** creating a new [virtual table] using the module and before using a
5470 ** preexisting [virtual table] for the module.
5472 ** ^The module name is registered on the [database connection] specified
5473 ** by the first parameter. ^The name of the module is given by the
5474 ** second parameter. ^The third parameter is a pointer to
5475 ** the implementation of the [virtual table module]. ^The fourth
5476 ** parameter is an arbitrary client data pointer that is passed through
5477 ** into the [xCreate] and [xConnect] methods of the virtual table module
5478 ** when a new virtual table is be being created or reinitialized.
5480 ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
5481 ** is a pointer to a destructor for the pClientData. ^SQLite will
5482 ** invoke the destructor function (if it is not NULL) when SQLite
5483 ** no longer needs the pClientData pointer. ^The destructor will also
5484 ** be invoked if the call to sqlite3_create_module_v2() fails.
5485 ** ^The sqlite3_create_module()
5486 ** interface is equivalent to sqlite3_create_module_v2() with a NULL
5487 ** destructor.
5489 SQLITE_API int sqlite3_create_module(
5490 sqlite3 *db, /* SQLite connection to register module with */
5491 const char *zName, /* Name of the module */
5492 const sqlite3_module *p, /* Methods for the module */
5493 void *pClientData /* Client data for xCreate/xConnect */
5495 SQLITE_API int sqlite3_create_module_v2(
5496 sqlite3 *db, /* SQLite connection to register module with */
5497 const char *zName, /* Name of the module */
5498 const sqlite3_module *p, /* Methods for the module */
5499 void *pClientData, /* Client data for xCreate/xConnect */
5500 void(*xDestroy)(void*) /* Module destructor function */
5504 ** CAPI3REF: Virtual Table Instance Object
5505 ** KEYWORDS: sqlite3_vtab
5507 ** Every [virtual table module] implementation uses a subclass
5508 ** of this object to describe a particular instance
5509 ** of the [virtual table]. Each subclass will
5510 ** be tailored to the specific needs of the module implementation.
5511 ** The purpose of this superclass is to define certain fields that are
5512 ** common to all module implementations.
5514 ** ^Virtual tables methods can set an error message by assigning a
5515 ** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should
5516 ** take care that any prior string is freed by a call to [sqlite3_free()]
5517 ** prior to assigning a new string to zErrMsg. ^After the error message
5518 ** is delivered up to the client application, the string will be automatically
5519 ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
5521 struct sqlite3_vtab {
5522 const sqlite3_module *pModule; /* The module for this virtual table */
5523 int nRef; /* NO LONGER USED */
5524 char *zErrMsg; /* Error message from sqlite3_mprintf() */
5525 /* Virtual table implementations will typically add additional fields */
5529 ** CAPI3REF: Virtual Table Cursor Object
5530 ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
5532 ** Every [virtual table module] implementation uses a subclass of the
5533 ** following structure to describe cursors that point into the
5534 ** [virtual table] and are used
5535 ** to loop through the virtual table. Cursors are created using the
5536 ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
5537 ** by the [sqlite3_module.xClose | xClose] method. Cursors are used
5538 ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
5539 ** of the module. Each module implementation will define
5540 ** the content of a cursor structure to suit its own needs.
5542 ** This superclass exists in order to define fields of the cursor that
5543 ** are common to all implementations.
5545 struct sqlite3_vtab_cursor {
5546 sqlite3_vtab *pVtab; /* Virtual table of this cursor */
5547 /* Virtual table implementations will typically add additional fields */
5551 ** CAPI3REF: Declare The Schema Of A Virtual Table
5553 ** ^The [xCreate] and [xConnect] methods of a
5554 ** [virtual table module] call this interface
5555 ** to declare the format (the names and datatypes of the columns) of
5556 ** the virtual tables they implement.
5558 SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
5561 ** CAPI3REF: Overload A Function For A Virtual Table
5563 ** ^(Virtual tables can provide alternative implementations of functions
5564 ** using the [xFindFunction] method of the [virtual table module].
5565 ** But global versions of those functions
5566 ** must exist in order to be overloaded.)^
5568 ** ^(This API makes sure a global version of a function with a particular
5569 ** name and number of parameters exists. If no such function exists
5570 ** before this API is called, a new function is created.)^ ^The implementation
5571 ** of the new function always causes an exception to be thrown. So
5572 ** the new function is not good for anything by itself. Its only
5573 ** purpose is to be a placeholder function that can be overloaded
5574 ** by a [virtual table].
5576 SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
5579 ** The interface to the virtual-table mechanism defined above (back up
5580 ** to a comment remarkably similar to this one) is currently considered
5581 ** to be experimental. The interface might change in incompatible ways.
5582 ** If this is a problem for you, do not use the interface at this time.
5584 ** When the virtual-table mechanism stabilizes, we will declare the
5585 ** interface fixed, support it indefinitely, and remove this comment.
5589 ** CAPI3REF: A Handle To An Open BLOB
5590 ** KEYWORDS: {BLOB handle} {BLOB handles}
5592 ** An instance of this object represents an open BLOB on which
5593 ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
5594 ** ^Objects of this type are created by [sqlite3_blob_open()]
5595 ** and destroyed by [sqlite3_blob_close()].
5596 ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
5597 ** can be used to read or write small subsections of the BLOB.
5598 ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
5600 typedef struct sqlite3_blob sqlite3_blob;
5603 ** CAPI3REF: Open A BLOB For Incremental I/O
5605 ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
5606 ** in row iRow, column zColumn, table zTable in database zDb;
5607 ** in other words, the same BLOB that would be selected by:
5609 ** <pre>
5610 ** SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
5611 ** </pre>)^
5613 ** ^If the flags parameter is non-zero, then the BLOB is opened for read
5614 ** and write access. ^If it is zero, the BLOB is opened for read access.
5615 ** ^It is not possible to open a column that is part of an index or primary
5616 ** key for writing. ^If [foreign key constraints] are enabled, it is
5617 ** not possible to open a column that is part of a [child key] for writing.
5619 ** ^Note that the database name is not the filename that contains
5620 ** the database but rather the symbolic name of the database that
5621 ** appears after the AS keyword when the database is connected using [ATTACH].
5622 ** ^For the main database file, the database name is "main".
5623 ** ^For TEMP tables, the database name is "temp".
5625 ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written
5626 ** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set
5627 ** to be a null pointer.)^
5628 ** ^This function sets the [database connection] error code and message
5629 ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related
5630 ** functions. ^Note that the *ppBlob variable is always initialized in a
5631 ** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob
5632 ** regardless of the success or failure of this routine.
5634 ** ^(If the row that a BLOB handle points to is modified by an
5635 ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
5636 ** then the BLOB handle is marked as "expired".
5637 ** This is true if any column of the row is changed, even a column
5638 ** other than the one the BLOB handle is open on.)^
5639 ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
5640 ** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
5641 ** ^(Changes written into a BLOB prior to the BLOB expiring are not
5642 ** rolled back by the expiration of the BLOB. Such changes will eventually
5643 ** commit if the transaction continues to completion.)^
5645 ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
5646 ** the opened blob. ^The size of a blob may not be changed by this
5647 ** interface. Use the [UPDATE] SQL command to change the size of a
5648 ** blob.
5650 ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
5651 ** and the built-in [zeroblob] SQL function can be used, if desired,
5652 ** to create an empty, zero-filled blob in which to read or write using
5653 ** this interface.
5655 ** To avoid a resource leak, every open [BLOB handle] should eventually
5656 ** be released by a call to [sqlite3_blob_close()].
5658 SQLITE_API int sqlite3_blob_open(
5659 sqlite3*,
5660 const char *zDb,
5661 const char *zTable,
5662 const char *zColumn,
5663 sqlite3_int64 iRow,
5664 int flags,
5665 sqlite3_blob **ppBlob
5669 ** CAPI3REF: Move a BLOB Handle to a New Row
5671 ** ^This function is used to move an existing blob handle so that it points
5672 ** to a different row of the same database table. ^The new row is identified
5673 ** by the rowid value passed as the second argument. Only the row can be
5674 ** changed. ^The database, table and column on which the blob handle is open
5675 ** remain the same. Moving an existing blob handle to a new row can be
5676 ** faster than closing the existing handle and opening a new one.
5678 ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
5679 ** it must exist and there must be either a blob or text value stored in
5680 ** the nominated column.)^ ^If the new row is not present in the table, or if
5681 ** it does not contain a blob or text value, or if another error occurs, an
5682 ** SQLite error code is returned and the blob handle is considered aborted.
5683 ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
5684 ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
5685 ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
5686 ** always returns zero.
5688 ** ^This function sets the database handle error code and message.
5690 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
5693 ** CAPI3REF: Close A BLOB Handle
5695 ** ^Closes an open [BLOB handle].
5697 ** ^Closing a BLOB shall cause the current transaction to commit
5698 ** if there are no other BLOBs, no pending prepared statements, and the
5699 ** database connection is in [autocommit mode].
5700 ** ^If any writes were made to the BLOB, they might be held in cache
5701 ** until the close operation if they will fit.
5703 ** ^(Closing the BLOB often forces the changes
5704 ** out to disk and so if any I/O errors occur, they will likely occur
5705 ** at the time when the BLOB is closed. Any errors that occur during
5706 ** closing are reported as a non-zero return value.)^
5708 ** ^(The BLOB is closed unconditionally. Even if this routine returns
5709 ** an error code, the BLOB is still closed.)^
5711 ** ^Calling this routine with a null pointer (such as would be returned
5712 ** by a failed call to [sqlite3_blob_open()]) is a harmless no-op.
5714 SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
5717 ** CAPI3REF: Return The Size Of An Open BLOB
5719 ** ^Returns the size in bytes of the BLOB accessible via the
5720 ** successfully opened [BLOB handle] in its only argument. ^The
5721 ** incremental blob I/O routines can only read or overwriting existing
5722 ** blob content; they cannot change the size of a blob.
5724 ** This routine only works on a [BLOB handle] which has been created
5725 ** by a prior successful call to [sqlite3_blob_open()] and which has not
5726 ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
5727 ** to this routine results in undefined and probably undesirable behavior.
5729 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
5732 ** CAPI3REF: Read Data From A BLOB Incrementally
5734 ** ^(This function is used to read data from an open [BLOB handle] into a
5735 ** caller-supplied buffer. N bytes of data are copied into buffer Z
5736 ** from the open BLOB, starting at offset iOffset.)^
5738 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
5739 ** [SQLITE_ERROR] is returned and no data is read. ^If N or iOffset is
5740 ** less than zero, [SQLITE_ERROR] is returned and no data is read.
5741 ** ^The size of the blob (and hence the maximum value of N+iOffset)
5742 ** can be determined using the [sqlite3_blob_bytes()] interface.
5744 ** ^An attempt to read from an expired [BLOB handle] fails with an
5745 ** error code of [SQLITE_ABORT].
5747 ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
5748 ** Otherwise, an [error code] or an [extended error code] is returned.)^
5750 ** This routine only works on a [BLOB handle] which has been created
5751 ** by a prior successful call to [sqlite3_blob_open()] and which has not
5752 ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
5753 ** to this routine results in undefined and probably undesirable behavior.
5755 ** See also: [sqlite3_blob_write()].
5757 SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
5760 ** CAPI3REF: Write Data Into A BLOB Incrementally
5762 ** ^This function is used to write data into an open [BLOB handle] from a
5763 ** caller-supplied buffer. ^N bytes of data are copied from the buffer Z
5764 ** into the open BLOB, starting at offset iOffset.
5766 ** ^If the [BLOB handle] passed as the first argument was not opened for
5767 ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
5768 ** this function returns [SQLITE_READONLY].
5770 ** ^This function may only modify the contents of the BLOB; it is
5771 ** not possible to increase the size of a BLOB using this API.
5772 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
5773 ** [SQLITE_ERROR] is returned and no data is written. ^If N is
5774 ** less than zero [SQLITE_ERROR] is returned and no data is written.
5775 ** The size of the BLOB (and hence the maximum value of N+iOffset)
5776 ** can be determined using the [sqlite3_blob_bytes()] interface.
5778 ** ^An attempt to write to an expired [BLOB handle] fails with an
5779 ** error code of [SQLITE_ABORT]. ^Writes to the BLOB that occurred
5780 ** before the [BLOB handle] expired are not rolled back by the
5781 ** expiration of the handle, though of course those changes might
5782 ** have been overwritten by the statement that expired the BLOB handle
5783 ** or by other independent statements.
5785 ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
5786 ** Otherwise, an [error code] or an [extended error code] is returned.)^
5788 ** This routine only works on a [BLOB handle] which has been created
5789 ** by a prior successful call to [sqlite3_blob_open()] and which has not
5790 ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
5791 ** to this routine results in undefined and probably undesirable behavior.
5793 ** See also: [sqlite3_blob_read()].
5795 SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
5798 ** CAPI3REF: Virtual File System Objects
5800 ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
5801 ** that SQLite uses to interact
5802 ** with the underlying operating system. Most SQLite builds come with a
5803 ** single default VFS that is appropriate for the host computer.
5804 ** New VFSes can be registered and existing VFSes can be unregistered.
5805 ** The following interfaces are provided.
5807 ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
5808 ** ^Names are case sensitive.
5809 ** ^Names are zero-terminated UTF-8 strings.
5810 ** ^If there is no match, a NULL pointer is returned.
5811 ** ^If zVfsName is NULL then the default VFS is returned.
5813 ** ^New VFSes are registered with sqlite3_vfs_register().
5814 ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
5815 ** ^The same VFS can be registered multiple times without injury.
5816 ** ^To make an existing VFS into the default VFS, register it again
5817 ** with the makeDflt flag set. If two different VFSes with the
5818 ** same name are registered, the behavior is undefined. If a
5819 ** VFS is registered with a name that is NULL or an empty string,
5820 ** then the behavior is undefined.
5822 ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
5823 ** ^(If the default VFS is unregistered, another VFS is chosen as
5824 ** the default. The choice for the new VFS is arbitrary.)^
5826 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
5827 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
5828 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
5831 ** CAPI3REF: Mutexes
5833 ** The SQLite core uses these routines for thread
5834 ** synchronization. Though they are intended for internal
5835 ** use by SQLite, code that links against SQLite is
5836 ** permitted to use any of these routines.
5838 ** The SQLite source code contains multiple implementations
5839 ** of these mutex routines. An appropriate implementation
5840 ** is selected automatically at compile-time. ^(The following
5841 ** implementations are available in the SQLite core:
5843 ** <ul>
5844 ** <li> SQLITE_MUTEX_OS2
5845 ** <li> SQLITE_MUTEX_PTHREAD
5846 ** <li> SQLITE_MUTEX_W32
5847 ** <li> SQLITE_MUTEX_NOOP
5848 ** </ul>)^
5850 ** ^The SQLITE_MUTEX_NOOP implementation is a set of routines
5851 ** that does no real locking and is appropriate for use in
5852 ** a single-threaded application. ^The SQLITE_MUTEX_OS2,
5853 ** SQLITE_MUTEX_PTHREAD, and SQLITE_MUTEX_W32 implementations
5854 ** are appropriate for use on OS/2, Unix, and Windows.
5856 ** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
5857 ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
5858 ** implementation is included with the library. In this case the
5859 ** application must supply a custom mutex implementation using the
5860 ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
5861 ** before calling sqlite3_initialize() or any other public sqlite3_
5862 ** function that calls sqlite3_initialize().)^
5864 ** ^The sqlite3_mutex_alloc() routine allocates a new
5865 ** mutex and returns a pointer to it. ^If it returns NULL
5866 ** that means that a mutex could not be allocated. ^SQLite
5867 ** will unwind its stack and return an error. ^(The argument
5868 ** to sqlite3_mutex_alloc() is one of these integer constants:
5870 ** <ul>
5871 ** <li> SQLITE_MUTEX_FAST
5872 ** <li> SQLITE_MUTEX_RECURSIVE
5873 ** <li> SQLITE_MUTEX_STATIC_MASTER
5874 ** <li> SQLITE_MUTEX_STATIC_MEM
5875 ** <li> SQLITE_MUTEX_STATIC_MEM2
5876 ** <li> SQLITE_MUTEX_STATIC_PRNG
5877 ** <li> SQLITE_MUTEX_STATIC_LRU
5878 ** <li> SQLITE_MUTEX_STATIC_LRU2
5879 ** </ul>)^
5881 ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
5882 ** cause sqlite3_mutex_alloc() to create
5883 ** a new mutex. ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
5884 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
5885 ** The mutex implementation does not need to make a distinction
5886 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
5887 ** not want to. ^SQLite will only request a recursive mutex in
5888 ** cases where it really needs one. ^If a faster non-recursive mutex
5889 ** implementation is available on the host platform, the mutex subsystem
5890 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
5892 ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
5893 ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
5894 ** a pointer to a static preexisting mutex. ^Six static mutexes are
5895 ** used by the current version of SQLite. Future versions of SQLite
5896 ** may add additional static mutexes. Static mutexes are for internal
5897 ** use by SQLite only. Applications that use SQLite mutexes should
5898 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
5899 ** SQLITE_MUTEX_RECURSIVE.
5901 ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
5902 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
5903 ** returns a different mutex on every call. ^But for the static
5904 ** mutex types, the same mutex is returned on every call that has
5905 ** the same type number.
5907 ** ^The sqlite3_mutex_free() routine deallocates a previously
5908 ** allocated dynamic mutex. ^SQLite is careful to deallocate every
5909 ** dynamic mutex that it allocates. The dynamic mutexes must not be in
5910 ** use when they are deallocated. Attempting to deallocate a static
5911 ** mutex results in undefined behavior. ^SQLite never deallocates
5912 ** a static mutex.
5914 ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
5915 ** to enter a mutex. ^If another thread is already within the mutex,
5916 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
5917 ** SQLITE_BUSY. ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
5918 ** upon successful entry. ^(Mutexes created using
5919 ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
5920 ** In such cases the,
5921 ** mutex must be exited an equal number of times before another thread
5922 ** can enter.)^ ^(If the same thread tries to enter any other
5923 ** kind of mutex more than once, the behavior is undefined.
5924 ** SQLite will never exhibit
5925 ** such behavior in its own use of mutexes.)^
5927 ** ^(Some systems (for example, Windows 95) do not support the operation
5928 ** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try()
5929 ** will always return SQLITE_BUSY. The SQLite core only ever uses
5930 ** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^
5932 ** ^The sqlite3_mutex_leave() routine exits a mutex that was
5933 ** previously entered by the same thread. ^(The behavior
5934 ** is undefined if the mutex is not currently entered by the
5935 ** calling thread or is not currently allocated. SQLite will
5936 ** never do either.)^
5938 ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
5939 ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
5940 ** behave as no-ops.
5942 ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
5944 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
5945 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
5946 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
5947 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
5948 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
5951 ** CAPI3REF: Mutex Methods Object
5953 ** An instance of this structure defines the low-level routines
5954 ** used to allocate and use mutexes.
5956 ** Usually, the default mutex implementations provided by SQLite are
5957 ** sufficient, however the user has the option of substituting a custom
5958 ** implementation for specialized deployments or systems for which SQLite
5959 ** does not provide a suitable implementation. In this case, the user
5960 ** creates and populates an instance of this structure to pass
5961 ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
5962 ** Additionally, an instance of this structure can be used as an
5963 ** output variable when querying the system for the current mutex
5964 ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
5966 ** ^The xMutexInit method defined by this structure is invoked as
5967 ** part of system initialization by the sqlite3_initialize() function.
5968 ** ^The xMutexInit routine is called by SQLite exactly once for each
5969 ** effective call to [sqlite3_initialize()].
5971 ** ^The xMutexEnd method defined by this structure is invoked as
5972 ** part of system shutdown by the sqlite3_shutdown() function. The
5973 ** implementation of this method is expected to release all outstanding
5974 ** resources obtained by the mutex methods implementation, especially
5975 ** those obtained by the xMutexInit method. ^The xMutexEnd()
5976 ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
5978 ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
5979 ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
5980 ** xMutexNotheld) implement the following interfaces (respectively):
5982 ** <ul>
5983 ** <li> [sqlite3_mutex_alloc()] </li>
5984 ** <li> [sqlite3_mutex_free()] </li>
5985 ** <li> [sqlite3_mutex_enter()] </li>
5986 ** <li> [sqlite3_mutex_try()] </li>
5987 ** <li> [sqlite3_mutex_leave()] </li>
5988 ** <li> [sqlite3_mutex_held()] </li>
5989 ** <li> [sqlite3_mutex_notheld()] </li>
5990 ** </ul>)^
5992 ** The only difference is that the public sqlite3_XXX functions enumerated
5993 ** above silently ignore any invocations that pass a NULL pointer instead
5994 ** of a valid mutex handle. The implementations of the methods defined
5995 ** by this structure are not required to handle this case, the results
5996 ** of passing a NULL pointer instead of a valid mutex handle are undefined
5997 ** (i.e. it is acceptable to provide an implementation that segfaults if
5998 ** it is passed a NULL pointer).
6000 ** The xMutexInit() method must be threadsafe. ^It must be harmless to
6001 ** invoke xMutexInit() multiple times within the same process and without
6002 ** intervening calls to xMutexEnd(). Second and subsequent calls to
6003 ** xMutexInit() must be no-ops.
6005 ** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
6006 ** and its associates). ^Similarly, xMutexAlloc() must not use SQLite memory
6007 ** allocation for a static mutex. ^However xMutexAlloc() may use SQLite
6008 ** memory allocation for a fast or recursive mutex.
6010 ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
6011 ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
6012 ** If xMutexInit fails in any way, it is expected to clean up after itself
6013 ** prior to returning.
6015 typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
6016 struct sqlite3_mutex_methods {
6017 int (*xMutexInit)(void);
6018 int (*xMutexEnd)(void);
6019 sqlite3_mutex *(*xMutexAlloc)(int);
6020 void (*xMutexFree)(sqlite3_mutex *);
6021 void (*xMutexEnter)(sqlite3_mutex *);
6022 int (*xMutexTry)(sqlite3_mutex *);
6023 void (*xMutexLeave)(sqlite3_mutex *);
6024 int (*xMutexHeld)(sqlite3_mutex *);
6025 int (*xMutexNotheld)(sqlite3_mutex *);
6029 ** CAPI3REF: Mutex Verification Routines
6031 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
6032 ** are intended for use inside assert() statements. ^The SQLite core
6033 ** never uses these routines except inside an assert() and applications
6034 ** are advised to follow the lead of the core. ^The SQLite core only
6035 ** provides implementations for these routines when it is compiled
6036 ** with the SQLITE_DEBUG flag. ^External mutex implementations
6037 ** are only required to provide these routines if SQLITE_DEBUG is
6038 ** defined and if NDEBUG is not defined.
6040 ** ^These routines should return true if the mutex in their argument
6041 ** is held or not held, respectively, by the calling thread.
6043 ** ^The implementation is not required to provided versions of these
6044 ** routines that actually work. If the implementation does not provide working
6045 ** versions of these routines, it should at least provide stubs that always
6046 ** return true so that one does not get spurious assertion failures.
6048 ** ^If the argument to sqlite3_mutex_held() is a NULL pointer then
6049 ** the routine should return 1. This seems counter-intuitive since
6050 ** clearly the mutex cannot be held if it does not exist. But
6051 ** the reason the mutex does not exist is because the build is not
6052 ** using mutexes. And we do not want the assert() containing the
6053 ** call to sqlite3_mutex_held() to fail, so a non-zero return is
6054 ** the appropriate thing to do. ^The sqlite3_mutex_notheld()
6055 ** interface should also return 1 when given a NULL pointer.
6057 #ifndef NDEBUG
6058 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
6059 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
6060 #endif
6063 ** CAPI3REF: Mutex Types
6065 ** The [sqlite3_mutex_alloc()] interface takes a single argument
6066 ** which is one of these integer constants.
6068 ** The set of static mutexes may change from one SQLite release to the
6069 ** next. Applications that override the built-in mutex logic must be
6070 ** prepared to accommodate additional static mutexes.
6072 #define SQLITE_MUTEX_FAST 0
6073 #define SQLITE_MUTEX_RECURSIVE 1
6074 #define SQLITE_MUTEX_STATIC_MASTER 2
6075 #define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */
6076 #define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */
6077 #define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */
6078 #define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_random() */
6079 #define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */
6080 #define SQLITE_MUTEX_STATIC_LRU2 7 /* NOT USED */
6081 #define SQLITE_MUTEX_STATIC_PMEM 7 /* sqlite3PageMalloc() */
6084 ** CAPI3REF: Retrieve the mutex for a database connection
6086 ** ^This interface returns a pointer the [sqlite3_mutex] object that
6087 ** serializes access to the [database connection] given in the argument
6088 ** when the [threading mode] is Serialized.
6089 ** ^If the [threading mode] is Single-thread or Multi-thread then this
6090 ** routine returns a NULL pointer.
6092 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
6095 ** CAPI3REF: Low-Level Control Of Database Files
6097 ** ^The [sqlite3_file_control()] interface makes a direct call to the
6098 ** xFileControl method for the [sqlite3_io_methods] object associated
6099 ** with a particular database identified by the second argument. ^The
6100 ** name of the database is "main" for the main database or "temp" for the
6101 ** TEMP database, or the name that appears after the AS keyword for
6102 ** databases that are added using the [ATTACH] SQL command.
6103 ** ^A NULL pointer can be used in place of "main" to refer to the
6104 ** main database file.
6105 ** ^The third and fourth parameters to this routine
6106 ** are passed directly through to the second and third parameters of
6107 ** the xFileControl method. ^The return value of the xFileControl
6108 ** method becomes the return value of this routine.
6110 ** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
6111 ** a pointer to the underlying [sqlite3_file] object to be written into
6112 ** the space pointed to by the 4th parameter. ^The SQLITE_FCNTL_FILE_POINTER
6113 ** case is a short-circuit path which does not actually invoke the
6114 ** underlying sqlite3_io_methods.xFileControl method.
6116 ** ^If the second parameter (zDbName) does not match the name of any
6117 ** open database file, then SQLITE_ERROR is returned. ^This error
6118 ** code is not remembered and will not be recalled by [sqlite3_errcode()]
6119 ** or [sqlite3_errmsg()]. The underlying xFileControl method might
6120 ** also return SQLITE_ERROR. There is no way to distinguish between
6121 ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
6122 ** xFileControl method.
6124 ** See also: [SQLITE_FCNTL_LOCKSTATE]
6126 SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
6129 ** CAPI3REF: Testing Interface
6131 ** ^The sqlite3_test_control() interface is used to read out internal
6132 ** state of SQLite and to inject faults into SQLite for testing
6133 ** purposes. ^The first parameter is an operation code that determines
6134 ** the number, meaning, and operation of all subsequent parameters.
6136 ** This interface is not for use by applications. It exists solely
6137 ** for verifying the correct operation of the SQLite library. Depending
6138 ** on how the SQLite library is compiled, this interface might not exist.
6140 ** The details of the operation codes, their meanings, the parameters
6141 ** they take, and what they do are all subject to change without notice.
6142 ** Unlike most of the SQLite API, this function is not guaranteed to
6143 ** operate consistently from one release to the next.
6145 SQLITE_API int sqlite3_test_control(int op, ...);
6148 ** CAPI3REF: Testing Interface Operation Codes
6150 ** These constants are the valid operation code parameters used
6151 ** as the first argument to [sqlite3_test_control()].
6153 ** These parameters and their meanings are subject to change
6154 ** without notice. These values are for testing purposes only.
6155 ** Applications should not use any of these parameters or the
6156 ** [sqlite3_test_control()] interface.
6158 #define SQLITE_TESTCTRL_FIRST 5
6159 #define SQLITE_TESTCTRL_PRNG_SAVE 5
6160 #define SQLITE_TESTCTRL_PRNG_RESTORE 6
6161 #define SQLITE_TESTCTRL_PRNG_RESET 7
6162 #define SQLITE_TESTCTRL_BITVEC_TEST 8
6163 #define SQLITE_TESTCTRL_FAULT_INSTALL 9
6164 #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10
6165 #define SQLITE_TESTCTRL_PENDING_BYTE 11
6166 #define SQLITE_TESTCTRL_ASSERT 12
6167 #define SQLITE_TESTCTRL_ALWAYS 13
6168 #define SQLITE_TESTCTRL_RESERVE 14
6169 #define SQLITE_TESTCTRL_OPTIMIZATIONS 15
6170 #define SQLITE_TESTCTRL_ISKEYWORD 16
6171 #define SQLITE_TESTCTRL_PGHDRSZ 17
6172 #define SQLITE_TESTCTRL_SCRATCHMALLOC 18
6173 #define SQLITE_TESTCTRL_LOCALTIME_FAULT 19
6174 #define SQLITE_TESTCTRL_LAST 19
6177 ** CAPI3REF: SQLite Runtime Status
6179 ** ^This interface is used to retrieve runtime status information
6180 ** about the performance of SQLite, and optionally to reset various
6181 ** highwater marks. ^The first argument is an integer code for
6182 ** the specific parameter to measure. ^(Recognized integer codes
6183 ** are of the form [status parameters | SQLITE_STATUS_...].)^
6184 ** ^The current value of the parameter is returned into *pCurrent.
6185 ** ^The highest recorded value is returned in *pHighwater. ^If the
6186 ** resetFlag is true, then the highest record value is reset after
6187 ** *pHighwater is written. ^(Some parameters do not record the highest
6188 ** value. For those parameters
6189 ** nothing is written into *pHighwater and the resetFlag is ignored.)^
6190 ** ^(Other parameters record only the highwater mark and not the current
6191 ** value. For these latter parameters nothing is written into *pCurrent.)^
6193 ** ^The sqlite3_status() routine returns SQLITE_OK on success and a
6194 ** non-zero [error code] on failure.
6196 ** This routine is threadsafe but is not atomic. This routine can be
6197 ** called while other threads are running the same or different SQLite
6198 ** interfaces. However the values returned in *pCurrent and
6199 ** *pHighwater reflect the status of SQLite at different points in time
6200 ** and it is possible that another thread might change the parameter
6201 ** in between the times when *pCurrent and *pHighwater are written.
6203 ** See also: [sqlite3_db_status()]
6205 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
6209 ** CAPI3REF: Status Parameters
6210 ** KEYWORDS: {status parameters}
6212 ** These integer constants designate various run-time status parameters
6213 ** that can be returned by [sqlite3_status()].
6215 ** <dl>
6216 ** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
6217 ** <dd>This parameter is the current amount of memory checked out
6218 ** using [sqlite3_malloc()], either directly or indirectly. The
6219 ** figure includes calls made to [sqlite3_malloc()] by the application
6220 ** and internal memory usage by the SQLite library. Scratch memory
6221 ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
6222 ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
6223 ** this parameter. The amount returned is the sum of the allocation
6224 ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
6226 ** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
6227 ** <dd>This parameter records the largest memory allocation request
6228 ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
6229 ** internal equivalents). Only the value returned in the
6230 ** *pHighwater parameter to [sqlite3_status()] is of interest.
6231 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6233 ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
6234 ** <dd>This parameter records the number of separate memory allocations
6235 ** currently checked out.</dd>)^
6237 ** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
6238 ** <dd>This parameter returns the number of pages used out of the
6239 ** [pagecache memory allocator] that was configured using
6240 ** [SQLITE_CONFIG_PAGECACHE]. The
6241 ** value returned is in pages, not in bytes.</dd>)^
6243 ** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]]
6244 ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
6245 ** <dd>This parameter returns the number of bytes of page cache
6246 ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
6247 ** buffer and where forced to overflow to [sqlite3_malloc()]. The
6248 ** returned value includes allocations that overflowed because they
6249 ** where too large (they were larger than the "sz" parameter to
6250 ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
6251 ** no space was left in the page cache.</dd>)^
6253 ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
6254 ** <dd>This parameter records the largest memory allocation request
6255 ** handed to [pagecache memory allocator]. Only the value returned in the
6256 ** *pHighwater parameter to [sqlite3_status()] is of interest.
6257 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6259 ** [[SQLITE_STATUS_SCRATCH_USED]] ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
6260 ** <dd>This parameter returns the number of allocations used out of the
6261 ** [scratch memory allocator] configured using
6262 ** [SQLITE_CONFIG_SCRATCH]. The value returned is in allocations, not
6263 ** in bytes. Since a single thread may only have one scratch allocation
6264 ** outstanding at time, this parameter also reports the number of threads
6265 ** using scratch memory at the same time.</dd>)^
6267 ** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
6268 ** <dd>This parameter returns the number of bytes of scratch memory
6269 ** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
6270 ** buffer and where forced to overflow to [sqlite3_malloc()]. The values
6271 ** returned include overflows because the requested allocation was too
6272 ** larger (that is, because the requested allocation was larger than the
6273 ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
6274 ** slots were available.
6275 ** </dd>)^
6277 ** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
6278 ** <dd>This parameter records the largest memory allocation request
6279 ** handed to [scratch memory allocator]. Only the value returned in the
6280 ** *pHighwater parameter to [sqlite3_status()] is of interest.
6281 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6283 ** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
6284 ** <dd>This parameter records the deepest parser stack. It is only
6285 ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
6286 ** </dl>
6288 ** New status parameters may be added from time to time.
6290 #define SQLITE_STATUS_MEMORY_USED 0
6291 #define SQLITE_STATUS_PAGECACHE_USED 1
6292 #define SQLITE_STATUS_PAGECACHE_OVERFLOW 2
6293 #define SQLITE_STATUS_SCRATCH_USED 3
6294 #define SQLITE_STATUS_SCRATCH_OVERFLOW 4
6295 #define SQLITE_STATUS_MALLOC_SIZE 5
6296 #define SQLITE_STATUS_PARSER_STACK 6
6297 #define SQLITE_STATUS_PAGECACHE_SIZE 7
6298 #define SQLITE_STATUS_SCRATCH_SIZE 8
6299 #define SQLITE_STATUS_MALLOC_COUNT 9
6302 ** CAPI3REF: Database Connection Status
6304 ** ^This interface is used to retrieve runtime status information
6305 ** about a single [database connection]. ^The first argument is the
6306 ** database connection object to be interrogated. ^The second argument
6307 ** is an integer constant, taken from the set of
6308 ** [SQLITE_DBSTATUS options], that
6309 ** determines the parameter to interrogate. The set of
6310 ** [SQLITE_DBSTATUS options] is likely
6311 ** to grow in future releases of SQLite.
6313 ** ^The current value of the requested parameter is written into *pCur
6314 ** and the highest instantaneous value is written into *pHiwtr. ^If
6315 ** the resetFlg is true, then the highest instantaneous value is
6316 ** reset back down to the current value.
6318 ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
6319 ** non-zero [error code] on failure.
6321 ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
6323 SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
6326 ** CAPI3REF: Status Parameters for database connections
6327 ** KEYWORDS: {SQLITE_DBSTATUS options}
6329 ** These constants are the available integer "verbs" that can be passed as
6330 ** the second argument to the [sqlite3_db_status()] interface.
6332 ** New verbs may be added in future releases of SQLite. Existing verbs
6333 ** might be discontinued. Applications should check the return code from
6334 ** [sqlite3_db_status()] to make sure that the call worked.
6335 ** The [sqlite3_db_status()] interface will return a non-zero error code
6336 ** if a discontinued or unsupported verb is invoked.
6338 ** <dl>
6339 ** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
6340 ** <dd>This parameter returns the number of lookaside memory slots currently
6341 ** checked out.</dd>)^
6343 ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
6344 ** <dd>This parameter returns the number malloc attempts that were
6345 ** satisfied using lookaside memory. Only the high-water value is meaningful;
6346 ** the current value is always zero.)^
6348 ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
6349 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
6350 ** <dd>This parameter returns the number malloc attempts that might have
6351 ** been satisfied using lookaside memory but failed due to the amount of
6352 ** memory requested being larger than the lookaside slot size.
6353 ** Only the high-water value is meaningful;
6354 ** the current value is always zero.)^
6356 ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
6357 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
6358 ** <dd>This parameter returns the number malloc attempts that might have
6359 ** been satisfied using lookaside memory but failed due to all lookaside
6360 ** memory already being in use.
6361 ** Only the high-water value is meaningful;
6362 ** the current value is always zero.)^
6364 ** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
6365 ** <dd>This parameter returns the approximate number of of bytes of heap
6366 ** memory used by all pager caches associated with the database connection.)^
6367 ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
6369 ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
6370 ** <dd>This parameter returns the approximate number of of bytes of heap
6371 ** memory used to store the schema for all databases associated
6372 ** with the connection - main, temp, and any [ATTACH]-ed databases.)^
6373 ** ^The full amount of memory used by the schemas is reported, even if the
6374 ** schema memory is shared with other database connections due to
6375 ** [shared cache mode] being enabled.
6376 ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
6378 ** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
6379 ** <dd>This parameter returns the approximate number of of bytes of heap
6380 ** and lookaside memory used by all prepared statements associated with
6381 ** the database connection.)^
6382 ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
6383 ** </dd>
6385 ** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
6386 ** <dd>This parameter returns the number of pager cache hits that have
6387 ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT
6388 ** is always 0.
6389 ** </dd>
6391 ** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
6392 ** <dd>This parameter returns the number of pager cache misses that have
6393 ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS
6394 ** is always 0.
6395 ** </dd>
6396 ** </dl>
6398 #define SQLITE_DBSTATUS_LOOKASIDE_USED 0
6399 #define SQLITE_DBSTATUS_CACHE_USED 1
6400 #define SQLITE_DBSTATUS_SCHEMA_USED 2
6401 #define SQLITE_DBSTATUS_STMT_USED 3
6402 #define SQLITE_DBSTATUS_LOOKASIDE_HIT 4
6403 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE 5
6404 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL 6
6405 #define SQLITE_DBSTATUS_CACHE_HIT 7
6406 #define SQLITE_DBSTATUS_CACHE_MISS 8
6407 #define SQLITE_DBSTATUS_MAX 8 /* Largest defined DBSTATUS */
6411 ** CAPI3REF: Prepared Statement Status
6413 ** ^(Each prepared statement maintains various
6414 ** [SQLITE_STMTSTATUS counters] that measure the number
6415 ** of times it has performed specific operations.)^ These counters can
6416 ** be used to monitor the performance characteristics of the prepared
6417 ** statements. For example, if the number of table steps greatly exceeds
6418 ** the number of table searches or result rows, that would tend to indicate
6419 ** that the prepared statement is using a full table scan rather than
6420 ** an index.
6422 ** ^(This interface is used to retrieve and reset counter values from
6423 ** a [prepared statement]. The first argument is the prepared statement
6424 ** object to be interrogated. The second argument
6425 ** is an integer code for a specific [SQLITE_STMTSTATUS counter]
6426 ** to be interrogated.)^
6427 ** ^The current value of the requested counter is returned.
6428 ** ^If the resetFlg is true, then the counter is reset to zero after this
6429 ** interface call returns.
6431 ** See also: [sqlite3_status()] and [sqlite3_db_status()].
6433 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
6436 ** CAPI3REF: Status Parameters for prepared statements
6437 ** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
6439 ** These preprocessor macros define integer codes that name counter
6440 ** values associated with the [sqlite3_stmt_status()] interface.
6441 ** The meanings of the various counters are as follows:
6443 ** <dl>
6444 ** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
6445 ** <dd>^This is the number of times that SQLite has stepped forward in
6446 ** a table as part of a full table scan. Large numbers for this counter
6447 ** may indicate opportunities for performance improvement through
6448 ** careful use of indices.</dd>
6450 ** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
6451 ** <dd>^This is the number of sort operations that have occurred.
6452 ** A non-zero value in this counter may indicate an opportunity to
6453 ** improvement performance through careful use of indices.</dd>
6455 ** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
6456 ** <dd>^This is the number of rows inserted into transient indices that
6457 ** were created automatically in order to help joins run faster.
6458 ** A non-zero value in this counter may indicate an opportunity to
6459 ** improvement performance by adding permanent indices that do not
6460 ** need to be reinitialized each time the statement is run.</dd>
6461 ** </dl>
6463 #define SQLITE_STMTSTATUS_FULLSCAN_STEP 1
6464 #define SQLITE_STMTSTATUS_SORT 2
6465 #define SQLITE_STMTSTATUS_AUTOINDEX 3
6468 ** CAPI3REF: Custom Page Cache Object
6470 ** The sqlite3_pcache type is opaque. It is implemented by
6471 ** the pluggable module. The SQLite core has no knowledge of
6472 ** its size or internal structure and never deals with the
6473 ** sqlite3_pcache object except by holding and passing pointers
6474 ** to the object.
6476 ** See [sqlite3_pcache_methods] for additional information.
6478 typedef struct sqlite3_pcache sqlite3_pcache;
6481 ** CAPI3REF: Application Defined Page Cache.
6482 ** KEYWORDS: {page cache}
6484 ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE], ...) interface can
6485 ** register an alternative page cache implementation by passing in an
6486 ** instance of the sqlite3_pcache_methods structure.)^
6487 ** In many applications, most of the heap memory allocated by
6488 ** SQLite is used for the page cache.
6489 ** By implementing a
6490 ** custom page cache using this API, an application can better control
6491 ** the amount of memory consumed by SQLite, the way in which
6492 ** that memory is allocated and released, and the policies used to
6493 ** determine exactly which parts of a database file are cached and for
6494 ** how long.
6496 ** The alternative page cache mechanism is an
6497 ** extreme measure that is only needed by the most demanding applications.
6498 ** The built-in page cache is recommended for most uses.
6500 ** ^(The contents of the sqlite3_pcache_methods structure are copied to an
6501 ** internal buffer by SQLite within the call to [sqlite3_config]. Hence
6502 ** the application may discard the parameter after the call to
6503 ** [sqlite3_config()] returns.)^
6505 ** [[the xInit() page cache method]]
6506 ** ^(The xInit() method is called once for each effective
6507 ** call to [sqlite3_initialize()])^
6508 ** (usually only once during the lifetime of the process). ^(The xInit()
6509 ** method is passed a copy of the sqlite3_pcache_methods.pArg value.)^
6510 ** The intent of the xInit() method is to set up global data structures
6511 ** required by the custom page cache implementation.
6512 ** ^(If the xInit() method is NULL, then the
6513 ** built-in default page cache is used instead of the application defined
6514 ** page cache.)^
6516 ** [[the xShutdown() page cache method]]
6517 ** ^The xShutdown() method is called by [sqlite3_shutdown()].
6518 ** It can be used to clean up
6519 ** any outstanding resources before process shutdown, if required.
6520 ** ^The xShutdown() method may be NULL.
6522 ** ^SQLite automatically serializes calls to the xInit method,
6523 ** so the xInit method need not be threadsafe. ^The
6524 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
6525 ** not need to be threadsafe either. All other methods must be threadsafe
6526 ** in multithreaded applications.
6528 ** ^SQLite will never invoke xInit() more than once without an intervening
6529 ** call to xShutdown().
6531 ** [[the xCreate() page cache methods]]
6532 ** ^SQLite invokes the xCreate() method to construct a new cache instance.
6533 ** SQLite will typically create one cache instance for each open database file,
6534 ** though this is not guaranteed. ^The
6535 ** first parameter, szPage, is the size in bytes of the pages that must
6536 ** be allocated by the cache. ^szPage will not be a power of two. ^szPage
6537 ** will the page size of the database file that is to be cached plus an
6538 ** increment (here called "R") of less than 250. SQLite will use the
6539 ** extra R bytes on each page to store metadata about the underlying
6540 ** database page on disk. The value of R depends
6541 ** on the SQLite version, the target platform, and how SQLite was compiled.
6542 ** ^(R is constant for a particular build of SQLite. Except, there are two
6543 ** distinct values of R when SQLite is compiled with the proprietary
6544 ** ZIPVFS extension.)^ ^The second argument to
6545 ** xCreate(), bPurgeable, is true if the cache being created will
6546 ** be used to cache database pages of a file stored on disk, or
6547 ** false if it is used for an in-memory database. The cache implementation
6548 ** does not have to do anything special based with the value of bPurgeable;
6549 ** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will
6550 ** never invoke xUnpin() except to deliberately delete a page.
6551 ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
6552 ** false will always have the "discard" flag set to true.
6553 ** ^Hence, a cache created with bPurgeable false will
6554 ** never contain any unpinned pages.
6556 ** [[the xCachesize() page cache method]]
6557 ** ^(The xCachesize() method may be called at any time by SQLite to set the
6558 ** suggested maximum cache-size (number of pages stored by) the cache
6559 ** instance passed as the first argument. This is the value configured using
6560 ** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable
6561 ** parameter, the implementation is not required to do anything with this
6562 ** value; it is advisory only.
6564 ** [[the xPagecount() page cache methods]]
6565 ** The xPagecount() method must return the number of pages currently
6566 ** stored in the cache, both pinned and unpinned.
6568 ** [[the xFetch() page cache methods]]
6569 ** The xFetch() method locates a page in the cache and returns a pointer to
6570 ** the page, or a NULL pointer.
6571 ** A "page", in this context, means a buffer of szPage bytes aligned at an
6572 ** 8-byte boundary. The page to be fetched is determined by the key. ^The
6573 ** minimum key value is 1. After it has been retrieved using xFetch, the page
6574 ** is considered to be "pinned".
6576 ** If the requested page is already in the page cache, then the page cache
6577 ** implementation must return a pointer to the page buffer with its content
6578 ** intact. If the requested page is not already in the cache, then the
6579 ** cache implementation should use the value of the createFlag
6580 ** parameter to help it determined what action to take:
6582 ** <table border=1 width=85% align=center>
6583 ** <tr><th> createFlag <th> Behaviour when page is not already in cache
6584 ** <tr><td> 0 <td> Do not allocate a new page. Return NULL.
6585 ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
6586 ** Otherwise return NULL.
6587 ** <tr><td> 2 <td> Make every effort to allocate a new page. Only return
6588 ** NULL if allocating a new page is effectively impossible.
6589 ** </table>
6591 ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite
6592 ** will only use a createFlag of 2 after a prior call with a createFlag of 1
6593 ** failed.)^ In between the to xFetch() calls, SQLite may
6594 ** attempt to unpin one or more cache pages by spilling the content of
6595 ** pinned pages to disk and synching the operating system disk cache.
6597 ** [[the xUnpin() page cache method]]
6598 ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
6599 ** as its second argument. If the third parameter, discard, is non-zero,
6600 ** then the page must be evicted from the cache.
6601 ** ^If the discard parameter is
6602 ** zero, then the page may be discarded or retained at the discretion of
6603 ** page cache implementation. ^The page cache implementation
6604 ** may choose to evict unpinned pages at any time.
6606 ** The cache must not perform any reference counting. A single
6607 ** call to xUnpin() unpins the page regardless of the number of prior calls
6608 ** to xFetch().
6610 ** [[the xRekey() page cache methods]]
6611 ** The xRekey() method is used to change the key value associated with the
6612 ** page passed as the second argument. If the cache
6613 ** previously contains an entry associated with newKey, it must be
6614 ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
6615 ** to be pinned.
6617 ** When SQLite calls the xTruncate() method, the cache must discard all
6618 ** existing cache entries with page numbers (keys) greater than or equal
6619 ** to the value of the iLimit parameter passed to xTruncate(). If any
6620 ** of these pages are pinned, they are implicitly unpinned, meaning that
6621 ** they can be safely discarded.
6623 ** [[the xDestroy() page cache method]]
6624 ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
6625 ** All resources associated with the specified cache should be freed. ^After
6626 ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
6627 ** handle invalid, and will not use it with any other sqlite3_pcache_methods
6628 ** functions.
6630 typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
6631 struct sqlite3_pcache_methods {
6632 void *pArg;
6633 int (*xInit)(void*);
6634 void (*xShutdown)(void*);
6635 sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
6636 void (*xCachesize)(sqlite3_pcache*, int nCachesize);
6637 int (*xPagecount)(sqlite3_pcache*);
6638 void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
6639 void (*xUnpin)(sqlite3_pcache*, void*, int discard);
6640 void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
6641 void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
6642 void (*xDestroy)(sqlite3_pcache*);
6646 ** CAPI3REF: Online Backup Object
6648 ** The sqlite3_backup object records state information about an ongoing
6649 ** online backup operation. ^The sqlite3_backup object is created by
6650 ** a call to [sqlite3_backup_init()] and is destroyed by a call to
6651 ** [sqlite3_backup_finish()].
6653 ** See Also: [Using the SQLite Online Backup API]
6655 typedef struct sqlite3_backup sqlite3_backup;
6658 ** CAPI3REF: Online Backup API.
6660 ** The backup API copies the content of one database into another.
6661 ** It is useful either for creating backups of databases or
6662 ** for copying in-memory databases to or from persistent files.
6664 ** See Also: [Using the SQLite Online Backup API]
6666 ** ^SQLite holds a write transaction open on the destination database file
6667 ** for the duration of the backup operation.
6668 ** ^The source database is read-locked only while it is being read;
6669 ** it is not locked continuously for the entire backup operation.
6670 ** ^Thus, the backup may be performed on a live source database without
6671 ** preventing other database connections from
6672 ** reading or writing to the source database while the backup is underway.
6674 ** ^(To perform a backup operation:
6675 ** <ol>
6676 ** <li><b>sqlite3_backup_init()</b> is called once to initialize the
6677 ** backup,
6678 ** <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
6679 ** the data between the two databases, and finally
6680 ** <li><b>sqlite3_backup_finish()</b> is called to release all resources
6681 ** associated with the backup operation.
6682 ** </ol>)^
6683 ** There should be exactly one call to sqlite3_backup_finish() for each
6684 ** successful call to sqlite3_backup_init().
6686 ** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
6688 ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
6689 ** [database connection] associated with the destination database
6690 ** and the database name, respectively.
6691 ** ^The database name is "main" for the main database, "temp" for the
6692 ** temporary database, or the name specified after the AS keyword in
6693 ** an [ATTACH] statement for an attached database.
6694 ** ^The S and M arguments passed to
6695 ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
6696 ** and database name of the source database, respectively.
6697 ** ^The source and destination [database connections] (parameters S and D)
6698 ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
6699 ** an error.
6701 ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
6702 ** returned and an error code and error message are stored in the
6703 ** destination [database connection] D.
6704 ** ^The error code and message for the failed call to sqlite3_backup_init()
6705 ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
6706 ** [sqlite3_errmsg16()] functions.
6707 ** ^A successful call to sqlite3_backup_init() returns a pointer to an
6708 ** [sqlite3_backup] object.
6709 ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
6710 ** sqlite3_backup_finish() functions to perform the specified backup
6711 ** operation.
6713 ** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
6715 ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
6716 ** the source and destination databases specified by [sqlite3_backup] object B.
6717 ** ^If N is negative, all remaining source pages are copied.
6718 ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
6719 ** are still more pages to be copied, then the function returns [SQLITE_OK].
6720 ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
6721 ** from source to destination, then it returns [SQLITE_DONE].
6722 ** ^If an error occurs while running sqlite3_backup_step(B,N),
6723 ** then an [error code] is returned. ^As well as [SQLITE_OK] and
6724 ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
6725 ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
6726 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
6728 ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
6729 ** <ol>
6730 ** <li> the destination database was opened read-only, or
6731 ** <li> the destination database is using write-ahead-log journaling
6732 ** and the destination and source page sizes differ, or
6733 ** <li> the destination database is an in-memory database and the
6734 ** destination and source page sizes differ.
6735 ** </ol>)^
6737 ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
6738 ** the [sqlite3_busy_handler | busy-handler function]
6739 ** is invoked (if one is specified). ^If the
6740 ** busy-handler returns non-zero before the lock is available, then
6741 ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
6742 ** sqlite3_backup_step() can be retried later. ^If the source
6743 ** [database connection]
6744 ** is being used to write to the source database when sqlite3_backup_step()
6745 ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
6746 ** case the call to sqlite3_backup_step() can be retried later on. ^(If
6747 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
6748 ** [SQLITE_READONLY] is returned, then
6749 ** there is no point in retrying the call to sqlite3_backup_step(). These
6750 ** errors are considered fatal.)^ The application must accept
6751 ** that the backup operation has failed and pass the backup operation handle
6752 ** to the sqlite3_backup_finish() to release associated resources.
6754 ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
6755 ** on the destination file. ^The exclusive lock is not released until either
6756 ** sqlite3_backup_finish() is called or the backup operation is complete
6757 ** and sqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to
6758 ** sqlite3_backup_step() obtains a [shared lock] on the source database that
6759 ** lasts for the duration of the sqlite3_backup_step() call.
6760 ** ^Because the source database is not locked between calls to
6761 ** sqlite3_backup_step(), the source database may be modified mid-way
6762 ** through the backup process. ^If the source database is modified by an
6763 ** external process or via a database connection other than the one being
6764 ** used by the backup operation, then the backup will be automatically
6765 ** restarted by the next call to sqlite3_backup_step(). ^If the source
6766 ** database is modified by the using the same database connection as is used
6767 ** by the backup operation, then the backup database is automatically
6768 ** updated at the same time.
6770 ** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
6772 ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
6773 ** application wishes to abandon the backup operation, the application
6774 ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
6775 ** ^The sqlite3_backup_finish() interfaces releases all
6776 ** resources associated with the [sqlite3_backup] object.
6777 ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
6778 ** active write-transaction on the destination database is rolled back.
6779 ** The [sqlite3_backup] object is invalid
6780 ** and may not be used following a call to sqlite3_backup_finish().
6782 ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
6783 ** sqlite3_backup_step() errors occurred, regardless or whether or not
6784 ** sqlite3_backup_step() completed.
6785 ** ^If an out-of-memory condition or IO error occurred during any prior
6786 ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
6787 ** sqlite3_backup_finish() returns the corresponding [error code].
6789 ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
6790 ** is not a permanent error and does not affect the return value of
6791 ** sqlite3_backup_finish().
6793 ** [[sqlite3_backup__remaining()]] [[sqlite3_backup_pagecount()]]
6794 ** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
6796 ** ^Each call to sqlite3_backup_step() sets two values inside
6797 ** the [sqlite3_backup] object: the number of pages still to be backed
6798 ** up and the total number of pages in the source database file.
6799 ** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces
6800 ** retrieve these two values, respectively.
6802 ** ^The values returned by these functions are only updated by
6803 ** sqlite3_backup_step(). ^If the source database is modified during a backup
6804 ** operation, then the values are not updated to account for any extra
6805 ** pages that need to be updated or the size of the source database file
6806 ** changing.
6808 ** <b>Concurrent Usage of Database Handles</b>
6810 ** ^The source [database connection] may be used by the application for other
6811 ** purposes while a backup operation is underway or being initialized.
6812 ** ^If SQLite is compiled and configured to support threadsafe database
6813 ** connections, then the source database connection may be used concurrently
6814 ** from within other threads.
6816 ** However, the application must guarantee that the destination
6817 ** [database connection] is not passed to any other API (by any thread) after
6818 ** sqlite3_backup_init() is called and before the corresponding call to
6819 ** sqlite3_backup_finish(). SQLite does not currently check to see
6820 ** if the application incorrectly accesses the destination [database connection]
6821 ** and so no error code is reported, but the operations may malfunction
6822 ** nevertheless. Use of the destination database connection while a
6823 ** backup is in progress might also also cause a mutex deadlock.
6825 ** If running in [shared cache mode], the application must
6826 ** guarantee that the shared cache used by the destination database
6827 ** is not accessed while the backup is running. In practice this means
6828 ** that the application must guarantee that the disk file being
6829 ** backed up to is not accessed by any connection within the process,
6830 ** not just the specific connection that was passed to sqlite3_backup_init().
6832 ** The [sqlite3_backup] object itself is partially threadsafe. Multiple
6833 ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
6834 ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
6835 ** APIs are not strictly speaking threadsafe. If they are invoked at the
6836 ** same time as another thread is invoking sqlite3_backup_step() it is
6837 ** possible that they return invalid values.
6839 SQLITE_API sqlite3_backup *sqlite3_backup_init(
6840 sqlite3 *pDest, /* Destination database handle */
6841 const char *zDestName, /* Destination database name */
6842 sqlite3 *pSource, /* Source database handle */
6843 const char *zSourceName /* Source database name */
6845 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
6846 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
6847 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
6848 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
6851 ** CAPI3REF: Unlock Notification
6853 ** ^When running in shared-cache mode, a database operation may fail with
6854 ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
6855 ** individual tables within the shared-cache cannot be obtained. See
6856 ** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
6857 ** ^This API may be used to register a callback that SQLite will invoke
6858 ** when the connection currently holding the required lock relinquishes it.
6859 ** ^This API is only available if the library was compiled with the
6860 ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
6862 ** See Also: [Using the SQLite Unlock Notification Feature].
6864 ** ^Shared-cache locks are released when a database connection concludes
6865 ** its current transaction, either by committing it or rolling it back.
6867 ** ^When a connection (known as the blocked connection) fails to obtain a
6868 ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
6869 ** identity of the database connection (the blocking connection) that
6870 ** has locked the required resource is stored internally. ^After an
6871 ** application receives an SQLITE_LOCKED error, it may call the
6872 ** sqlite3_unlock_notify() method with the blocked connection handle as
6873 ** the first argument to register for a callback that will be invoked
6874 ** when the blocking connections current transaction is concluded. ^The
6875 ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
6876 ** call that concludes the blocking connections transaction.
6878 ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
6879 ** there is a chance that the blocking connection will have already
6880 ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
6881 ** If this happens, then the specified callback is invoked immediately,
6882 ** from within the call to sqlite3_unlock_notify().)^
6884 ** ^If the blocked connection is attempting to obtain a write-lock on a
6885 ** shared-cache table, and more than one other connection currently holds
6886 ** a read-lock on the same table, then SQLite arbitrarily selects one of
6887 ** the other connections to use as the blocking connection.
6889 ** ^(There may be at most one unlock-notify callback registered by a
6890 ** blocked connection. If sqlite3_unlock_notify() is called when the
6891 ** blocked connection already has a registered unlock-notify callback,
6892 ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
6893 ** called with a NULL pointer as its second argument, then any existing
6894 ** unlock-notify callback is canceled. ^The blocked connections
6895 ** unlock-notify callback may also be canceled by closing the blocked
6896 ** connection using [sqlite3_close()].
6898 ** The unlock-notify callback is not reentrant. If an application invokes
6899 ** any sqlite3_xxx API functions from within an unlock-notify callback, a
6900 ** crash or deadlock may be the result.
6902 ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
6903 ** returns SQLITE_OK.
6905 ** <b>Callback Invocation Details</b>
6907 ** When an unlock-notify callback is registered, the application provides a
6908 ** single void* pointer that is passed to the callback when it is invoked.
6909 ** However, the signature of the callback function allows SQLite to pass
6910 ** it an array of void* context pointers. The first argument passed to
6911 ** an unlock-notify callback is a pointer to an array of void* pointers,
6912 ** and the second is the number of entries in the array.
6914 ** When a blocking connections transaction is concluded, there may be
6915 ** more than one blocked connection that has registered for an unlock-notify
6916 ** callback. ^If two or more such blocked connections have specified the
6917 ** same callback function, then instead of invoking the callback function
6918 ** multiple times, it is invoked once with the set of void* context pointers
6919 ** specified by the blocked connections bundled together into an array.
6920 ** This gives the application an opportunity to prioritize any actions
6921 ** related to the set of unblocked database connections.
6923 ** <b>Deadlock Detection</b>
6925 ** Assuming that after registering for an unlock-notify callback a
6926 ** database waits for the callback to be issued before taking any further
6927 ** action (a reasonable assumption), then using this API may cause the
6928 ** application to deadlock. For example, if connection X is waiting for
6929 ** connection Y's transaction to be concluded, and similarly connection
6930 ** Y is waiting on connection X's transaction, then neither connection
6931 ** will proceed and the system may remain deadlocked indefinitely.
6933 ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
6934 ** detection. ^If a given call to sqlite3_unlock_notify() would put the
6935 ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
6936 ** unlock-notify callback is registered. The system is said to be in
6937 ** a deadlocked state if connection A has registered for an unlock-notify
6938 ** callback on the conclusion of connection B's transaction, and connection
6939 ** B has itself registered for an unlock-notify callback when connection
6940 ** A's transaction is concluded. ^Indirect deadlock is also detected, so
6941 ** the system is also considered to be deadlocked if connection B has
6942 ** registered for an unlock-notify callback on the conclusion of connection
6943 ** C's transaction, where connection C is waiting on connection A. ^Any
6944 ** number of levels of indirection are allowed.
6946 ** <b>The "DROP TABLE" Exception</b>
6948 ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
6949 ** always appropriate to call sqlite3_unlock_notify(). There is however,
6950 ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
6951 ** SQLite checks if there are any currently executing SELECT statements
6952 ** that belong to the same connection. If there are, SQLITE_LOCKED is
6953 ** returned. In this case there is no "blocking connection", so invoking
6954 ** sqlite3_unlock_notify() results in the unlock-notify callback being
6955 ** invoked immediately. If the application then re-attempts the "DROP TABLE"
6956 ** or "DROP INDEX" query, an infinite loop might be the result.
6958 ** One way around this problem is to check the extended error code returned
6959 ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
6960 ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
6961 ** the special "DROP TABLE/INDEX" case, the extended error code is just
6962 ** SQLITE_LOCKED.)^
6964 SQLITE_API int sqlite3_unlock_notify(
6965 sqlite3 *pBlocked, /* Waiting connection */
6966 void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */
6967 void *pNotifyArg /* Argument to pass to xNotify */
6972 ** CAPI3REF: String Comparison
6974 ** ^The [sqlite3_strnicmp()] API allows applications and extensions to
6975 ** compare the contents of two buffers containing UTF-8 strings in a
6976 ** case-independent fashion, using the same definition of case independence
6977 ** that SQLite uses internally when comparing identifiers.
6979 SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
6982 ** CAPI3REF: Error Logging Interface
6984 ** ^The [sqlite3_log()] interface writes a message into the error log
6985 ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
6986 ** ^If logging is enabled, the zFormat string and subsequent arguments are
6987 ** used with [sqlite3_snprintf()] to generate the final output string.
6989 ** The sqlite3_log() interface is intended for use by extensions such as
6990 ** virtual tables, collating functions, and SQL functions. While there is
6991 ** nothing to prevent an application from calling sqlite3_log(), doing so
6992 ** is considered bad form.
6994 ** The zFormat string must not be NULL.
6996 ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
6997 ** will not use dynamically allocated memory. The log message is stored in
6998 ** a fixed-length buffer on the stack. If the log message is longer than
6999 ** a few hundred characters, it will be truncated to the length of the
7000 ** buffer.
7002 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
7005 ** CAPI3REF: Write-Ahead Log Commit Hook
7007 ** ^The [sqlite3_wal_hook()] function is used to register a callback that
7008 ** will be invoked each time a database connection commits data to a
7009 ** [write-ahead log] (i.e. whenever a transaction is committed in
7010 ** [journal_mode | journal_mode=WAL mode]).
7012 ** ^The callback is invoked by SQLite after the commit has taken place and
7013 ** the associated write-lock on the database released, so the implementation
7014 ** may read, write or [checkpoint] the database as required.
7016 ** ^The first parameter passed to the callback function when it is invoked
7017 ** is a copy of the third parameter passed to sqlite3_wal_hook() when
7018 ** registering the callback. ^The second is a copy of the database handle.
7019 ** ^The third parameter is the name of the database that was written to -
7020 ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
7021 ** is the number of pages currently in the write-ahead log file,
7022 ** including those that were just committed.
7024 ** The callback function should normally return [SQLITE_OK]. ^If an error
7025 ** code is returned, that error will propagate back up through the
7026 ** SQLite code base to cause the statement that provoked the callback
7027 ** to report an error, though the commit will have still occurred. If the
7028 ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
7029 ** that does not correspond to any valid SQLite error code, the results
7030 ** are undefined.
7032 ** A single database handle may have at most a single write-ahead log callback
7033 ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
7034 ** previously registered write-ahead log callback. ^Note that the
7035 ** [sqlite3_wal_autocheckpoint()] interface and the
7036 ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
7037 ** those overwrite any prior [sqlite3_wal_hook()] settings.
7039 SQLITE_API void *sqlite3_wal_hook(
7040 sqlite3*,
7041 int(*)(void *,sqlite3*,const char*,int),
7042 void*
7046 ** CAPI3REF: Configure an auto-checkpoint
7048 ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
7049 ** [sqlite3_wal_hook()] that causes any database on [database connection] D
7050 ** to automatically [checkpoint]
7051 ** after committing a transaction if there are N or
7052 ** more frames in the [write-ahead log] file. ^Passing zero or
7053 ** a negative value as the nFrame parameter disables automatic
7054 ** checkpoints entirely.
7056 ** ^The callback registered by this function replaces any existing callback
7057 ** registered using [sqlite3_wal_hook()]. ^Likewise, registering a callback
7058 ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
7059 ** configured by this function.
7061 ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
7062 ** from SQL.
7064 ** ^Every new [database connection] defaults to having the auto-checkpoint
7065 ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
7066 ** pages. The use of this interface
7067 ** is only necessary if the default setting is found to be suboptimal
7068 ** for a particular application.
7070 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
7073 ** CAPI3REF: Checkpoint a database
7075 ** ^The [sqlite3_wal_checkpoint(D,X)] interface causes database named X
7076 ** on [database connection] D to be [checkpointed]. ^If X is NULL or an
7077 ** empty string, then a checkpoint is run on all databases of
7078 ** connection D. ^If the database connection D is not in
7079 ** [WAL | write-ahead log mode] then this interface is a harmless no-op.
7081 ** ^The [wal_checkpoint pragma] can be used to invoke this interface
7082 ** from SQL. ^The [sqlite3_wal_autocheckpoint()] interface and the
7083 ** [wal_autocheckpoint pragma] can be used to cause this interface to be
7084 ** run whenever the WAL reaches a certain size threshold.
7086 ** See also: [sqlite3_wal_checkpoint_v2()]
7088 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
7091 ** CAPI3REF: Checkpoint a database
7093 ** Run a checkpoint operation on WAL database zDb attached to database
7094 ** handle db. The specific operation is determined by the value of the
7095 ** eMode parameter:
7097 ** <dl>
7098 ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
7099 ** Checkpoint as many frames as possible without waiting for any database
7100 ** readers or writers to finish. Sync the db file if all frames in the log
7101 ** are checkpointed. This mode is the same as calling
7102 ** sqlite3_wal_checkpoint(). The busy-handler callback is never invoked.
7104 ** <dt>SQLITE_CHECKPOINT_FULL<dd>
7105 ** This mode blocks (calls the busy-handler callback) until there is no
7106 ** database writer and all readers are reading from the most recent database
7107 ** snapshot. It then checkpoints all frames in the log file and syncs the
7108 ** database file. This call blocks database writers while it is running,
7109 ** but not database readers.
7111 ** <dt>SQLITE_CHECKPOINT_RESTART<dd>
7112 ** This mode works the same way as SQLITE_CHECKPOINT_FULL, except after
7113 ** checkpointing the log file it blocks (calls the busy-handler callback)
7114 ** until all readers are reading from the database file only. This ensures
7115 ** that the next client to write to the database file restarts the log file
7116 ** from the beginning. This call blocks database writers while it is running,
7117 ** but not database readers.
7118 ** </dl>
7120 ** If pnLog is not NULL, then *pnLog is set to the total number of frames in
7121 ** the log file before returning. If pnCkpt is not NULL, then *pnCkpt is set to
7122 ** the total number of checkpointed frames (including any that were already
7123 ** checkpointed when this function is called). *pnLog and *pnCkpt may be
7124 ** populated even if sqlite3_wal_checkpoint_v2() returns other than SQLITE_OK.
7125 ** If no values are available because of an error, they are both set to -1
7126 ** before returning to communicate this to the caller.
7128 ** All calls obtain an exclusive "checkpoint" lock on the database file. If
7129 ** any other process is running a checkpoint operation at the same time, the
7130 ** lock cannot be obtained and SQLITE_BUSY is returned. Even if there is a
7131 ** busy-handler configured, it will not be invoked in this case.
7133 ** The SQLITE_CHECKPOINT_FULL and RESTART modes also obtain the exclusive
7134 ** "writer" lock on the database file. If the writer lock cannot be obtained
7135 ** immediately, and a busy-handler is configured, it is invoked and the writer
7136 ** lock retried until either the busy-handler returns 0 or the lock is
7137 ** successfully obtained. The busy-handler is also invoked while waiting for
7138 ** database readers as described above. If the busy-handler returns 0 before
7139 ** the writer lock is obtained or while waiting for database readers, the
7140 ** checkpoint operation proceeds from that point in the same way as
7141 ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
7142 ** without blocking any further. SQLITE_BUSY is returned in this case.
7144 ** If parameter zDb is NULL or points to a zero length string, then the
7145 ** specified operation is attempted on all WAL databases. In this case the
7146 ** values written to output parameters *pnLog and *pnCkpt are undefined. If
7147 ** an SQLITE_BUSY error is encountered when processing one or more of the
7148 ** attached WAL databases, the operation is still attempted on any remaining
7149 ** attached databases and SQLITE_BUSY is returned to the caller. If any other
7150 ** error occurs while processing an attached database, processing is abandoned
7151 ** and the error code returned to the caller immediately. If no error
7152 ** (SQLITE_BUSY or otherwise) is encountered while processing the attached
7153 ** databases, SQLITE_OK is returned.
7155 ** If database zDb is the name of an attached database that is not in WAL
7156 ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. If
7157 ** zDb is not NULL (or a zero length string) and is not the name of any
7158 ** attached database, SQLITE_ERROR is returned to the caller.
7160 SQLITE_API int sqlite3_wal_checkpoint_v2(
7161 sqlite3 *db, /* Database handle */
7162 const char *zDb, /* Name of attached database (or NULL) */
7163 int eMode, /* SQLITE_CHECKPOINT_* value */
7164 int *pnLog, /* OUT: Size of WAL log in frames */
7165 int *pnCkpt /* OUT: Total number of frames checkpointed */
7169 ** CAPI3REF: Checkpoint operation parameters
7171 ** These constants can be used as the 3rd parameter to
7172 ** [sqlite3_wal_checkpoint_v2()]. See the [sqlite3_wal_checkpoint_v2()]
7173 ** documentation for additional information about the meaning and use of
7174 ** each of these values.
7176 #define SQLITE_CHECKPOINT_PASSIVE 0
7177 #define SQLITE_CHECKPOINT_FULL 1
7178 #define SQLITE_CHECKPOINT_RESTART 2
7181 ** CAPI3REF: Virtual Table Interface Configuration
7183 ** This function may be called by either the [xConnect] or [xCreate] method
7184 ** of a [virtual table] implementation to configure
7185 ** various facets of the virtual table interface.
7187 ** If this interface is invoked outside the context of an xConnect or
7188 ** xCreate virtual table method then the behavior is undefined.
7190 ** At present, there is only one option that may be configured using
7191 ** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].) Further options
7192 ** may be added in the future.
7194 SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);
7197 ** CAPI3REF: Virtual Table Configuration Options
7199 ** These macros define the various options to the
7200 ** [sqlite3_vtab_config()] interface that [virtual table] implementations
7201 ** can use to customize and optimize their behavior.
7203 ** <dl>
7204 ** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
7205 ** <dd>Calls of the form
7206 ** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
7207 ** where X is an integer. If X is zero, then the [virtual table] whose
7208 ** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
7209 ** support constraints. In this configuration (which is the default) if
7210 ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
7211 ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
7212 ** specified as part of the users SQL statement, regardless of the actual
7213 ** ON CONFLICT mode specified.
7215 ** If X is non-zero, then the virtual table implementation guarantees
7216 ** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
7217 ** any modifications to internal or persistent data structures have been made.
7218 ** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite
7219 ** is able to roll back a statement or database transaction, and abandon
7220 ** or continue processing the current SQL statement as appropriate.
7221 ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
7222 ** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
7223 ** had been ABORT.
7225 ** Virtual table implementations that are required to handle OR REPLACE
7226 ** must do so within the [xUpdate] method. If a call to the
7227 ** [sqlite3_vtab_on_conflict()] function indicates that the current ON
7228 ** CONFLICT policy is REPLACE, the virtual table implementation should
7229 ** silently replace the appropriate rows within the xUpdate callback and
7230 ** return SQLITE_OK. Or, if this is not possible, it may return
7231 ** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT
7232 ** constraint handling.
7233 ** </dl>
7235 #define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
7238 ** CAPI3REF: Determine The Virtual Table Conflict Policy
7240 ** This function may only be called from within a call to the [xUpdate] method
7241 ** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
7242 ** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
7243 ** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
7244 ** of the SQL statement that triggered the call to the [xUpdate] method of the
7245 ** [virtual table].
7247 SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);
7250 ** CAPI3REF: Conflict resolution modes
7252 ** These constants are returned by [sqlite3_vtab_on_conflict()] to
7253 ** inform a [virtual table] implementation what the [ON CONFLICT] mode
7254 ** is for the SQL statement being evaluated.
7256 ** Note that the [SQLITE_IGNORE] constant is also used as a potential
7257 ** return value from the [sqlite3_set_authorizer()] callback and that
7258 ** [SQLITE_ABORT] is also a [result code].
7260 #define SQLITE_ROLLBACK 1
7261 /* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
7262 #define SQLITE_FAIL 3
7263 /* #define SQLITE_ABORT 4 // Also an error code */
7264 #define SQLITE_REPLACE 5
7269 ** Undo the hack that converts floating point types to integer for
7270 ** builds on processors without floating point support.
7272 #ifdef SQLITE_OMIT_FLOATING_POINT
7273 # undef double
7274 #endif
7276 #if 0
7277 } /* End of the 'extern "C"' block */
7278 #endif
7279 #endif
7282 ** 2010 August 30
7284 ** The author disclaims copyright to this source code. In place of
7285 ** a legal notice, here is a blessing:
7287 ** May you do good and not evil.
7288 ** May you find forgiveness for yourself and forgive others.
7289 ** May you share freely, never taking more than you give.
7291 *************************************************************************
7294 #ifndef _SQLITE3RTREE_H_
7295 #define _SQLITE3RTREE_H_
7298 #if 0
7299 extern "C" {
7300 #endif
7302 typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
7305 ** Register a geometry callback named zGeom that can be used as part of an
7306 ** R-Tree geometry query as follows:
7308 ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
7310 SQLITE_API int sqlite3_rtree_geometry_callback(
7311 sqlite3 *db,
7312 const char *zGeom,
7313 int (*xGeom)(sqlite3_rtree_geometry *, int nCoord, double *aCoord, int *pRes),
7314 void *pContext
7319 ** A pointer to a structure of the following type is passed as the first
7320 ** argument to callbacks registered using rtree_geometry_callback().
7322 struct sqlite3_rtree_geometry {
7323 void *pContext; /* Copy of pContext passed to s_r_g_c() */
7324 int nParam; /* Size of array aParam[] */
7325 double *aParam; /* Parameters passed to SQL geom function */
7326 void *pUser; /* Callback implementation user data */
7327 void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */
7331 #if 0
7332 } /* end of the 'extern "C"' block */
7333 #endif
7335 #endif /* ifndef _SQLITE3RTREE_H_ */
7338 /************** End of sqlite3.h *********************************************/
7339 /************** Continuing where we left off in sqliteInt.h ******************/
7340 /************** Include hash.h in the middle of sqliteInt.h ******************/
7341 /************** Begin file hash.h ********************************************/
7343 ** 2001 September 22
7345 ** The author disclaims copyright to this source code. In place of
7346 ** a legal notice, here is a blessing:
7348 ** May you do good and not evil.
7349 ** May you find forgiveness for yourself and forgive others.
7350 ** May you share freely, never taking more than you give.
7352 *************************************************************************
7353 ** This is the header file for the generic hash-table implemenation
7354 ** used in SQLite.
7356 #ifndef _SQLITE_HASH_H_
7357 #define _SQLITE_HASH_H_
7359 /* Forward declarations of structures. */
7360 typedef struct Hash Hash;
7361 typedef struct HashElem HashElem;
7363 /* A complete hash table is an instance of the following structure.
7364 ** The internals of this structure are intended to be opaque -- client
7365 ** code should not attempt to access or modify the fields of this structure
7366 ** directly. Change this structure only by using the routines below.
7367 ** However, some of the "procedures" and "functions" for modifying and
7368 ** accessing this structure are really macros, so we can't really make
7369 ** this structure opaque.
7371 ** All elements of the hash table are on a single doubly-linked list.
7372 ** Hash.first points to the head of this list.
7374 ** There are Hash.htsize buckets. Each bucket points to a spot in
7375 ** the global doubly-linked list. The contents of the bucket are the
7376 ** element pointed to plus the next _ht.count-1 elements in the list.
7378 ** Hash.htsize and Hash.ht may be zero. In that case lookup is done
7379 ** by a linear search of the global list. For small tables, the
7380 ** Hash.ht table is never allocated because if there are few elements
7381 ** in the table, it is faster to do a linear search than to manage
7382 ** the hash table.
7384 struct Hash {
7385 unsigned int htsize; /* Number of buckets in the hash table */
7386 unsigned int count; /* Number of entries in this table */
7387 HashElem *first; /* The first element of the array */
7388 struct _ht { /* the hash table */
7389 int count; /* Number of entries with this hash */
7390 HashElem *chain; /* Pointer to first entry with this hash */
7391 } *ht;
7394 /* Each element in the hash table is an instance of the following
7395 ** structure. All elements are stored on a single doubly-linked list.
7397 ** Again, this structure is intended to be opaque, but it can't really
7398 ** be opaque because it is used by macros.
7400 struct HashElem {
7401 HashElem *next, *prev; /* Next and previous elements in the table */
7402 void *data; /* Data associated with this element */
7403 const char *pKey; int nKey; /* Key associated with this element */
7407 ** Access routines. To delete, insert a NULL pointer.
7409 SQLITE_PRIVATE void sqlite3HashInit(Hash*);
7410 SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData);
7411 SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey, int nKey);
7412 SQLITE_PRIVATE void sqlite3HashClear(Hash*);
7415 ** Macros for looping over all elements of a hash table. The idiom is
7416 ** like this:
7418 ** Hash h;
7419 ** HashElem *p;
7420 ** ...
7421 ** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
7422 ** SomeStructure *pData = sqliteHashData(p);
7423 ** // do something with pData
7424 ** }
7426 #define sqliteHashFirst(H) ((H)->first)
7427 #define sqliteHashNext(E) ((E)->next)
7428 #define sqliteHashData(E) ((E)->data)
7429 /* #define sqliteHashKey(E) ((E)->pKey) // NOT USED */
7430 /* #define sqliteHashKeysize(E) ((E)->nKey) // NOT USED */
7433 ** Number of entries in a hash table
7435 /* #define sqliteHashCount(H) ((H)->count) // NOT USED */
7437 #endif /* _SQLITE_HASH_H_ */
7439 /************** End of hash.h ************************************************/
7440 /************** Continuing where we left off in sqliteInt.h ******************/
7441 /************** Include parse.h in the middle of sqliteInt.h *****************/
7442 /************** Begin file parse.h *******************************************/
7443 #define TK_SEMI 1
7444 #define TK_EXPLAIN 2
7445 #define TK_QUERY 3
7446 #define TK_PLAN 4
7447 #define TK_BEGIN 5
7448 #define TK_TRANSACTION 6
7449 #define TK_DEFERRED 7
7450 #define TK_IMMEDIATE 8
7451 #define TK_EXCLUSIVE 9
7452 #define TK_COMMIT 10
7453 #define TK_END 11
7454 #define TK_ROLLBACK 12
7455 #define TK_SAVEPOINT 13
7456 #define TK_RELEASE 14
7457 #define TK_TO 15
7458 #define TK_TABLE 16
7459 #define TK_CREATE 17
7460 #define TK_IF 18
7461 #define TK_NOT 19
7462 #define TK_EXISTS 20
7463 #define TK_TEMP 21
7464 #define TK_LP 22
7465 #define TK_RP 23
7466 #define TK_AS 24
7467 #define TK_COMMA 25
7468 #define TK_ID 26
7469 #define TK_INDEXED 27
7470 #define TK_ABORT 28
7471 #define TK_ACTION 29
7472 #define TK_AFTER 30
7473 #define TK_ANALYZE 31
7474 #define TK_ASC 32
7475 #define TK_ATTACH 33
7476 #define TK_BEFORE 34
7477 #define TK_BY 35
7478 #define TK_CASCADE 36
7479 #define TK_CAST 37
7480 #define TK_COLUMNKW 38
7481 #define TK_CONFLICT 39
7482 #define TK_DATABASE 40
7483 #define TK_DESC 41
7484 #define TK_DETACH 42
7485 #define TK_EACH 43
7486 #define TK_FAIL 44
7487 #define TK_FOR 45
7488 #define TK_IGNORE 46
7489 #define TK_INITIALLY 47
7490 #define TK_INSTEAD 48
7491 #define TK_LIKE_KW 49
7492 #define TK_MATCH 50
7493 #define TK_NO 51
7494 #define TK_KEY 52
7495 #define TK_OF 53
7496 #define TK_OFFSET 54
7497 #define TK_PRAGMA 55
7498 #define TK_RAISE 56
7499 #define TK_REPLACE 57
7500 #define TK_RESTRICT 58
7501 #define TK_ROW 59
7502 #define TK_TRIGGER 60
7503 #define TK_VACUUM 61
7504 #define TK_VIEW 62
7505 #define TK_VIRTUAL 63
7506 #define TK_REINDEX 64
7507 #define TK_RENAME 65
7508 #define TK_CTIME_KW 66
7509 #define TK_ANY 67
7510 #define TK_OR 68
7511 #define TK_AND 69
7512 #define TK_IS 70
7513 #define TK_BETWEEN 71
7514 #define TK_IN 72
7515 #define TK_ISNULL 73
7516 #define TK_NOTNULL 74
7517 #define TK_NE 75
7518 #define TK_EQ 76
7519 #define TK_GT 77
7520 #define TK_LE 78
7521 #define TK_LT 79
7522 #define TK_GE 80
7523 #define TK_ESCAPE 81
7524 #define TK_BITAND 82
7525 #define TK_BITOR 83
7526 #define TK_LSHIFT 84
7527 #define TK_RSHIFT 85
7528 #define TK_PLUS 86
7529 #define TK_MINUS 87
7530 #define TK_STAR 88
7531 #define TK_SLASH 89
7532 #define TK_REM 90
7533 #define TK_CONCAT 91
7534 #define TK_COLLATE 92
7535 #define TK_BITNOT 93
7536 #define TK_STRING 94
7537 #define TK_JOIN_KW 95
7538 #define TK_CONSTRAINT 96
7539 #define TK_DEFAULT 97
7540 #define TK_NULL 98
7541 #define TK_PRIMARY 99
7542 #define TK_UNIQUE 100
7543 #define TK_CHECK 101
7544 #define TK_REFERENCES 102
7545 #define TK_AUTOINCR 103
7546 #define TK_ON 104
7547 #define TK_INSERT 105
7548 #define TK_DELETE 106
7549 #define TK_UPDATE 107
7550 #define TK_SET 108
7551 #define TK_DEFERRABLE 109
7552 #define TK_FOREIGN 110
7553 #define TK_DROP 111
7554 #define TK_UNION 112
7555 #define TK_ALL 113
7556 #define TK_EXCEPT 114
7557 #define TK_INTERSECT 115
7558 #define TK_SELECT 116
7559 #define TK_DISTINCT 117
7560 #define TK_DOT 118
7561 #define TK_FROM 119
7562 #define TK_JOIN 120
7563 #define TK_USING 121
7564 #define TK_ORDER 122
7565 #define TK_GROUP 123
7566 #define TK_HAVING 124
7567 #define TK_LIMIT 125
7568 #define TK_WHERE 126
7569 #define TK_INTO 127
7570 #define TK_VALUES 128
7571 #define TK_INTEGER 129
7572 #define TK_FLOAT 130
7573 #define TK_BLOB 131
7574 #define TK_REGISTER 132
7575 #define TK_VARIABLE 133
7576 #define TK_CASE 134
7577 #define TK_WHEN 135
7578 #define TK_THEN 136
7579 #define TK_ELSE 137
7580 #define TK_INDEX 138
7581 #define TK_ALTER 139
7582 #define TK_ADD 140
7583 #define TK_TO_TEXT 141
7584 #define TK_TO_BLOB 142
7585 #define TK_TO_NUMERIC 143
7586 #define TK_TO_INT 144
7587 #define TK_TO_REAL 145
7588 #define TK_ISNOT 146
7589 #define TK_END_OF_FILE 147
7590 #define TK_ILLEGAL 148
7591 #define TK_SPACE 149
7592 #define TK_UNCLOSED_STRING 150
7593 #define TK_FUNCTION 151
7594 #define TK_COLUMN 152
7595 #define TK_AGG_FUNCTION 153
7596 #define TK_AGG_COLUMN 154
7597 #define TK_CONST_FUNC 155
7598 #define TK_UMINUS 156
7599 #define TK_UPLUS 157
7601 /************** End of parse.h ***********************************************/
7602 /************** Continuing where we left off in sqliteInt.h ******************/
7603 #include <stdio.h>
7604 #include <stdlib.h>
7605 #include <string.h>
7606 #include <assert.h>
7607 #include <stddef.h>
7610 ** If compiling for a processor that lacks floating point support,
7611 ** substitute integer for floating-point
7613 #ifdef SQLITE_OMIT_FLOATING_POINT
7614 # define double sqlite_int64
7615 # define float sqlite_int64
7616 # define LONGDOUBLE_TYPE sqlite_int64
7617 # ifndef SQLITE_BIG_DBL
7618 # define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
7619 # endif
7620 # define SQLITE_OMIT_DATETIME_FUNCS 1
7621 # define SQLITE_OMIT_TRACE 1
7622 # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
7623 # undef SQLITE_HAVE_ISNAN
7624 #endif
7625 #ifndef SQLITE_BIG_DBL
7626 # define SQLITE_BIG_DBL (1e99)
7627 #endif
7630 ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
7631 ** afterward. Having this macro allows us to cause the C compiler
7632 ** to omit code used by TEMP tables without messy #ifndef statements.
7634 #ifdef SQLITE_OMIT_TEMPDB
7635 #define OMIT_TEMPDB 1
7636 #else
7637 #define OMIT_TEMPDB 0
7638 #endif
7641 ** The "file format" number is an integer that is incremented whenever
7642 ** the VDBE-level file format changes. The following macros define the
7643 ** the default file format for new databases and the maximum file format
7644 ** that the library can read.
7646 #define SQLITE_MAX_FILE_FORMAT 4
7647 #ifndef SQLITE_DEFAULT_FILE_FORMAT
7648 # define SQLITE_DEFAULT_FILE_FORMAT 1
7649 #endif
7652 ** Determine whether triggers are recursive by default. This can be
7653 ** changed at run-time using a pragma.
7655 #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
7656 # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
7657 #endif
7660 ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
7661 ** on the command-line
7663 #ifndef SQLITE_TEMP_STORE
7664 # define SQLITE_TEMP_STORE 1
7665 #endif
7668 ** GCC does not define the offsetof() macro so we'll have to do it
7669 ** ourselves.
7671 #ifndef offsetof
7672 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
7673 #endif
7676 ** Check to see if this machine uses EBCDIC. (Yes, believe it or
7677 ** not, there are still machines out there that use EBCDIC.)
7679 #if 'A' == '\301'
7680 # define SQLITE_EBCDIC 1
7681 #else
7682 # define SQLITE_ASCII 1
7683 #endif
7686 ** Integers of known sizes. These typedefs might change for architectures
7687 ** where the sizes very. Preprocessor macros are available so that the
7688 ** types can be conveniently redefined at compile-type. Like this:
7690 ** cc '-DUINTPTR_TYPE=long long int' ...
7692 #ifndef UINT32_TYPE
7693 # ifdef HAVE_UINT32_T
7694 # define UINT32_TYPE uint32_t
7695 # else
7696 # define UINT32_TYPE unsigned int
7697 # endif
7698 #endif
7699 #ifndef UINT16_TYPE
7700 # ifdef HAVE_UINT16_T
7701 # define UINT16_TYPE uint16_t
7702 # else
7703 # define UINT16_TYPE unsigned short int
7704 # endif
7705 #endif
7706 #ifndef INT16_TYPE
7707 # ifdef HAVE_INT16_T
7708 # define INT16_TYPE int16_t
7709 # else
7710 # define INT16_TYPE short int
7711 # endif
7712 #endif
7713 #ifndef UINT8_TYPE
7714 # ifdef HAVE_UINT8_T
7715 # define UINT8_TYPE uint8_t
7716 # else
7717 # define UINT8_TYPE unsigned char
7718 # endif
7719 #endif
7720 #ifndef INT8_TYPE
7721 # ifdef HAVE_INT8_T
7722 # define INT8_TYPE int8_t
7723 # else
7724 # define INT8_TYPE signed char
7725 # endif
7726 #endif
7727 #ifndef LONGDOUBLE_TYPE
7728 # define LONGDOUBLE_TYPE long double
7729 #endif
7730 typedef sqlite_int64 i64; /* 8-byte signed integer */
7731 typedef sqlite_uint64 u64; /* 8-byte unsigned integer */
7732 typedef UINT32_TYPE u32; /* 4-byte unsigned integer */
7733 typedef UINT16_TYPE u16; /* 2-byte unsigned integer */
7734 typedef INT16_TYPE i16; /* 2-byte signed integer */
7735 typedef UINT8_TYPE u8; /* 1-byte unsigned integer */
7736 typedef INT8_TYPE i8; /* 1-byte signed integer */
7739 ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
7740 ** that can be stored in a u32 without loss of data. The value
7741 ** is 0x00000000ffffffff. But because of quirks of some compilers, we
7742 ** have to specify the value in the less intuitive manner shown:
7744 #define SQLITE_MAX_U32 ((((u64)1)<<32)-1)
7747 ** The datatype used to store estimates of the number of rows in a
7748 ** table or index. This is an unsigned integer type. For 99.9% of
7749 ** the world, a 32-bit integer is sufficient. But a 64-bit integer
7750 ** can be used at compile-time if desired.
7752 #ifdef SQLITE_64BIT_STATS
7753 typedef u64 tRowcnt; /* 64-bit only if requested at compile-time */
7754 #else
7755 typedef u32 tRowcnt; /* 32-bit is the default */
7756 #endif
7759 ** Macros to determine whether the machine is big or little endian,
7760 ** evaluated at runtime.
7762 #ifdef SQLITE_AMALGAMATION
7763 SQLITE_PRIVATE const int sqlite3one = 1;
7764 #else
7765 SQLITE_PRIVATE const int sqlite3one;
7766 #endif
7767 #if defined(i386) || defined(__i386__) || defined(_M_IX86)\
7768 || defined(__x86_64) || defined(__x86_64__)
7769 # define SQLITE_BIGENDIAN 0
7770 # define SQLITE_LITTLEENDIAN 1
7771 # define SQLITE_UTF16NATIVE SQLITE_UTF16LE
7772 #else
7773 # define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0)
7774 # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
7775 # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
7776 #endif
7779 ** Constants for the largest and smallest possible 64-bit signed integers.
7780 ** These macros are designed to work correctly on both 32-bit and 64-bit
7781 ** compilers.
7783 #define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
7784 #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
7787 ** Round up a number to the next larger multiple of 8. This is used
7788 ** to force 8-byte alignment on 64-bit architectures.
7790 #define ROUND8(x) (((x)+7)&~7)
7793 ** Round down to the nearest multiple of 8
7795 #define ROUNDDOWN8(x) ((x)&~7)
7798 ** Assert that the pointer X is aligned to an 8-byte boundary. This
7799 ** macro is used only within assert() to verify that the code gets
7800 ** all alignment restrictions correct.
7802 ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
7803 ** underlying malloc() implemention might return us 4-byte aligned
7804 ** pointers. In that case, only verify 4-byte alignment.
7806 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
7807 # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&3)==0)
7808 #else
7809 # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&7)==0)
7810 #endif
7814 ** An instance of the following structure is used to store the busy-handler
7815 ** callback for a given sqlite handle.
7817 ** The sqlite.busyHandler member of the sqlite struct contains the busy
7818 ** callback for the database handle. Each pager opened via the sqlite
7819 ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
7820 ** callback is currently invoked only from within pager.c.
7822 typedef struct BusyHandler BusyHandler;
7823 struct BusyHandler {
7824 int (*xFunc)(void *,int); /* The busy callback */
7825 void *pArg; /* First arg to busy callback */
7826 int nBusy; /* Incremented with each busy call */
7830 ** Name of the master database table. The master database table
7831 ** is a special table that holds the names and attributes of all
7832 ** user tables and indices.
7834 #define MASTER_NAME "sqlite_master"
7835 #define TEMP_MASTER_NAME "sqlite_temp_master"
7838 ** The root-page of the master database table.
7840 #define MASTER_ROOT 1
7843 ** The name of the schema table.
7845 #define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
7848 ** A convenience macro that returns the number of elements in
7849 ** an array.
7851 #define ArraySize(X) ((int)(sizeof(X)/sizeof(X[0])))
7854 ** The following value as a destructor means to use sqlite3DbFree().
7855 ** This is an internal extension to SQLITE_STATIC and SQLITE_TRANSIENT.
7857 #define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3DbFree)
7860 ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
7861 ** not support Writable Static Data (WSD) such as global and static variables.
7862 ** All variables must either be on the stack or dynamically allocated from
7863 ** the heap. When WSD is unsupported, the variable declarations scattered
7864 ** throughout the SQLite code must become constants instead. The SQLITE_WSD
7865 ** macro is used for this purpose. And instead of referencing the variable
7866 ** directly, we use its constant as a key to lookup the run-time allocated
7867 ** buffer that holds real variable. The constant is also the initializer
7868 ** for the run-time allocated buffer.
7870 ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
7871 ** macros become no-ops and have zero performance impact.
7873 #ifdef SQLITE_OMIT_WSD
7874 #define SQLITE_WSD const
7875 #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
7876 #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
7877 SQLITE_API int sqlite3_wsd_init(int N, int J);
7878 SQLITE_API void *sqlite3_wsd_find(void *K, int L);
7879 #else
7880 #define SQLITE_WSD
7881 #define GLOBAL(t,v) v
7882 #define sqlite3GlobalConfig sqlite3Config
7883 #endif
7886 ** The following macros are used to suppress compiler warnings and to
7887 ** make it clear to human readers when a function parameter is deliberately
7888 ** left unused within the body of a function. This usually happens when
7889 ** a function is called via a function pointer. For example the
7890 ** implementation of an SQL aggregate step callback may not use the
7891 ** parameter indicating the number of arguments passed to the aggregate,
7892 ** if it knows that this is enforced elsewhere.
7894 ** When a function parameter is not used at all within the body of a function,
7895 ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
7896 ** However, these macros may also be used to suppress warnings related to
7897 ** parameters that may or may not be used depending on compilation options.
7898 ** For example those parameters only used in assert() statements. In these
7899 ** cases the parameters are named as per the usual conventions.
7901 #define UNUSED_PARAMETER(x) (void)(x)
7902 #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
7905 ** Forward references to structures
7907 typedef struct AggInfo AggInfo;
7908 typedef struct AuthContext AuthContext;
7909 typedef struct AutoincInfo AutoincInfo;
7910 typedef struct Bitvec Bitvec;
7911 typedef struct CollSeq CollSeq;
7912 typedef struct Column Column;
7913 typedef struct Db Db;
7914 typedef struct Schema Schema;
7915 typedef struct Expr Expr;
7916 typedef struct ExprList ExprList;
7917 typedef struct ExprSpan ExprSpan;
7918 typedef struct FKey FKey;
7919 typedef struct FuncDestructor FuncDestructor;
7920 typedef struct FuncDef FuncDef;
7921 typedef struct FuncDefHash FuncDefHash;
7922 typedef struct IdList IdList;
7923 typedef struct Index Index;
7924 typedef struct IndexSample IndexSample;
7925 typedef struct KeyClass KeyClass;
7926 typedef struct KeyInfo KeyInfo;
7927 typedef struct Lookaside Lookaside;
7928 typedef struct LookasideSlot LookasideSlot;
7929 typedef struct Module Module;
7930 typedef struct NameContext NameContext;
7931 typedef struct Parse Parse;
7932 typedef struct RowSet RowSet;
7933 typedef struct Savepoint Savepoint;
7934 typedef struct Select Select;
7935 typedef struct SrcList SrcList;
7936 typedef struct StrAccum StrAccum;
7937 typedef struct Table Table;
7938 typedef struct TableLock TableLock;
7939 typedef struct Token Token;
7940 typedef struct Trigger Trigger;
7941 typedef struct TriggerPrg TriggerPrg;
7942 typedef struct TriggerStep TriggerStep;
7943 typedef struct UnpackedRecord UnpackedRecord;
7944 typedef struct VTable VTable;
7945 typedef struct VtabCtx VtabCtx;
7946 typedef struct Walker Walker;
7947 typedef struct WherePlan WherePlan;
7948 typedef struct WhereInfo WhereInfo;
7949 typedef struct WhereLevel WhereLevel;
7952 ** Defer sourcing vdbe.h and btree.h until after the "u8" and
7953 ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
7954 ** pointer types (i.e. FuncDef) defined above.
7956 /************** Include btree.h in the middle of sqliteInt.h *****************/
7957 /************** Begin file btree.h *******************************************/
7959 ** 2001 September 15
7961 ** The author disclaims copyright to this source code. In place of
7962 ** a legal notice, here is a blessing:
7964 ** May you do good and not evil.
7965 ** May you find forgiveness for yourself and forgive others.
7966 ** May you share freely, never taking more than you give.
7968 *************************************************************************
7969 ** This header file defines the interface that the sqlite B-Tree file
7970 ** subsystem. See comments in the source code for a detailed description
7971 ** of what each interface routine does.
7973 #ifndef _BTREE_H_
7974 #define _BTREE_H_
7976 /* TODO: This definition is just included so other modules compile. It
7977 ** needs to be revisited.
7979 #define SQLITE_N_BTREE_META 10
7982 ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
7983 ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
7985 #ifndef SQLITE_DEFAULT_AUTOVACUUM
7986 #define SQLITE_DEFAULT_AUTOVACUUM 0
7987 #endif
7989 #define BTREE_AUTOVACUUM_NONE 0 /* Do not do auto-vacuum */
7990 #define BTREE_AUTOVACUUM_FULL 1 /* Do full auto-vacuum */
7991 #define BTREE_AUTOVACUUM_INCR 2 /* Incremental vacuum */
7994 ** Forward declarations of structure
7996 typedef struct Btree Btree;
7997 typedef struct BtCursor BtCursor;
7998 typedef struct BtShared BtShared;
8001 SQLITE_PRIVATE int sqlite3BtreeOpen(
8002 sqlite3_vfs *pVfs, /* VFS to use with this b-tree */
8003 const char *zFilename, /* Name of database file to open */
8004 sqlite3 *db, /* Associated database connection */
8005 Btree **ppBtree, /* Return open Btree* here */
8006 int flags, /* Flags */
8007 int vfsFlags /* Flags passed through to VFS open */
8010 /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
8011 ** following values.
8013 ** NOTE: These values must match the corresponding PAGER_ values in
8014 ** pager.h.
8016 #define BTREE_OMIT_JOURNAL 1 /* Do not create or use a rollback journal */
8017 #define BTREE_NO_READLOCK 2 /* Omit readlocks on readonly files */
8018 #define BTREE_MEMORY 4 /* This is an in-memory DB */
8019 #define BTREE_SINGLE 8 /* The file contains at most 1 b-tree */
8020 #define BTREE_UNORDERED 16 /* Use of a hash implementation is OK */
8022 SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
8023 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
8024 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int,int);
8025 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
8026 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
8027 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
8028 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
8029 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
8030 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
8031 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
8032 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
8033 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
8034 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
8035 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
8036 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
8037 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
8038 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*);
8039 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
8040 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
8041 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
8042 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
8043 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
8044 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
8045 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
8046 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
8047 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
8049 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
8050 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
8051 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
8053 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
8055 /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
8056 ** of the flags shown below.
8058 ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
8059 ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
8060 ** is stored in the leaves. (BTREE_INTKEY is used for SQL tables.) With
8061 ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
8062 ** anywhere - the key is the content. (BTREE_BLOBKEY is used for SQL
8063 ** indices.)
8065 #define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */
8066 #define BTREE_BLOBKEY 2 /* Table has keys only - no data */
8068 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
8069 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
8070 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
8072 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
8073 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
8076 ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
8077 ** should be one of the following values. The integer values are assigned
8078 ** to constants so that the offset of the corresponding field in an
8079 ** SQLite database header may be found using the following formula:
8081 ** offset = 36 + (idx * 4)
8083 ** For example, the free-page-count field is located at byte offset 36 of
8084 ** the database file header. The incr-vacuum-flag field is located at
8085 ** byte offset 64 (== 36+4*7).
8087 #define BTREE_FREE_PAGE_COUNT 0
8088 #define BTREE_SCHEMA_VERSION 1
8089 #define BTREE_FILE_FORMAT 2
8090 #define BTREE_DEFAULT_CACHE_SIZE 3
8091 #define BTREE_LARGEST_ROOT_PAGE 4
8092 #define BTREE_TEXT_ENCODING 5
8093 #define BTREE_USER_VERSION 6
8094 #define BTREE_INCR_VACUUM 7
8096 SQLITE_PRIVATE int sqlite3BtreeCursor(
8097 Btree*, /* BTree containing table to open */
8098 int iTable, /* Index of root page */
8099 int wrFlag, /* 1 for writing. 0 for read-only */
8100 struct KeyInfo*, /* First argument to compare function */
8101 BtCursor *pCursor /* Space to write cursor structure */
8103 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
8104 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
8106 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
8107 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
8108 BtCursor*,
8109 UnpackedRecord *pUnKey,
8110 i64 intKey,
8111 int bias,
8112 int *pRes
8114 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
8115 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
8116 SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
8117 const void *pData, int nData,
8118 int nZero, int bias, int seekResult);
8119 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
8120 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
8121 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
8122 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
8123 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
8124 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
8125 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
8126 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
8127 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
8128 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
8129 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
8130 SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64);
8131 SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor*);
8133 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
8134 SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
8136 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
8137 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);
8138 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
8140 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
8142 #ifndef NDEBUG
8143 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
8144 #endif
8146 #ifndef SQLITE_OMIT_BTREECOUNT
8147 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
8148 #endif
8150 #ifdef SQLITE_TEST
8151 SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
8152 SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
8153 #endif
8155 #ifndef SQLITE_OMIT_WAL
8156 SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
8157 #endif
8160 ** If we are not using shared cache, then there is no need to
8161 ** use mutexes to access the BtShared structures. So make the
8162 ** Enter and Leave procedures no-ops.
8164 #ifndef SQLITE_OMIT_SHARED_CACHE
8165 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree*);
8166 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3*);
8167 #else
8168 # define sqlite3BtreeEnter(X)
8169 # define sqlite3BtreeEnterAll(X)
8170 #endif
8172 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
8173 SQLITE_PRIVATE int sqlite3BtreeSharable(Btree*);
8174 SQLITE_PRIVATE void sqlite3BtreeLeave(Btree*);
8175 SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor*);
8176 SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor*);
8177 SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3*);
8178 #ifndef NDEBUG
8179 /* These routines are used inside assert() statements only. */
8180 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree*);
8181 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3*);
8182 SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
8183 #endif
8184 #else
8186 # define sqlite3BtreeSharable(X) 0
8187 # define sqlite3BtreeLeave(X)
8188 # define sqlite3BtreeEnterCursor(X)
8189 # define sqlite3BtreeLeaveCursor(X)
8190 # define sqlite3BtreeLeaveAll(X)
8192 # define sqlite3BtreeHoldsMutex(X) 1
8193 # define sqlite3BtreeHoldsAllMutexes(X) 1
8194 # define sqlite3SchemaMutexHeld(X,Y,Z) 1
8195 #endif
8198 #endif /* _BTREE_H_ */
8200 /************** End of btree.h ***********************************************/
8201 /************** Continuing where we left off in sqliteInt.h ******************/
8202 /************** Include vdbe.h in the middle of sqliteInt.h ******************/
8203 /************** Begin file vdbe.h ********************************************/
8205 ** 2001 September 15
8207 ** The author disclaims copyright to this source code. In place of
8208 ** a legal notice, here is a blessing:
8210 ** May you do good and not evil.
8211 ** May you find forgiveness for yourself and forgive others.
8212 ** May you share freely, never taking more than you give.
8214 *************************************************************************
8215 ** Header file for the Virtual DataBase Engine (VDBE)
8217 ** This header defines the interface to the virtual database engine
8218 ** or VDBE. The VDBE implements an abstract machine that runs a
8219 ** simple program to access and modify the underlying database.
8221 #ifndef _SQLITE_VDBE_H_
8222 #define _SQLITE_VDBE_H_
8223 /* #include <stdio.h> */
8226 ** A single VDBE is an opaque structure named "Vdbe". Only routines
8227 ** in the source file sqliteVdbe.c are allowed to see the insides
8228 ** of this structure.
8230 typedef struct Vdbe Vdbe;
8233 ** The names of the following types declared in vdbeInt.h are required
8234 ** for the VdbeOp definition.
8236 typedef struct VdbeFunc VdbeFunc;
8237 typedef struct Mem Mem;
8238 typedef struct SubProgram SubProgram;
8241 ** A single instruction of the virtual machine has an opcode
8242 ** and as many as three operands. The instruction is recorded
8243 ** as an instance of the following structure:
8245 struct VdbeOp {
8246 u8 opcode; /* What operation to perform */
8247 signed char p4type; /* One of the P4_xxx constants for p4 */
8248 u8 opflags; /* Mask of the OPFLG_* flags in opcodes.h */
8249 u8 p5; /* Fifth parameter is an unsigned character */
8250 int p1; /* First operand */
8251 int p2; /* Second parameter (often the jump destination) */
8252 int p3; /* The third parameter */
8253 union { /* fourth parameter */
8254 int i; /* Integer value if p4type==P4_INT32 */
8255 void *p; /* Generic pointer */
8256 char *z; /* Pointer to data for string (char array) types */
8257 i64 *pI64; /* Used when p4type is P4_INT64 */
8258 double *pReal; /* Used when p4type is P4_REAL */
8259 FuncDef *pFunc; /* Used when p4type is P4_FUNCDEF */
8260 VdbeFunc *pVdbeFunc; /* Used when p4type is P4_VDBEFUNC */
8261 CollSeq *pColl; /* Used when p4type is P4_COLLSEQ */
8262 Mem *pMem; /* Used when p4type is P4_MEM */
8263 VTable *pVtab; /* Used when p4type is P4_VTAB */
8264 KeyInfo *pKeyInfo; /* Used when p4type is P4_KEYINFO */
8265 int *ai; /* Used when p4type is P4_INTARRAY */
8266 SubProgram *pProgram; /* Used when p4type is P4_SUBPROGRAM */
8267 int (*xAdvance)(BtCursor *, int *);
8268 } p4;
8269 #ifdef SQLITE_DEBUG
8270 char *zComment; /* Comment to improve readability */
8271 #endif
8272 #ifdef VDBE_PROFILE
8273 int cnt; /* Number of times this instruction was executed */
8274 u64 cycles; /* Total time spent executing this instruction */
8275 #endif
8277 typedef struct VdbeOp VdbeOp;
8281 ** A sub-routine used to implement a trigger program.
8283 struct SubProgram {
8284 VdbeOp *aOp; /* Array of opcodes for sub-program */
8285 int nOp; /* Elements in aOp[] */
8286 int nMem; /* Number of memory cells required */
8287 int nCsr; /* Number of cursors required */
8288 void *token; /* id that may be used to recursive triggers */
8289 SubProgram *pNext; /* Next sub-program already visited */
8293 ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
8294 ** it takes up less space.
8296 struct VdbeOpList {
8297 u8 opcode; /* What operation to perform */
8298 signed char p1; /* First operand */
8299 signed char p2; /* Second parameter (often the jump destination) */
8300 signed char p3; /* Third parameter */
8302 typedef struct VdbeOpList VdbeOpList;
8305 ** Allowed values of VdbeOp.p4type
8307 #define P4_NOTUSED 0 /* The P4 parameter is not used */
8308 #define P4_DYNAMIC (-1) /* Pointer to a string obtained from sqliteMalloc() */
8309 #define P4_STATIC (-2) /* Pointer to a static string */
8310 #define P4_COLLSEQ (-4) /* P4 is a pointer to a CollSeq structure */
8311 #define P4_FUNCDEF (-5) /* P4 is a pointer to a FuncDef structure */
8312 #define P4_KEYINFO (-6) /* P4 is a pointer to a KeyInfo structure */
8313 #define P4_VDBEFUNC (-7) /* P4 is a pointer to a VdbeFunc structure */
8314 #define P4_MEM (-8) /* P4 is a pointer to a Mem* structure */
8315 #define P4_TRANSIENT 0 /* P4 is a pointer to a transient string */
8316 #define P4_VTAB (-10) /* P4 is a pointer to an sqlite3_vtab structure */
8317 #define P4_MPRINTF (-11) /* P4 is a string obtained from sqlite3_mprintf() */
8318 #define P4_REAL (-12) /* P4 is a 64-bit floating point value */
8319 #define P4_INT64 (-13) /* P4 is a 64-bit signed integer */
8320 #define P4_INT32 (-14) /* P4 is a 32-bit signed integer */
8321 #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
8322 #define P4_SUBPROGRAM (-18) /* P4 is a pointer to a SubProgram structure */
8323 #define P4_ADVANCE (-19) /* P4 is a pointer to BtreeNext() or BtreePrev() */
8325 /* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
8326 ** is made. That copy is freed when the Vdbe is finalized. But if the
8327 ** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used. It still
8328 ** gets freed when the Vdbe is finalized so it still should be obtained
8329 ** from a single sqliteMalloc(). But no copy is made and the calling
8330 ** function should *not* try to free the KeyInfo.
8332 #define P4_KEYINFO_HANDOFF (-16)
8333 #define P4_KEYINFO_STATIC (-17)
8336 ** The Vdbe.aColName array contains 5n Mem structures, where n is the
8337 ** number of columns of data returned by the statement.
8339 #define COLNAME_NAME 0
8340 #define COLNAME_DECLTYPE 1
8341 #define COLNAME_DATABASE 2
8342 #define COLNAME_TABLE 3
8343 #define COLNAME_COLUMN 4
8344 #ifdef SQLITE_ENABLE_COLUMN_METADATA
8345 # define COLNAME_N 5 /* Number of COLNAME_xxx symbols */
8346 #else
8347 # ifdef SQLITE_OMIT_DECLTYPE
8348 # define COLNAME_N 1 /* Store only the name */
8349 # else
8350 # define COLNAME_N 2 /* Store the name and decltype */
8351 # endif
8352 #endif
8355 ** The following macro converts a relative address in the p2 field
8356 ** of a VdbeOp structure into a negative number so that
8357 ** sqlite3VdbeAddOpList() knows that the address is relative. Calling
8358 ** the macro again restores the address.
8360 #define ADDR(X) (-1-(X))
8363 ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
8364 ** header file that defines a number for each opcode used by the VDBE.
8366 /************** Include opcodes.h in the middle of vdbe.h ********************/
8367 /************** Begin file opcodes.h *****************************************/
8368 /* Automatically generated. Do not edit */
8369 /* See the mkopcodeh.awk script for details */
8370 #define OP_Goto 1
8371 #define OP_Gosub 2
8372 #define OP_Return 3
8373 #define OP_Yield 4
8374 #define OP_HaltIfNull 5
8375 #define OP_Halt 6
8376 #define OP_Integer 7
8377 #define OP_Int64 8
8378 #define OP_Real 130 /* same as TK_FLOAT */
8379 #define OP_String8 94 /* same as TK_STRING */
8380 #define OP_String 9
8381 #define OP_Null 10
8382 #define OP_Blob 11
8383 #define OP_Variable 12
8384 #define OP_Move 13
8385 #define OP_Copy 14
8386 #define OP_SCopy 15
8387 #define OP_ResultRow 16
8388 #define OP_Concat 91 /* same as TK_CONCAT */
8389 #define OP_Add 86 /* same as TK_PLUS */
8390 #define OP_Subtract 87 /* same as TK_MINUS */
8391 #define OP_Multiply 88 /* same as TK_STAR */
8392 #define OP_Divide 89 /* same as TK_SLASH */
8393 #define OP_Remainder 90 /* same as TK_REM */
8394 #define OP_CollSeq 17
8395 #define OP_Function 18
8396 #define OP_BitAnd 82 /* same as TK_BITAND */
8397 #define OP_BitOr 83 /* same as TK_BITOR */
8398 #define OP_ShiftLeft 84 /* same as TK_LSHIFT */
8399 #define OP_ShiftRight 85 /* same as TK_RSHIFT */
8400 #define OP_AddImm 20
8401 #define OP_MustBeInt 21
8402 #define OP_RealAffinity 22
8403 #define OP_ToText 141 /* same as TK_TO_TEXT */
8404 #define OP_ToBlob 142 /* same as TK_TO_BLOB */
8405 #define OP_ToNumeric 143 /* same as TK_TO_NUMERIC*/
8406 #define OP_ToInt 144 /* same as TK_TO_INT */
8407 #define OP_ToReal 145 /* same as TK_TO_REAL */
8408 #define OP_Eq 76 /* same as TK_EQ */
8409 #define OP_Ne 75 /* same as TK_NE */
8410 #define OP_Lt 79 /* same as TK_LT */
8411 #define OP_Le 78 /* same as TK_LE */
8412 #define OP_Gt 77 /* same as TK_GT */
8413 #define OP_Ge 80 /* same as TK_GE */
8414 #define OP_Permutation 23
8415 #define OP_Compare 24
8416 #define OP_Jump 25
8417 #define OP_And 69 /* same as TK_AND */
8418 #define OP_Or 68 /* same as TK_OR */
8419 #define OP_Not 19 /* same as TK_NOT */
8420 #define OP_BitNot 93 /* same as TK_BITNOT */
8421 #define OP_Once 26
8422 #define OP_If 27
8423 #define OP_IfNot 28
8424 #define OP_IsNull 73 /* same as TK_ISNULL */
8425 #define OP_NotNull 74 /* same as TK_NOTNULL */
8426 #define OP_Column 29
8427 #define OP_Affinity 30
8428 #define OP_MakeRecord 31
8429 #define OP_Count 32
8430 #define OP_Savepoint 33
8431 #define OP_AutoCommit 34
8432 #define OP_Transaction 35
8433 #define OP_ReadCookie 36
8434 #define OP_SetCookie 37
8435 #define OP_VerifyCookie 38
8436 #define OP_OpenRead 39
8437 #define OP_OpenWrite 40
8438 #define OP_OpenAutoindex 41
8439 #define OP_OpenEphemeral 42
8440 #define OP_SorterOpen 43
8441 #define OP_OpenPseudo 44
8442 #define OP_Close 45
8443 #define OP_SeekLt 46
8444 #define OP_SeekLe 47
8445 #define OP_SeekGe 48
8446 #define OP_SeekGt 49
8447 #define OP_Seek 50
8448 #define OP_NotFound 51
8449 #define OP_Found 52
8450 #define OP_IsUnique 53
8451 #define OP_NotExists 54
8452 #define OP_Sequence 55
8453 #define OP_NewRowid 56
8454 #define OP_Insert 57
8455 #define OP_InsertInt 58
8456 #define OP_Delete 59
8457 #define OP_ResetCount 60
8458 #define OP_SorterCompare 61
8459 #define OP_SorterData 62
8460 #define OP_RowKey 63
8461 #define OP_RowData 64
8462 #define OP_Rowid 65
8463 #define OP_NullRow 66
8464 #define OP_Last 67
8465 #define OP_SorterSort 70
8466 #define OP_Sort 71
8467 #define OP_Rewind 72
8468 #define OP_SorterNext 81
8469 #define OP_Prev 92
8470 #define OP_Next 95
8471 #define OP_SorterInsert 96
8472 #define OP_IdxInsert 97
8473 #define OP_IdxDelete 98
8474 #define OP_IdxRowid 99
8475 #define OP_IdxLT 100
8476 #define OP_IdxGE 101
8477 #define OP_Destroy 102
8478 #define OP_Clear 103
8479 #define OP_CreateIndex 104
8480 #define OP_CreateTable 105
8481 #define OP_ParseSchema 106
8482 #define OP_LoadAnalysis 107
8483 #define OP_DropTable 108
8484 #define OP_DropIndex 109
8485 #define OP_DropTrigger 110
8486 #define OP_IntegrityCk 111
8487 #define OP_RowSetAdd 112
8488 #define OP_RowSetRead 113
8489 #define OP_RowSetTest 114
8490 #define OP_Program 115
8491 #define OP_Param 116
8492 #define OP_FkCounter 117
8493 #define OP_FkIfZero 118
8494 #define OP_MemMax 119
8495 #define OP_IfPos 120
8496 #define OP_IfNeg 121
8497 #define OP_IfZero 122
8498 #define OP_AggStep 123
8499 #define OP_AggFinal 124
8500 #define OP_Checkpoint 125
8501 #define OP_JournalMode 126
8502 #define OP_Vacuum 127
8503 #define OP_IncrVacuum 128
8504 #define OP_Expire 129
8505 #define OP_TableLock 131
8506 #define OP_VBegin 132
8507 #define OP_VCreate 133
8508 #define OP_VDestroy 134
8509 #define OP_VOpen 135
8510 #define OP_VFilter 136
8511 #define OP_VColumn 137
8512 #define OP_VNext 138
8513 #define OP_VRename 139
8514 #define OP_VUpdate 140
8515 #define OP_Pagecount 146
8516 #define OP_MaxPgcnt 147
8517 #define OP_Trace 148
8518 #define OP_Noop 149
8519 #define OP_Explain 150
8522 /* Properties such as "out2" or "jump" that are specified in
8523 ** comments following the "case" for each opcode in the vdbe.c
8524 ** are encoded into bitvectors as follows:
8526 #define OPFLG_JUMP 0x0001 /* jump: P2 holds jmp target */
8527 #define OPFLG_OUT2_PRERELEASE 0x0002 /* out2-prerelease: */
8528 #define OPFLG_IN1 0x0004 /* in1: P1 is an input */
8529 #define OPFLG_IN2 0x0008 /* in2: P2 is an input */
8530 #define OPFLG_IN3 0x0010 /* in3: P3 is an input */
8531 #define OPFLG_OUT2 0x0020 /* out2: P2 is an output */
8532 #define OPFLG_OUT3 0x0040 /* out3: P3 is an output */
8533 #define OPFLG_INITIALIZER {\
8534 /* 0 */ 0x00, 0x01, 0x05, 0x04, 0x04, 0x10, 0x00, 0x02,\
8535 /* 8 */ 0x02, 0x02, 0x02, 0x02, 0x02, 0x00, 0x24, 0x24,\
8536 /* 16 */ 0x00, 0x00, 0x00, 0x24, 0x04, 0x05, 0x04, 0x00,\
8537 /* 24 */ 0x00, 0x01, 0x05, 0x05, 0x05, 0x00, 0x00, 0x00,\
8538 /* 32 */ 0x02, 0x00, 0x00, 0x00, 0x02, 0x10, 0x00, 0x00,\
8539 /* 40 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x11,\
8540 /* 48 */ 0x11, 0x11, 0x08, 0x11, 0x11, 0x11, 0x11, 0x02,\
8541 /* 56 */ 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
8542 /* 64 */ 0x00, 0x02, 0x00, 0x01, 0x4c, 0x4c, 0x01, 0x01,\
8543 /* 72 */ 0x01, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\
8544 /* 80 */ 0x15, 0x01, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c,\
8545 /* 88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x01, 0x24, 0x02, 0x01,\
8546 /* 96 */ 0x08, 0x08, 0x00, 0x02, 0x01, 0x01, 0x02, 0x00,\
8547 /* 104 */ 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
8548 /* 112 */ 0x0c, 0x45, 0x15, 0x01, 0x02, 0x00, 0x01, 0x08,\
8549 /* 120 */ 0x05, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02, 0x00,\
8550 /* 128 */ 0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,\
8551 /* 136 */ 0x01, 0x00, 0x01, 0x00, 0x00, 0x04, 0x04, 0x04,\
8552 /* 144 */ 0x04, 0x04, 0x02, 0x02, 0x00, 0x00, 0x00,}
8554 /************** End of opcodes.h *********************************************/
8555 /************** Continuing where we left off in vdbe.h ***********************/
8558 ** Prototypes for the VDBE interface. See comments on the implementation
8559 ** for a description of what each of these routines does.
8561 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*);
8562 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
8563 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
8564 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
8565 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
8566 SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
8567 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
8568 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
8569 SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
8570 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
8571 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
8572 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
8573 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
8574 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
8575 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr);
8576 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
8577 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
8578 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
8579 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
8580 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
8581 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
8582 SQLITE_PRIVATE void sqlite3VdbeDeleteObject(sqlite3*,Vdbe*);
8583 SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
8584 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
8585 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
8586 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
8587 #ifdef SQLITE_DEBUG
8588 SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *, int);
8589 SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe*,FILE*);
8590 #endif
8591 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
8592 SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
8593 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
8594 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
8595 SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
8596 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
8597 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
8598 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
8599 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
8600 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
8601 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe*, int, u8);
8602 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
8603 #ifndef SQLITE_OMIT_TRACE
8604 SQLITE_PRIVATE char *sqlite3VdbeExpandSql(Vdbe*, const char*);
8605 #endif
8607 SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
8608 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
8609 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo *, char *, int, char **);
8611 #ifndef SQLITE_OMIT_TRIGGER
8612 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
8613 #endif
8616 #ifndef NDEBUG
8617 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe*, const char*, ...);
8618 # define VdbeComment(X) sqlite3VdbeComment X
8619 SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
8620 # define VdbeNoopComment(X) sqlite3VdbeNoopComment X
8621 #else
8622 # define VdbeComment(X)
8623 # define VdbeNoopComment(X)
8624 #endif
8626 #endif
8628 /************** End of vdbe.h ************************************************/
8629 /************** Continuing where we left off in sqliteInt.h ******************/
8630 /************** Include pager.h in the middle of sqliteInt.h *****************/
8631 /************** Begin file pager.h *******************************************/
8633 ** 2001 September 15
8635 ** The author disclaims copyright to this source code. In place of
8636 ** a legal notice, here is a blessing:
8638 ** May you do good and not evil.
8639 ** May you find forgiveness for yourself and forgive others.
8640 ** May you share freely, never taking more than you give.
8642 *************************************************************************
8643 ** This header file defines the interface that the sqlite page cache
8644 ** subsystem. The page cache subsystem reads and writes a file a page
8645 ** at a time and provides a journal for rollback.
8648 #ifndef _PAGER_H_
8649 #define _PAGER_H_
8652 ** Default maximum size for persistent journal files. A negative
8653 ** value means no limit. This value may be overridden using the
8654 ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
8656 #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
8657 #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
8658 #endif
8661 ** The type used to represent a page number. The first page in a file
8662 ** is called page 1. 0 is used to represent "not a page".
8664 typedef u32 Pgno;
8667 ** Each open file is managed by a separate instance of the "Pager" structure.
8669 typedef struct Pager Pager;
8672 ** Handle type for pages.
8674 typedef struct PgHdr DbPage;
8677 ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
8678 ** reserved for working around a windows/posix incompatibility). It is
8679 ** used in the journal to signify that the remainder of the journal file
8680 ** is devoted to storing a master journal name - there are no more pages to
8681 ** roll back. See comments for function writeMasterJournal() in pager.c
8682 ** for details.
8684 #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
8687 ** Allowed values for the flags parameter to sqlite3PagerOpen().
8689 ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
8691 #define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */
8692 #define PAGER_NO_READLOCK 0x0002 /* Omit readlocks on readonly files */
8693 #define PAGER_MEMORY 0x0004 /* In-memory database */
8696 ** Valid values for the second argument to sqlite3PagerLockingMode().
8698 #define PAGER_LOCKINGMODE_QUERY -1
8699 #define PAGER_LOCKINGMODE_NORMAL 0
8700 #define PAGER_LOCKINGMODE_EXCLUSIVE 1
8703 ** Numeric constants that encode the journalmode.
8705 #define PAGER_JOURNALMODE_QUERY (-1) /* Query the value of journalmode */
8706 #define PAGER_JOURNALMODE_DELETE 0 /* Commit by deleting journal file */
8707 #define PAGER_JOURNALMODE_PERSIST 1 /* Commit by zeroing journal header */
8708 #define PAGER_JOURNALMODE_OFF 2 /* Journal omitted. */
8709 #define PAGER_JOURNALMODE_TRUNCATE 3 /* Commit by truncating journal */
8710 #define PAGER_JOURNALMODE_MEMORY 4 /* In-memory journal file */
8711 #define PAGER_JOURNALMODE_WAL 5 /* Use write-ahead logging */
8714 ** The remainder of this file contains the declarations of the functions
8715 ** that make up the Pager sub-system API. See source code comments for
8716 ** a detailed description of each routine.
8719 /* Open and close a Pager connection. */
8720 SQLITE_PRIVATE int sqlite3PagerOpen(
8721 sqlite3_vfs*,
8722 Pager **ppPager,
8723 const char*,
8724 int,
8725 int,
8726 int,
8727 void(*)(DbPage*)
8729 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
8730 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
8732 /* Functions used to configure a Pager object. */
8733 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
8734 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
8735 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
8736 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
8737 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager*,int,int,int);
8738 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
8739 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
8740 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
8741 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
8742 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
8743 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
8745 /* Functions used to obtain and release page references. */
8746 SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
8747 #define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
8748 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
8749 SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
8750 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
8752 /* Operations on page references. */
8753 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
8754 SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
8755 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
8756 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
8757 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
8758 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
8760 /* Functions used to manage pager transactions and savepoints. */
8761 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
8762 SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
8763 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
8764 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
8765 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);
8766 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
8767 SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
8768 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
8769 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
8770 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
8772 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*);
8773 SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager);
8774 SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager);
8775 SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
8776 SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager);
8778 /* Functions used to query pager state and configuration. */
8779 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
8780 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
8781 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
8782 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*);
8783 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
8784 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
8785 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
8786 SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
8787 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
8788 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
8789 SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
8790 SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *);
8792 /* Functions used to truncate the database file. */
8793 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
8795 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
8796 SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
8797 #endif
8799 /* Functions to support testing and debugging. */
8800 #if !defined(NDEBUG) || defined(SQLITE_TEST)
8801 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage*);
8802 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage*);
8803 #endif
8804 #ifdef SQLITE_TEST
8805 SQLITE_PRIVATE int *sqlite3PagerStats(Pager*);
8806 SQLITE_PRIVATE void sqlite3PagerRefdump(Pager*);
8807 void disable_simulated_io_errors(void);
8808 void enable_simulated_io_errors(void);
8809 #else
8810 # define disable_simulated_io_errors()
8811 # define enable_simulated_io_errors()
8812 #endif
8814 #endif /* _PAGER_H_ */
8816 /************** End of pager.h ***********************************************/
8817 /************** Continuing where we left off in sqliteInt.h ******************/
8818 /************** Include pcache.h in the middle of sqliteInt.h ****************/
8819 /************** Begin file pcache.h ******************************************/
8821 ** 2008 August 05
8823 ** The author disclaims copyright to this source code. In place of
8824 ** a legal notice, here is a blessing:
8826 ** May you do good and not evil.
8827 ** May you find forgiveness for yourself and forgive others.
8828 ** May you share freely, never taking more than you give.
8830 *************************************************************************
8831 ** This header file defines the interface that the sqlite page cache
8832 ** subsystem.
8835 #ifndef _PCACHE_H_
8837 typedef struct PgHdr PgHdr;
8838 typedef struct PCache PCache;
8841 ** Every page in the cache is controlled by an instance of the following
8842 ** structure.
8844 struct PgHdr {
8845 void *pData; /* Content of this page */
8846 void *pExtra; /* Extra content */
8847 PgHdr *pDirty; /* Transient list of dirty pages */
8848 Pgno pgno; /* Page number for this page */
8849 Pager *pPager; /* The pager this page is part of */
8850 #ifdef SQLITE_CHECK_PAGES
8851 u32 pageHash; /* Hash of page content */
8852 #endif
8853 u16 flags; /* PGHDR flags defined below */
8855 /**********************************************************************
8856 ** Elements above are public. All that follows is private to pcache.c
8857 ** and should not be accessed by other modules.
8859 i16 nRef; /* Number of users of this page */
8860 PCache *pCache; /* Cache that owns this page */
8862 PgHdr *pDirtyNext; /* Next element in list of dirty pages */
8863 PgHdr *pDirtyPrev; /* Previous element in list of dirty pages */
8866 /* Bit values for PgHdr.flags */
8867 #define PGHDR_DIRTY 0x002 /* Page has changed */
8868 #define PGHDR_NEED_SYNC 0x004 /* Fsync the rollback journal before
8869 ** writing this page to the database */
8870 #define PGHDR_NEED_READ 0x008 /* Content is unread */
8871 #define PGHDR_REUSE_UNLIKELY 0x010 /* A hint that reuse is unlikely */
8872 #define PGHDR_DONT_WRITE 0x020 /* Do not write content to disk */
8874 /* Initialize and shutdown the page cache subsystem */
8875 SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
8876 SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
8878 /* Page cache buffer management:
8879 ** These routines implement SQLITE_CONFIG_PAGECACHE.
8881 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
8883 /* Create a new pager cache.
8884 ** Under memory stress, invoke xStress to try to make pages clean.
8885 ** Only clean and unpinned pages can be reclaimed.
8887 SQLITE_PRIVATE void sqlite3PcacheOpen(
8888 int szPage, /* Size of every page */
8889 int szExtra, /* Extra space associated with each page */
8890 int bPurgeable, /* True if pages are on backing store */
8891 int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
8892 void *pStress, /* Argument to xStress */
8893 PCache *pToInit /* Preallocated space for the PCache */
8896 /* Modify the page-size after the cache has been created. */
8897 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int);
8899 /* Return the size in bytes of a PCache object. Used to preallocate
8900 ** storage space.
8902 SQLITE_PRIVATE int sqlite3PcacheSize(void);
8904 /* One release per successful fetch. Page is pinned until released.
8905 ** Reference counted.
8907 SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**);
8908 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
8910 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */
8911 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */
8912 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */
8913 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */
8915 /* Change a page number. Used by incr-vacuum. */
8916 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
8918 /* Remove all pages with pgno>x. Reset the cache if x==0 */
8919 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
8921 /* Get a list of all dirty pages in the cache, sorted by page number */
8922 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
8924 /* Reset and close the cache object */
8925 SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
8927 /* Clear flags from pages of the page cache */
8928 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
8930 /* Discard the contents of the cache */
8931 SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
8933 /* Return the total number of outstanding page references */
8934 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
8936 /* Increment the reference count of an existing page */
8937 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
8939 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
8941 /* Return the total number of pages stored in the cache */
8942 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
8944 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
8945 /* Iterate through all dirty pages currently stored in the cache. This
8946 ** interface is only available if SQLITE_CHECK_PAGES is defined when the
8947 ** library is built.
8949 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
8950 #endif
8952 /* Set and get the suggested cache-size for the specified pager-cache.
8954 ** If no global maximum is configured, then the system attempts to limit
8955 ** the total number of pages cached by purgeable pager-caches to the sum
8956 ** of the suggested cache-sizes.
8958 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
8959 #ifdef SQLITE_TEST
8960 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
8961 #endif
8963 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
8964 /* Try to return memory used by the pcache module to the main memory heap */
8965 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
8966 #endif
8968 #ifdef SQLITE_TEST
8969 SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
8970 #endif
8972 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
8974 #endif /* _PCACHE_H_ */
8976 /************** End of pcache.h **********************************************/
8977 /************** Continuing where we left off in sqliteInt.h ******************/
8979 /************** Include os.h in the middle of sqliteInt.h ********************/
8980 /************** Begin file os.h **********************************************/
8982 ** 2001 September 16
8984 ** The author disclaims copyright to this source code. In place of
8985 ** a legal notice, here is a blessing:
8987 ** May you do good and not evil.
8988 ** May you find forgiveness for yourself and forgive others.
8989 ** May you share freely, never taking more than you give.
8991 ******************************************************************************
8993 ** This header file (together with is companion C source-code file
8994 ** "os.c") attempt to abstract the underlying operating system so that
8995 ** the SQLite library will work on both POSIX and windows systems.
8997 ** This header file is #include-ed by sqliteInt.h and thus ends up
8998 ** being included by every source file.
9000 #ifndef _SQLITE_OS_H_
9001 #define _SQLITE_OS_H_
9004 ** Figure out if we are dealing with Unix, Windows, or some other
9005 ** operating system. After the following block of preprocess macros,
9006 ** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, SQLITE_OS_OS2, and SQLITE_OS_OTHER
9007 ** will defined to either 1 or 0. One of the four will be 1. The other
9008 ** three will be 0.
9010 #if defined(SQLITE_OS_OTHER)
9011 # if SQLITE_OS_OTHER==1
9012 # undef SQLITE_OS_UNIX
9013 # define SQLITE_OS_UNIX 0
9014 # undef SQLITE_OS_WIN
9015 # define SQLITE_OS_WIN 0
9016 # undef SQLITE_OS_OS2
9017 # define SQLITE_OS_OS2 0
9018 # else
9019 # undef SQLITE_OS_OTHER
9020 # endif
9021 #endif
9022 #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
9023 # define SQLITE_OS_OTHER 0
9024 # ifndef SQLITE_OS_WIN
9025 # if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
9026 # define SQLITE_OS_WIN 1
9027 # define SQLITE_OS_UNIX 0
9028 # define SQLITE_OS_OS2 0
9029 # elif defined(__EMX__) || defined(_OS2) || defined(OS2) || defined(_OS2_) || defined(__OS2__)
9030 # define SQLITE_OS_WIN 0
9031 # define SQLITE_OS_UNIX 0
9032 # define SQLITE_OS_OS2 1
9033 # else
9034 # define SQLITE_OS_WIN 0
9035 # define SQLITE_OS_UNIX 1
9036 # define SQLITE_OS_OS2 0
9037 # endif
9038 # else
9039 # define SQLITE_OS_UNIX 0
9040 # define SQLITE_OS_OS2 0
9041 # endif
9042 #else
9043 # ifndef SQLITE_OS_WIN
9044 # define SQLITE_OS_WIN 0
9045 # endif
9046 #endif
9049 ** Determine if we are dealing with WindowsCE - which has a much
9050 ** reduced API.
9052 #if defined(_WIN32_WCE)
9053 # define SQLITE_OS_WINCE 1
9054 #else
9055 # define SQLITE_OS_WINCE 0
9056 #endif
9060 ** Define the maximum size of a temporary filename
9062 #if SQLITE_OS_WIN
9063 # include <windows.h>
9064 # define SQLITE_TEMPNAME_SIZE (MAX_PATH+50)
9065 #elif SQLITE_OS_OS2
9066 # if (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 3) && defined(OS2_HIGH_MEMORY)
9067 # include <os2safe.h> /* has to be included before os2.h for linking to work */
9068 # endif
9069 # define INCL_DOSDATETIME
9070 # define INCL_DOSFILEMGR
9071 # define INCL_DOSERRORS
9072 # define INCL_DOSMISC
9073 # define INCL_DOSPROCESS
9074 # define INCL_DOSMODULEMGR
9075 # define INCL_DOSSEMAPHORES
9076 # include <os2.h>
9077 # include <uconv.h>
9078 # define SQLITE_TEMPNAME_SIZE (CCHMAXPATHCOMP)
9079 #else
9080 # define SQLITE_TEMPNAME_SIZE 200
9081 #endif
9083 /* If the SET_FULLSYNC macro is not defined above, then make it
9084 ** a no-op
9086 #ifndef SET_FULLSYNC
9087 # define SET_FULLSYNC(x,y)
9088 #endif
9091 ** The default size of a disk sector
9093 #ifndef SQLITE_DEFAULT_SECTOR_SIZE
9094 # define SQLITE_DEFAULT_SECTOR_SIZE 512
9095 #endif
9098 ** Temporary files are named starting with this prefix followed by 16 random
9099 ** alphanumeric characters, and no file extension. They are stored in the
9100 ** OS's standard temporary file directory, and are deleted prior to exit.
9101 ** If sqlite is being embedded in another program, you may wish to change the
9102 ** prefix to reflect your program's name, so that if your program exits
9103 ** prematurely, old temporary files can be easily identified. This can be done
9104 ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
9106 ** 2006-10-31: The default prefix used to be "sqlite_". But then
9107 ** Mcafee started using SQLite in their anti-virus product and it
9108 ** started putting files with the "sqlite" name in the c:/temp folder.
9109 ** This annoyed many windows users. Those users would then do a
9110 ** Google search for "sqlite", find the telephone numbers of the
9111 ** developers and call to wake them up at night and complain.
9112 ** For this reason, the default name prefix is changed to be "sqlite"
9113 ** spelled backwards. So the temp files are still identified, but
9114 ** anybody smart enough to figure out the code is also likely smart
9115 ** enough to know that calling the developer will not help get rid
9116 ** of the file.
9118 #ifndef SQLITE_TEMP_FILE_PREFIX
9119 # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
9120 #endif
9123 ** The following values may be passed as the second argument to
9124 ** sqlite3OsLock(). The various locks exhibit the following semantics:
9126 ** SHARED: Any number of processes may hold a SHARED lock simultaneously.
9127 ** RESERVED: A single process may hold a RESERVED lock on a file at
9128 ** any time. Other processes may hold and obtain new SHARED locks.
9129 ** PENDING: A single process may hold a PENDING lock on a file at
9130 ** any one time. Existing SHARED locks may persist, but no new
9131 ** SHARED locks may be obtained by other processes.
9132 ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
9134 ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
9135 ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
9136 ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
9137 ** sqlite3OsLock().
9139 #define NO_LOCK 0
9140 #define SHARED_LOCK 1
9141 #define RESERVED_LOCK 2
9142 #define PENDING_LOCK 3
9143 #define EXCLUSIVE_LOCK 4
9146 ** File Locking Notes: (Mostly about windows but also some info for Unix)
9148 ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
9149 ** those functions are not available. So we use only LockFile() and
9150 ** UnlockFile().
9152 ** LockFile() prevents not just writing but also reading by other processes.
9153 ** A SHARED_LOCK is obtained by locking a single randomly-chosen
9154 ** byte out of a specific range of bytes. The lock byte is obtained at
9155 ** random so two separate readers can probably access the file at the
9156 ** same time, unless they are unlucky and choose the same lock byte.
9157 ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
9158 ** There can only be one writer. A RESERVED_LOCK is obtained by locking
9159 ** a single byte of the file that is designated as the reserved lock byte.
9160 ** A PENDING_LOCK is obtained by locking a designated byte different from
9161 ** the RESERVED_LOCK byte.
9163 ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
9164 ** which means we can use reader/writer locks. When reader/writer locks
9165 ** are used, the lock is placed on the same range of bytes that is used
9166 ** for probabilistic locking in Win95/98/ME. Hence, the locking scheme
9167 ** will support two or more Win95 readers or two or more WinNT readers.
9168 ** But a single Win95 reader will lock out all WinNT readers and a single
9169 ** WinNT reader will lock out all other Win95 readers.
9171 ** The following #defines specify the range of bytes used for locking.
9172 ** SHARED_SIZE is the number of bytes available in the pool from which
9173 ** a random byte is selected for a shared lock. The pool of bytes for
9174 ** shared locks begins at SHARED_FIRST.
9176 ** The same locking strategy and
9177 ** byte ranges are used for Unix. This leaves open the possiblity of having
9178 ** clients on win95, winNT, and unix all talking to the same shared file
9179 ** and all locking correctly. To do so would require that samba (or whatever
9180 ** tool is being used for file sharing) implements locks correctly between
9181 ** windows and unix. I'm guessing that isn't likely to happen, but by
9182 ** using the same locking range we are at least open to the possibility.
9184 ** Locking in windows is manditory. For this reason, we cannot store
9185 ** actual data in the bytes used for locking. The pager never allocates
9186 ** the pages involved in locking therefore. SHARED_SIZE is selected so
9187 ** that all locks will fit on a single page even at the minimum page size.
9188 ** PENDING_BYTE defines the beginning of the locks. By default PENDING_BYTE
9189 ** is set high so that we don't have to allocate an unused page except
9190 ** for very large databases. But one should test the page skipping logic
9191 ** by setting PENDING_BYTE low and running the entire regression suite.
9193 ** Changing the value of PENDING_BYTE results in a subtly incompatible
9194 ** file format. Depending on how it is changed, you might not notice
9195 ** the incompatibility right away, even running a full regression test.
9196 ** The default location of PENDING_BYTE is the first byte past the
9197 ** 1GB boundary.
9200 #ifdef SQLITE_OMIT_WSD
9201 # define PENDING_BYTE (0x40000000)
9202 #else
9203 # define PENDING_BYTE sqlite3PendingByte
9204 #endif
9205 #define RESERVED_BYTE (PENDING_BYTE+1)
9206 #define SHARED_FIRST (PENDING_BYTE+2)
9207 #define SHARED_SIZE 510
9210 ** Wrapper around OS specific sqlite3_os_init() function.
9212 SQLITE_PRIVATE int sqlite3OsInit(void);
9215 ** Functions for accessing sqlite3_file methods
9217 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
9218 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
9219 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
9220 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
9221 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
9222 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
9223 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
9224 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
9225 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
9226 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
9227 #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
9228 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
9229 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
9230 SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
9231 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
9232 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
9233 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
9236 ** Functions for accessing sqlite3_vfs methods
9238 SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
9239 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
9240 SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
9241 SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
9242 #ifndef SQLITE_OMIT_LOAD_EXTENSION
9243 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
9244 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
9245 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
9246 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
9247 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
9248 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
9249 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
9250 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
9253 ** Convenience functions for opening and closing files using
9254 ** sqlite3_malloc() to obtain space for the file-handle structure.
9256 SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
9257 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
9259 #endif /* _SQLITE_OS_H_ */
9261 /************** End of os.h **************************************************/
9262 /************** Continuing where we left off in sqliteInt.h ******************/
9263 /************** Include mutex.h in the middle of sqliteInt.h *****************/
9264 /************** Begin file mutex.h *******************************************/
9266 ** 2007 August 28
9268 ** The author disclaims copyright to this source code. In place of
9269 ** a legal notice, here is a blessing:
9271 ** May you do good and not evil.
9272 ** May you find forgiveness for yourself and forgive others.
9273 ** May you share freely, never taking more than you give.
9275 *************************************************************************
9277 ** This file contains the common header for all mutex implementations.
9278 ** The sqliteInt.h header #includes this file so that it is available
9279 ** to all source files. We break it out in an effort to keep the code
9280 ** better organized.
9282 ** NOTE: source files should *not* #include this header file directly.
9283 ** Source files should #include the sqliteInt.h file and let that file
9284 ** include this one indirectly.
9289 ** Figure out what version of the code to use. The choices are
9291 ** SQLITE_MUTEX_OMIT No mutex logic. Not even stubs. The
9292 ** mutexes implemention cannot be overridden
9293 ** at start-time.
9295 ** SQLITE_MUTEX_NOOP For single-threaded applications. No
9296 ** mutual exclusion is provided. But this
9297 ** implementation can be overridden at
9298 ** start-time.
9300 ** SQLITE_MUTEX_PTHREADS For multi-threaded applications on Unix.
9302 ** SQLITE_MUTEX_W32 For multi-threaded applications on Win32.
9304 ** SQLITE_MUTEX_OS2 For multi-threaded applications on OS/2.
9306 #if !SQLITE_THREADSAFE
9307 # define SQLITE_MUTEX_OMIT
9308 #endif
9309 #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
9310 # if SQLITE_OS_UNIX
9311 # define SQLITE_MUTEX_PTHREADS
9312 # elif SQLITE_OS_WIN
9313 # define SQLITE_MUTEX_W32
9314 # elif SQLITE_OS_OS2
9315 # define SQLITE_MUTEX_OS2
9316 # else
9317 # define SQLITE_MUTEX_NOOP
9318 # endif
9319 #endif
9321 #ifdef SQLITE_MUTEX_OMIT
9323 ** If this is a no-op implementation, implement everything as macros.
9325 #define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8)
9326 #define sqlite3_mutex_free(X)
9327 #define sqlite3_mutex_enter(X)
9328 #define sqlite3_mutex_try(X) SQLITE_OK
9329 #define sqlite3_mutex_leave(X)
9330 #define sqlite3_mutex_held(X) ((void)(X),1)
9331 #define sqlite3_mutex_notheld(X) ((void)(X),1)
9332 #define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8)
9333 #define sqlite3MutexInit() SQLITE_OK
9334 #define sqlite3MutexEnd()
9335 #define MUTEX_LOGIC(X)
9336 #else
9337 #define MUTEX_LOGIC(X) X
9338 #endif /* defined(SQLITE_MUTEX_OMIT) */
9340 /************** End of mutex.h ***********************************************/
9341 /************** Continuing where we left off in sqliteInt.h ******************/
9345 ** Each database file to be accessed by the system is an instance
9346 ** of the following structure. There are normally two of these structures
9347 ** in the sqlite.aDb[] array. aDb[0] is the main database file and
9348 ** aDb[1] is the database file used to hold temporary tables. Additional
9349 ** databases may be attached.
9351 struct Db {
9352 char *zName; /* Name of this database */
9353 Btree *pBt; /* The B*Tree structure for this database file */
9354 u8 inTrans; /* 0: not writable. 1: Transaction. 2: Checkpoint */
9355 u8 safety_level; /* How aggressive at syncing data to disk */
9356 Schema *pSchema; /* Pointer to database schema (possibly shared) */
9360 ** An instance of the following structure stores a database schema.
9362 ** Most Schema objects are associated with a Btree. The exception is
9363 ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
9364 ** In shared cache mode, a single Schema object can be shared by multiple
9365 ** Btrees that refer to the same underlying BtShared object.
9367 ** Schema objects are automatically deallocated when the last Btree that
9368 ** references them is destroyed. The TEMP Schema is manually freed by
9369 ** sqlite3_close().
9371 ** A thread must be holding a mutex on the corresponding Btree in order
9372 ** to access Schema content. This implies that the thread must also be
9373 ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
9374 ** For a TEMP Schema, only the connection mutex is required.
9376 struct Schema {
9377 int schema_cookie; /* Database schema version number for this file */
9378 int iGeneration; /* Generation counter. Incremented with each change */
9379 Hash tblHash; /* All tables indexed by name */
9380 Hash idxHash; /* All (named) indices indexed by name */
9381 Hash trigHash; /* All triggers indexed by name */
9382 Hash fkeyHash; /* All foreign keys by referenced table name */
9383 Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */
9384 u8 file_format; /* Schema format version for this file */
9385 u8 enc; /* Text encoding used by this database */
9386 u16 flags; /* Flags associated with this schema */
9387 int cache_size; /* Number of pages to use in the cache */
9391 ** These macros can be used to test, set, or clear bits in the
9392 ** Db.pSchema->flags field.
9394 #define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))==(P))
9395 #define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))!=0)
9396 #define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->flags|=(P)
9397 #define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->flags&=~(P)
9400 ** Allowed values for the DB.pSchema->flags field.
9402 ** The DB_SchemaLoaded flag is set after the database schema has been
9403 ** read into internal hash tables.
9405 ** DB_UnresetViews means that one or more views have column names that
9406 ** have been filled out. If the schema changes, these column names might
9407 ** changes and so the view will need to be reset.
9409 #define DB_SchemaLoaded 0x0001 /* The schema has been loaded */
9410 #define DB_UnresetViews 0x0002 /* Some views have defined column names */
9411 #define DB_Empty 0x0004 /* The file is empty (length 0 bytes) */
9414 ** The number of different kinds of things that can be limited
9415 ** using the sqlite3_limit() interface.
9417 #define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1)
9420 ** Lookaside malloc is a set of fixed-size buffers that can be used
9421 ** to satisfy small transient memory allocation requests for objects
9422 ** associated with a particular database connection. The use of
9423 ** lookaside malloc provides a significant performance enhancement
9424 ** (approx 10%) by avoiding numerous malloc/free requests while parsing
9425 ** SQL statements.
9427 ** The Lookaside structure holds configuration information about the
9428 ** lookaside malloc subsystem. Each available memory allocation in
9429 ** the lookaside subsystem is stored on a linked list of LookasideSlot
9430 ** objects.
9432 ** Lookaside allocations are only allowed for objects that are associated
9433 ** with a particular database connection. Hence, schema information cannot
9434 ** be stored in lookaside because in shared cache mode the schema information
9435 ** is shared by multiple database connections. Therefore, while parsing
9436 ** schema information, the Lookaside.bEnabled flag is cleared so that
9437 ** lookaside allocations are not used to construct the schema objects.
9439 struct Lookaside {
9440 u16 sz; /* Size of each buffer in bytes */
9441 u8 bEnabled; /* False to disable new lookaside allocations */
9442 u8 bMalloced; /* True if pStart obtained from sqlite3_malloc() */
9443 int nOut; /* Number of buffers currently checked out */
9444 int mxOut; /* Highwater mark for nOut */
9445 int anStat[3]; /* 0: hits. 1: size misses. 2: full misses */
9446 LookasideSlot *pFree; /* List of available buffers */
9447 void *pStart; /* First byte of available memory space */
9448 void *pEnd; /* First byte past end of available space */
9450 struct LookasideSlot {
9451 LookasideSlot *pNext; /* Next buffer in the list of free buffers */
9455 ** A hash table for function definitions.
9457 ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
9458 ** Collisions are on the FuncDef.pHash chain.
9460 struct FuncDefHash {
9461 FuncDef *a[23]; /* Hash table for functions */
9465 ** Each database connection is an instance of the following structure.
9467 ** The sqlite.lastRowid records the last insert rowid generated by an
9468 ** insert statement. Inserts on views do not affect its value. Each
9469 ** trigger has its own context, so that lastRowid can be updated inside
9470 ** triggers as usual. The previous value will be restored once the trigger
9471 ** exits. Upon entering a before or instead of trigger, lastRowid is no
9472 ** longer (since after version 2.8.12) reset to -1.
9474 ** The sqlite.nChange does not count changes within triggers and keeps no
9475 ** context. It is reset at start of sqlite3_exec.
9476 ** The sqlite.lsChange represents the number of changes made by the last
9477 ** insert, update, or delete statement. It remains constant throughout the
9478 ** length of a statement and is then updated by OP_SetCounts. It keeps a
9479 ** context stack just like lastRowid so that the count of changes
9480 ** within a trigger is not seen outside the trigger. Changes to views do not
9481 ** affect the value of lsChange.
9482 ** The sqlite.csChange keeps track of the number of current changes (since
9483 ** the last statement) and is used to update sqlite_lsChange.
9485 ** The member variables sqlite.errCode, sqlite.zErrMsg and sqlite.zErrMsg16
9486 ** store the most recent error code and, if applicable, string. The
9487 ** internal function sqlite3Error() is used to set these variables
9488 ** consistently.
9490 struct sqlite3 {
9491 sqlite3_vfs *pVfs; /* OS Interface */
9492 int nDb; /* Number of backends currently in use */
9493 Db *aDb; /* All backends */
9494 int flags; /* Miscellaneous flags. See below */
9495 unsigned int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */
9496 int errCode; /* Most recent error code (SQLITE_*) */
9497 int errMask; /* & result codes with this before returning */
9498 u8 autoCommit; /* The auto-commit flag. */
9499 u8 temp_store; /* 1: file 2: memory 0: default */
9500 u8 mallocFailed; /* True if we have seen a malloc failure */
9501 u8 dfltLockMode; /* Default locking-mode for attached dbs */
9502 signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */
9503 u8 suppressErr; /* Do not issue error messages if true */
9504 u8 vtabOnConflict; /* Value to return for s3_vtab_on_conflict() */
9505 int nextPagesize; /* Pagesize after VACUUM if >0 */
9506 int nTable; /* Number of tables in the database */
9507 CollSeq *pDfltColl; /* The default collating sequence (BINARY) */
9508 i64 lastRowid; /* ROWID of most recent insert (see above) */
9509 u32 magic; /* Magic number for detect library misuse */
9510 int nChange; /* Value returned by sqlite3_changes() */
9511 int nTotalChange; /* Value returned by sqlite3_total_changes() */
9512 sqlite3_mutex *mutex; /* Connection mutex */
9513 int aLimit[SQLITE_N_LIMIT]; /* Limits */
9514 struct sqlite3InitInfo { /* Information used during initialization */
9515 int iDb; /* When back is being initialized */
9516 int newTnum; /* Rootpage of table being initialized */
9517 u8 busy; /* TRUE if currently initializing */
9518 u8 orphanTrigger; /* Last statement is orphaned TEMP trigger */
9519 } init;
9520 int nExtension; /* Number of loaded extensions */
9521 void **aExtension; /* Array of shared library handles */
9522 struct Vdbe *pVdbe; /* List of active virtual machines */
9523 int activeVdbeCnt; /* Number of VDBEs currently executing */
9524 int writeVdbeCnt; /* Number of active VDBEs that are writing */
9525 int vdbeExecCnt; /* Number of nested calls to VdbeExec() */
9526 void (*xTrace)(void*,const char*); /* Trace function */
9527 void *pTraceArg; /* Argument to the trace function */
9528 void (*xProfile)(void*,const char*,u64); /* Profiling function */
9529 void *pProfileArg; /* Argument to profile function */
9530 void *pCommitArg; /* Argument to xCommitCallback() */
9531 int (*xCommitCallback)(void*); /* Invoked at every commit. */
9532 void *pRollbackArg; /* Argument to xRollbackCallback() */
9533 void (*xRollbackCallback)(void*); /* Invoked at every commit. */
9534 void *pUpdateArg;
9535 void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
9536 #ifndef SQLITE_OMIT_WAL
9537 int (*xWalCallback)(void *, sqlite3 *, const char *, int);
9538 void *pWalArg;
9539 #endif
9540 void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
9541 void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
9542 void *pCollNeededArg;
9543 sqlite3_value *pErr; /* Most recent error message */
9544 char *zErrMsg; /* Most recent error message (UTF-8 encoded) */
9545 char *zErrMsg16; /* Most recent error message (UTF-16 encoded) */
9546 union {
9547 volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
9548 double notUsed1; /* Spacer */
9549 } u1;
9550 Lookaside lookaside; /* Lookaside malloc configuration */
9551 #ifndef SQLITE_OMIT_AUTHORIZATION
9552 int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
9553 /* Access authorization function */
9554 void *pAuthArg; /* 1st argument to the access auth function */
9555 #endif
9556 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
9557 int (*xProgress)(void *); /* The progress callback */
9558 void *pProgressArg; /* Argument to the progress callback */
9559 int nProgressOps; /* Number of opcodes for progress callback */
9560 #endif
9561 #ifndef SQLITE_OMIT_VIRTUALTABLE
9562 Hash aModule; /* populated by sqlite3_create_module() */
9563 VtabCtx *pVtabCtx; /* Context for active vtab connect/create */
9564 VTable **aVTrans; /* Virtual tables with open transactions */
9565 int nVTrans; /* Allocated size of aVTrans */
9566 VTable *pDisconnect; /* Disconnect these in next sqlite3_prepare() */
9567 #endif
9568 FuncDefHash aFunc; /* Hash table of connection functions */
9569 Hash aCollSeq; /* All collating sequences */
9570 BusyHandler busyHandler; /* Busy callback */
9571 int busyTimeout; /* Busy handler timeout, in msec */
9572 Db aDbStatic[2]; /* Static space for the 2 default backends */
9573 Savepoint *pSavepoint; /* List of active savepoints */
9574 int nSavepoint; /* Number of non-transaction savepoints */
9575 int nStatement; /* Number of nested statement-transactions */
9576 u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */
9577 i64 nDeferredCons; /* Net deferred constraints this transaction. */
9578 int *pnBytesFreed; /* If not NULL, increment this in DbFree() */
9580 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
9581 /* The following variables are all protected by the STATIC_MASTER
9582 ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
9584 ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
9585 ** unlock so that it can proceed.
9587 ** When X.pBlockingConnection==Y, that means that something that X tried
9588 ** tried to do recently failed with an SQLITE_LOCKED error due to locks
9589 ** held by Y.
9591 sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
9592 sqlite3 *pUnlockConnection; /* Connection to watch for unlock */
9593 void *pUnlockArg; /* Argument to xUnlockNotify */
9594 void (*xUnlockNotify)(void **, int); /* Unlock notify callback */
9595 sqlite3 *pNextBlocked; /* Next in list of all blocked connections */
9596 #endif
9600 ** A macro to discover the encoding of a database.
9602 #define ENC(db) ((db)->aDb[0].pSchema->enc)
9605 ** Possible values for the sqlite3.flags.
9607 #define SQLITE_VdbeTrace 0x00000100 /* True to trace VDBE execution */
9608 #define SQLITE_InternChanges 0x00000200 /* Uncommitted Hash table changes */
9609 #define SQLITE_FullColNames 0x00000400 /* Show full column names on SELECT */
9610 #define SQLITE_ShortColNames 0x00000800 /* Show short columns names */
9611 #define SQLITE_CountRows 0x00001000 /* Count rows changed by INSERT, */
9612 /* DELETE, or UPDATE and return */
9613 /* the count using a callback. */
9614 #define SQLITE_NullCallback 0x00002000 /* Invoke the callback once if the */
9615 /* result set is empty */
9616 #define SQLITE_SqlTrace 0x00004000 /* Debug print SQL as it executes */
9617 #define SQLITE_VdbeListing 0x00008000 /* Debug listings of VDBE programs */
9618 #define SQLITE_WriteSchema 0x00010000 /* OK to update SQLITE_MASTER */
9619 #define SQLITE_NoReadlock 0x00020000 /* Readlocks are omitted when
9620 ** accessing read-only databases */
9621 #define SQLITE_IgnoreChecks 0x00040000 /* Do not enforce check constraints */
9622 #define SQLITE_ReadUncommitted 0x0080000 /* For shared-cache mode */
9623 #define SQLITE_LegacyFileFmt 0x00100000 /* Create new databases in format 1 */
9624 #define SQLITE_FullFSync 0x00200000 /* Use full fsync on the backend */
9625 #define SQLITE_CkptFullFSync 0x00400000 /* Use full fsync for checkpoint */
9626 #define SQLITE_RecoveryMode 0x00800000 /* Ignore schema errors */
9627 #define SQLITE_ReverseOrder 0x01000000 /* Reverse unordered SELECTs */
9628 #define SQLITE_RecTriggers 0x02000000 /* Enable recursive triggers */
9629 #define SQLITE_ForeignKeys 0x04000000 /* Enforce foreign key constraints */
9630 #define SQLITE_AutoIndex 0x08000000 /* Enable automatic indexes */
9631 #define SQLITE_PreferBuiltin 0x10000000 /* Preference to built-in funcs */
9632 #define SQLITE_LoadExtension 0x20000000 /* Enable load_extension */
9633 #define SQLITE_EnableTrigger 0x40000000 /* True to enable triggers */
9636 ** Bits of the sqlite3.flags field that are used by the
9637 ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface.
9638 ** These must be the low-order bits of the flags field.
9640 #define SQLITE_QueryFlattener 0x01 /* Disable query flattening */
9641 #define SQLITE_ColumnCache 0x02 /* Disable the column cache */
9642 #define SQLITE_IndexSort 0x04 /* Disable indexes for sorting */
9643 #define SQLITE_IndexSearch 0x08 /* Disable indexes for searching */
9644 #define SQLITE_IndexCover 0x10 /* Disable index covering table */
9645 #define SQLITE_GroupByOrder 0x20 /* Disable GROUPBY cover of ORDERBY */
9646 #define SQLITE_FactorOutConst 0x40 /* Disable factoring out constants */
9647 #define SQLITE_IdxRealAsInt 0x80 /* Store REAL as INT in indices */
9648 #define SQLITE_DistinctOpt 0x80 /* DISTINCT using indexes */
9649 #define SQLITE_OptMask 0xff /* Mask of all disablable opts */
9652 ** Possible values for the sqlite.magic field.
9653 ** The numbers are obtained at random and have no special meaning, other
9654 ** than being distinct from one another.
9656 #define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */
9657 #define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */
9658 #define SQLITE_MAGIC_SICK 0x4b771290 /* Error and awaiting close */
9659 #define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */
9660 #define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */
9663 ** Each SQL function is defined by an instance of the following
9664 ** structure. A pointer to this structure is stored in the sqlite.aFunc
9665 ** hash table. When multiple functions have the same name, the hash table
9666 ** points to a linked list of these structures.
9668 struct FuncDef {
9669 i16 nArg; /* Number of arguments. -1 means unlimited */
9670 u8 iPrefEnc; /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
9671 u8 flags; /* Some combination of SQLITE_FUNC_* */
9672 void *pUserData; /* User data parameter */
9673 FuncDef *pNext; /* Next function with same name */
9674 void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
9675 void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
9676 void (*xFinalize)(sqlite3_context*); /* Aggregate finalizer */
9677 char *zName; /* SQL name of the function. */
9678 FuncDef *pHash; /* Next with a different name but the same hash */
9679 FuncDestructor *pDestructor; /* Reference counted destructor function */
9683 ** This structure encapsulates a user-function destructor callback (as
9684 ** configured using create_function_v2()) and a reference counter. When
9685 ** create_function_v2() is called to create a function with a destructor,
9686 ** a single object of this type is allocated. FuncDestructor.nRef is set to
9687 ** the number of FuncDef objects created (either 1 or 3, depending on whether
9688 ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
9689 ** member of each of the new FuncDef objects is set to point to the allocated
9690 ** FuncDestructor.
9692 ** Thereafter, when one of the FuncDef objects is deleted, the reference
9693 ** count on this object is decremented. When it reaches 0, the destructor
9694 ** is invoked and the FuncDestructor structure freed.
9696 struct FuncDestructor {
9697 int nRef;
9698 void (*xDestroy)(void *);
9699 void *pUserData;
9703 ** Possible values for FuncDef.flags
9705 #define SQLITE_FUNC_LIKE 0x01 /* Candidate for the LIKE optimization */
9706 #define SQLITE_FUNC_CASE 0x02 /* Case-sensitive LIKE-type function */
9707 #define SQLITE_FUNC_EPHEM 0x04 /* Ephemeral. Delete with VDBE */
9708 #define SQLITE_FUNC_NEEDCOLL 0x08 /* sqlite3GetFuncCollSeq() might be called */
9709 #define SQLITE_FUNC_PRIVATE 0x10 /* Allowed for internal use only */
9710 #define SQLITE_FUNC_COUNT 0x20 /* Built-in count(*) aggregate */
9711 #define SQLITE_FUNC_COALESCE 0x40 /* Built-in coalesce() or ifnull() function */
9714 ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
9715 ** used to create the initializers for the FuncDef structures.
9717 ** FUNCTION(zName, nArg, iArg, bNC, xFunc)
9718 ** Used to create a scalar function definition of a function zName
9719 ** implemented by C function xFunc that accepts nArg arguments. The
9720 ** value passed as iArg is cast to a (void*) and made available
9721 ** as the user-data (sqlite3_user_data()) for the function. If
9722 ** argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
9724 ** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
9725 ** Used to create an aggregate function definition implemented by
9726 ** the C functions xStep and xFinal. The first four parameters
9727 ** are interpreted in the same way as the first 4 parameters to
9728 ** FUNCTION().
9730 ** LIKEFUNC(zName, nArg, pArg, flags)
9731 ** Used to create a scalar function definition of a function zName
9732 ** that accepts nArg arguments and is implemented by a call to C
9733 ** function likeFunc. Argument pArg is cast to a (void *) and made
9734 ** available as the function user-data (sqlite3_user_data()). The
9735 ** FuncDef.flags variable is set to the value passed as the flags
9736 ** parameter.
9738 #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
9739 {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
9740 SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
9741 #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
9742 {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
9743 pArg, 0, xFunc, 0, 0, #zName, 0, 0}
9744 #define LIKEFUNC(zName, nArg, arg, flags) \
9745 {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0}
9746 #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
9747 {nArg, SQLITE_UTF8, nc*SQLITE_FUNC_NEEDCOLL, \
9748 SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
9751 ** All current savepoints are stored in a linked list starting at
9752 ** sqlite3.pSavepoint. The first element in the list is the most recently
9753 ** opened savepoint. Savepoints are added to the list by the vdbe
9754 ** OP_Savepoint instruction.
9756 struct Savepoint {
9757 char *zName; /* Savepoint name (nul-terminated) */
9758 i64 nDeferredCons; /* Number of deferred fk violations */
9759 Savepoint *pNext; /* Parent savepoint (if any) */
9763 ** The following are used as the second parameter to sqlite3Savepoint(),
9764 ** and as the P1 argument to the OP_Savepoint instruction.
9766 #define SAVEPOINT_BEGIN 0
9767 #define SAVEPOINT_RELEASE 1
9768 #define SAVEPOINT_ROLLBACK 2
9772 ** Each SQLite module (virtual table definition) is defined by an
9773 ** instance of the following structure, stored in the sqlite3.aModule
9774 ** hash table.
9776 struct Module {
9777 const sqlite3_module *pModule; /* Callback pointers */
9778 const char *zName; /* Name passed to create_module() */
9779 void *pAux; /* pAux passed to create_module() */
9780 void (*xDestroy)(void *); /* Module destructor function */
9784 ** information about each column of an SQL table is held in an instance
9785 ** of this structure.
9787 struct Column {
9788 char *zName; /* Name of this column */
9789 Expr *pDflt; /* Default value of this column */
9790 char *zDflt; /* Original text of the default value */
9791 char *zType; /* Data type for this column */
9792 char *zColl; /* Collating sequence. If NULL, use the default */
9793 u8 notNull; /* True if there is a NOT NULL constraint */
9794 u8 isPrimKey; /* True if this column is part of the PRIMARY KEY */
9795 char affinity; /* One of the SQLITE_AFF_... values */
9796 #ifndef SQLITE_OMIT_VIRTUALTABLE
9797 u8 isHidden; /* True if this column is 'hidden' */
9798 #endif
9802 ** A "Collating Sequence" is defined by an instance of the following
9803 ** structure. Conceptually, a collating sequence consists of a name and
9804 ** a comparison routine that defines the order of that sequence.
9806 ** There may two separate implementations of the collation function, one
9807 ** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that
9808 ** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine
9809 ** native byte order. When a collation sequence is invoked, SQLite selects
9810 ** the version that will require the least expensive encoding
9811 ** translations, if any.
9813 ** The CollSeq.pUser member variable is an extra parameter that passed in
9814 ** as the first argument to the UTF-8 comparison function, xCmp.
9815 ** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function,
9816 ** xCmp16.
9818 ** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the
9819 ** collating sequence is undefined. Indices built on an undefined
9820 ** collating sequence may not be read or written.
9822 struct CollSeq {
9823 char *zName; /* Name of the collating sequence, UTF-8 encoded */
9824 u8 enc; /* Text encoding handled by xCmp() */
9825 u8 type; /* One of the SQLITE_COLL_... values below */
9826 void *pUser; /* First argument to xCmp() */
9827 int (*xCmp)(void*,int, const void*, int, const void*);
9828 void (*xDel)(void*); /* Destructor for pUser */
9832 ** Allowed values of CollSeq.type:
9834 #define SQLITE_COLL_BINARY 1 /* The default memcmp() collating sequence */
9835 #define SQLITE_COLL_NOCASE 2 /* The built-in NOCASE collating sequence */
9836 #define SQLITE_COLL_REVERSE 3 /* The built-in REVERSE collating sequence */
9837 #define SQLITE_COLL_USER 0 /* Any other user-defined collating sequence */
9840 ** A sort order can be either ASC or DESC.
9842 #define SQLITE_SO_ASC 0 /* Sort in ascending order */
9843 #define SQLITE_SO_DESC 1 /* Sort in ascending order */
9846 ** Column affinity types.
9848 ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
9849 ** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve
9850 ** the speed a little by numbering the values consecutively.
9852 ** But rather than start with 0 or 1, we begin with 'a'. That way,
9853 ** when multiple affinity types are concatenated into a string and
9854 ** used as the P4 operand, they will be more readable.
9856 ** Note also that the numeric types are grouped together so that testing
9857 ** for a numeric type is a single comparison.
9859 #define SQLITE_AFF_TEXT 'a'
9860 #define SQLITE_AFF_NONE 'b'
9861 #define SQLITE_AFF_NUMERIC 'c'
9862 #define SQLITE_AFF_INTEGER 'd'
9863 #define SQLITE_AFF_REAL 'e'
9865 #define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC)
9868 ** The SQLITE_AFF_MASK values masks off the significant bits of an
9869 ** affinity value.
9871 #define SQLITE_AFF_MASK 0x67
9874 ** Additional bit values that can be ORed with an affinity without
9875 ** changing the affinity.
9877 #define SQLITE_JUMPIFNULL 0x08 /* jumps if either operand is NULL */
9878 #define SQLITE_STOREP2 0x10 /* Store result in reg[P2] rather than jump */
9879 #define SQLITE_NULLEQ 0x80 /* NULL=NULL */
9882 ** An object of this type is created for each virtual table present in
9883 ** the database schema.
9885 ** If the database schema is shared, then there is one instance of this
9886 ** structure for each database connection (sqlite3*) that uses the shared
9887 ** schema. This is because each database connection requires its own unique
9888 ** instance of the sqlite3_vtab* handle used to access the virtual table
9889 ** implementation. sqlite3_vtab* handles can not be shared between
9890 ** database connections, even when the rest of the in-memory database
9891 ** schema is shared, as the implementation often stores the database
9892 ** connection handle passed to it via the xConnect() or xCreate() method
9893 ** during initialization internally. This database connection handle may
9894 ** then be used by the virtual table implementation to access real tables
9895 ** within the database. So that they appear as part of the callers
9896 ** transaction, these accesses need to be made via the same database
9897 ** connection as that used to execute SQL operations on the virtual table.
9899 ** All VTable objects that correspond to a single table in a shared
9900 ** database schema are initially stored in a linked-list pointed to by
9901 ** the Table.pVTable member variable of the corresponding Table object.
9902 ** When an sqlite3_prepare() operation is required to access the virtual
9903 ** table, it searches the list for the VTable that corresponds to the
9904 ** database connection doing the preparing so as to use the correct
9905 ** sqlite3_vtab* handle in the compiled query.
9907 ** When an in-memory Table object is deleted (for example when the
9908 ** schema is being reloaded for some reason), the VTable objects are not
9909 ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
9910 ** immediately. Instead, they are moved from the Table.pVTable list to
9911 ** another linked list headed by the sqlite3.pDisconnect member of the
9912 ** corresponding sqlite3 structure. They are then deleted/xDisconnected
9913 ** next time a statement is prepared using said sqlite3*. This is done
9914 ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
9915 ** Refer to comments above function sqlite3VtabUnlockList() for an
9916 ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
9917 ** list without holding the corresponding sqlite3.mutex mutex.
9919 ** The memory for objects of this type is always allocated by
9920 ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
9921 ** the first argument.
9923 struct VTable {
9924 sqlite3 *db; /* Database connection associated with this table */
9925 Module *pMod; /* Pointer to module implementation */
9926 sqlite3_vtab *pVtab; /* Pointer to vtab instance */
9927 int nRef; /* Number of pointers to this structure */
9928 u8 bConstraint; /* True if constraints are supported */
9929 int iSavepoint; /* Depth of the SAVEPOINT stack */
9930 VTable *pNext; /* Next in linked list (see above) */
9934 ** Each SQL table is represented in memory by an instance of the
9935 ** following structure.
9937 ** Table.zName is the name of the table. The case of the original
9938 ** CREATE TABLE statement is stored, but case is not significant for
9939 ** comparisons.
9941 ** Table.nCol is the number of columns in this table. Table.aCol is a
9942 ** pointer to an array of Column structures, one for each column.
9944 ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
9945 ** the column that is that key. Otherwise Table.iPKey is negative. Note
9946 ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
9947 ** be set. An INTEGER PRIMARY KEY is used as the rowid for each row of
9948 ** the table. If a table has no INTEGER PRIMARY KEY, then a random rowid
9949 ** is generated for each row of the table. TF_HasPrimaryKey is set if
9950 ** the table has any PRIMARY KEY, INTEGER or otherwise.
9952 ** Table.tnum is the page number for the root BTree page of the table in the
9953 ** database file. If Table.iDb is the index of the database table backend
9954 ** in sqlite.aDb[]. 0 is for the main database and 1 is for the file that
9955 ** holds temporary tables and indices. If TF_Ephemeral is set
9956 ** then the table is stored in a file that is automatically deleted
9957 ** when the VDBE cursor to the table is closed. In this case Table.tnum
9958 ** refers VDBE cursor number that holds the table open, not to the root
9959 ** page number. Transient tables are used to hold the results of a
9960 ** sub-query that appears instead of a real table name in the FROM clause
9961 ** of a SELECT statement.
9963 struct Table {
9964 char *zName; /* Name of the table or view */
9965 int iPKey; /* If not negative, use aCol[iPKey] as the primary key */
9966 int nCol; /* Number of columns in this table */
9967 Column *aCol; /* Information about each column */
9968 Index *pIndex; /* List of SQL indexes on this table. */
9969 int tnum; /* Root BTree node for this table (see note above) */
9970 tRowcnt nRowEst; /* Estimated rows in table - from sqlite_stat1 table */
9971 Select *pSelect; /* NULL for tables. Points to definition if a view. */
9972 u16 nRef; /* Number of pointers to this Table */
9973 u8 tabFlags; /* Mask of TF_* values */
9974 u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */
9975 FKey *pFKey; /* Linked list of all foreign keys in this table */
9976 char *zColAff; /* String defining the affinity of each column */
9977 #ifndef SQLITE_OMIT_CHECK
9978 Expr *pCheck; /* The AND of all CHECK constraints */
9979 #endif
9980 #ifndef SQLITE_OMIT_ALTERTABLE
9981 int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */
9982 #endif
9983 #ifndef SQLITE_OMIT_VIRTUALTABLE
9984 VTable *pVTable; /* List of VTable objects. */
9985 int nModuleArg; /* Number of arguments to the module */
9986 char **azModuleArg; /* Text of all module args. [0] is module name */
9987 #endif
9988 Trigger *pTrigger; /* List of triggers stored in pSchema */
9989 Schema *pSchema; /* Schema that contains this table */
9990 Table *pNextZombie; /* Next on the Parse.pZombieTab list */
9994 ** Allowed values for Tabe.tabFlags.
9996 #define TF_Readonly 0x01 /* Read-only system table */
9997 #define TF_Ephemeral 0x02 /* An ephemeral table */
9998 #define TF_HasPrimaryKey 0x04 /* Table has a primary key */
9999 #define TF_Autoincrement 0x08 /* Integer primary key is autoincrement */
10000 #define TF_Virtual 0x10 /* Is a virtual table */
10001 #define TF_NeedMetadata 0x20 /* aCol[].zType and aCol[].pColl missing */
10006 ** Test to see whether or not a table is a virtual table. This is
10007 ** done as a macro so that it will be optimized out when virtual
10008 ** table support is omitted from the build.
10010 #ifndef SQLITE_OMIT_VIRTUALTABLE
10011 # define IsVirtual(X) (((X)->tabFlags & TF_Virtual)!=0)
10012 # define IsHiddenColumn(X) ((X)->isHidden)
10013 #else
10014 # define IsVirtual(X) 0
10015 # define IsHiddenColumn(X) 0
10016 #endif
10019 ** Each foreign key constraint is an instance of the following structure.
10021 ** A foreign key is associated with two tables. The "from" table is
10022 ** the table that contains the REFERENCES clause that creates the foreign
10023 ** key. The "to" table is the table that is named in the REFERENCES clause.
10024 ** Consider this example:
10026 ** CREATE TABLE ex1(
10027 ** a INTEGER PRIMARY KEY,
10028 ** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
10029 ** );
10031 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
10033 ** Each REFERENCES clause generates an instance of the following structure
10034 ** which is attached to the from-table. The to-table need not exist when
10035 ** the from-table is created. The existence of the to-table is not checked.
10037 struct FKey {
10038 Table *pFrom; /* Table containing the REFERENCES clause (aka: Child) */
10039 FKey *pNextFrom; /* Next foreign key in pFrom */
10040 char *zTo; /* Name of table that the key points to (aka: Parent) */
10041 FKey *pNextTo; /* Next foreign key on table named zTo */
10042 FKey *pPrevTo; /* Previous foreign key on table named zTo */
10043 int nCol; /* Number of columns in this key */
10044 /* EV: R-30323-21917 */
10045 u8 isDeferred; /* True if constraint checking is deferred till COMMIT */
10046 u8 aAction[2]; /* ON DELETE and ON UPDATE actions, respectively */
10047 Trigger *apTrigger[2]; /* Triggers for aAction[] actions */
10048 struct sColMap { /* Mapping of columns in pFrom to columns in zTo */
10049 int iFrom; /* Index of column in pFrom */
10050 char *zCol; /* Name of column in zTo. If 0 use PRIMARY KEY */
10051 } aCol[1]; /* One entry for each of nCol column s */
10055 ** SQLite supports many different ways to resolve a constraint
10056 ** error. ROLLBACK processing means that a constraint violation
10057 ** causes the operation in process to fail and for the current transaction
10058 ** to be rolled back. ABORT processing means the operation in process
10059 ** fails and any prior changes from that one operation are backed out,
10060 ** but the transaction is not rolled back. FAIL processing means that
10061 ** the operation in progress stops and returns an error code. But prior
10062 ** changes due to the same operation are not backed out and no rollback
10063 ** occurs. IGNORE means that the particular row that caused the constraint
10064 ** error is not inserted or updated. Processing continues and no error
10065 ** is returned. REPLACE means that preexisting database rows that caused
10066 ** a UNIQUE constraint violation are removed so that the new insert or
10067 ** update can proceed. Processing continues and no error is reported.
10069 ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
10070 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
10071 ** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign
10072 ** key is set to NULL. CASCADE means that a DELETE or UPDATE of the
10073 ** referenced table row is propagated into the row that holds the
10074 ** foreign key.
10076 ** The following symbolic values are used to record which type
10077 ** of action to take.
10079 #define OE_None 0 /* There is no constraint to check */
10080 #define OE_Rollback 1 /* Fail the operation and rollback the transaction */
10081 #define OE_Abort 2 /* Back out changes but do no rollback transaction */
10082 #define OE_Fail 3 /* Stop the operation but leave all prior changes */
10083 #define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */
10084 #define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */
10086 #define OE_Restrict 6 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
10087 #define OE_SetNull 7 /* Set the foreign key value to NULL */
10088 #define OE_SetDflt 8 /* Set the foreign key value to its default */
10089 #define OE_Cascade 9 /* Cascade the changes */
10091 #define OE_Default 99 /* Do whatever the default action is */
10095 ** An instance of the following structure is passed as the first
10096 ** argument to sqlite3VdbeKeyCompare and is used to control the
10097 ** comparison of the two index keys.
10099 struct KeyInfo {
10100 sqlite3 *db; /* The database connection */
10101 u8 enc; /* Text encoding - one of the SQLITE_UTF* values */
10102 u16 nField; /* Number of entries in aColl[] */
10103 u8 *aSortOrder; /* Sort order for each column. May be NULL */
10104 CollSeq *aColl[1]; /* Collating sequence for each term of the key */
10108 ** An instance of the following structure holds information about a
10109 ** single index record that has already been parsed out into individual
10110 ** values.
10112 ** A record is an object that contains one or more fields of data.
10113 ** Records are used to store the content of a table row and to store
10114 ** the key of an index. A blob encoding of a record is created by
10115 ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
10116 ** OP_Column opcode.
10118 ** This structure holds a record that has already been disassembled
10119 ** into its constituent fields.
10121 struct UnpackedRecord {
10122 KeyInfo *pKeyInfo; /* Collation and sort-order information */
10123 u16 nField; /* Number of entries in apMem[] */
10124 u16 flags; /* Boolean settings. UNPACKED_... below */
10125 i64 rowid; /* Used by UNPACKED_PREFIX_SEARCH */
10126 Mem *aMem; /* Values */
10130 ** Allowed values of UnpackedRecord.flags
10132 #define UNPACKED_NEED_FREE 0x0001 /* Memory is from sqlite3Malloc() */
10133 #define UNPACKED_NEED_DESTROY 0x0002 /* apMem[]s should all be destroyed */
10134 #define UNPACKED_IGNORE_ROWID 0x0004 /* Ignore trailing rowid on key1 */
10135 #define UNPACKED_INCRKEY 0x0008 /* Make this key an epsilon larger */
10136 #define UNPACKED_PREFIX_MATCH 0x0010 /* A prefix match is considered OK */
10137 #define UNPACKED_PREFIX_SEARCH 0x0020 /* A prefix match is considered OK */
10140 ** Each SQL index is represented in memory by an
10141 ** instance of the following structure.
10143 ** The columns of the table that are to be indexed are described
10144 ** by the aiColumn[] field of this structure. For example, suppose
10145 ** we have the following table and index:
10147 ** CREATE TABLE Ex1(c1 int, c2 int, c3 text);
10148 ** CREATE INDEX Ex2 ON Ex1(c3,c1);
10150 ** In the Table structure describing Ex1, nCol==3 because there are
10151 ** three columns in the table. In the Index structure describing
10152 ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
10153 ** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the
10154 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
10155 ** The second column to be indexed (c1) has an index of 0 in
10156 ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
10158 ** The Index.onError field determines whether or not the indexed columns
10159 ** must be unique and what to do if they are not. When Index.onError=OE_None,
10160 ** it means this is not a unique index. Otherwise it is a unique index
10161 ** and the value of Index.onError indicate the which conflict resolution
10162 ** algorithm to employ whenever an attempt is made to insert a non-unique
10163 ** element.
10165 struct Index {
10166 char *zName; /* Name of this index */
10167 int nColumn; /* Number of columns in the table used by this index */
10168 int *aiColumn; /* Which columns are used by this index. 1st is 0 */
10169 tRowcnt *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */
10170 Table *pTable; /* The SQL table being indexed */
10171 int tnum; /* Page containing root of this index in database file */
10172 u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
10173 u8 autoIndex; /* True if is automatically created (ex: by UNIQUE) */
10174 u8 bUnordered; /* Use this index for == or IN queries only */
10175 char *zColAff; /* String defining the affinity of each column */
10176 Index *pNext; /* The next index associated with the same table */
10177 Schema *pSchema; /* Schema containing this index */
10178 u8 *aSortOrder; /* Array of size Index.nColumn. True==DESC, False==ASC */
10179 char **azColl; /* Array of collation sequence names for index */
10180 #ifdef SQLITE_ENABLE_STAT3
10181 int nSample; /* Number of elements in aSample[] */
10182 tRowcnt avgEq; /* Average nEq value for key values not in aSample */
10183 IndexSample *aSample; /* Samples of the left-most key */
10184 #endif
10188 ** Each sample stored in the sqlite_stat3 table is represented in memory
10189 ** using a structure of this type. See documentation at the top of the
10190 ** analyze.c source file for additional information.
10192 struct IndexSample {
10193 union {
10194 char *z; /* Value if eType is SQLITE_TEXT or SQLITE_BLOB */
10195 double r; /* Value if eType is SQLITE_FLOAT */
10196 i64 i; /* Value if eType is SQLITE_INTEGER */
10197 } u;
10198 u8 eType; /* SQLITE_NULL, SQLITE_INTEGER ... etc. */
10199 int nByte; /* Size in byte of text or blob. */
10200 tRowcnt nEq; /* Est. number of rows where the key equals this sample */
10201 tRowcnt nLt; /* Est. number of rows where key is less than this sample */
10202 tRowcnt nDLt; /* Est. number of distinct keys less than this sample */
10206 ** Each token coming out of the lexer is an instance of
10207 ** this structure. Tokens are also used as part of an expression.
10209 ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
10210 ** may contain random values. Do not make any assumptions about Token.dyn
10211 ** and Token.n when Token.z==0.
10213 struct Token {
10214 const char *z; /* Text of the token. Not NULL-terminated! */
10215 unsigned int n; /* Number of characters in this token */
10219 ** An instance of this structure contains information needed to generate
10220 ** code for a SELECT that contains aggregate functions.
10222 ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
10223 ** pointer to this structure. The Expr.iColumn field is the index in
10224 ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
10225 ** code for that node.
10227 ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
10228 ** original Select structure that describes the SELECT statement. These
10229 ** fields do not need to be freed when deallocating the AggInfo structure.
10231 struct AggInfo {
10232 u8 directMode; /* Direct rendering mode means take data directly
10233 ** from source tables rather than from accumulators */
10234 u8 useSortingIdx; /* In direct mode, reference the sorting index rather
10235 ** than the source table */
10236 int sortingIdx; /* Cursor number of the sorting index */
10237 int sortingIdxPTab; /* Cursor number of pseudo-table */
10238 ExprList *pGroupBy; /* The group by clause */
10239 int nSortingColumn; /* Number of columns in the sorting index */
10240 struct AggInfo_col { /* For each column used in source tables */
10241 Table *pTab; /* Source table */
10242 int iTable; /* Cursor number of the source table */
10243 int iColumn; /* Column number within the source table */
10244 int iSorterColumn; /* Column number in the sorting index */
10245 int iMem; /* Memory location that acts as accumulator */
10246 Expr *pExpr; /* The original expression */
10247 } *aCol;
10248 int nColumn; /* Number of used entries in aCol[] */
10249 int nColumnAlloc; /* Number of slots allocated for aCol[] */
10250 int nAccumulator; /* Number of columns that show through to the output.
10251 ** Additional columns are used only as parameters to
10252 ** aggregate functions */
10253 struct AggInfo_func { /* For each aggregate function */
10254 Expr *pExpr; /* Expression encoding the function */
10255 FuncDef *pFunc; /* The aggregate function implementation */
10256 int iMem; /* Memory location that acts as accumulator */
10257 int iDistinct; /* Ephemeral table used to enforce DISTINCT */
10258 } *aFunc;
10259 int nFunc; /* Number of entries in aFunc[] */
10260 int nFuncAlloc; /* Number of slots allocated for aFunc[] */
10264 ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
10265 ** Usually it is 16-bits. But if SQLITE_MAX_VARIABLE_NUMBER is greater
10266 ** than 32767 we have to make it 32-bit. 16-bit is preferred because
10267 ** it uses less memory in the Expr object, which is a big memory user
10268 ** in systems with lots of prepared statements. And few applications
10269 ** need more than about 10 or 20 variables. But some extreme users want
10270 ** to have prepared statements with over 32767 variables, and for them
10271 ** the option is available (at compile-time).
10273 #if SQLITE_MAX_VARIABLE_NUMBER<=32767
10274 typedef i16 ynVar;
10275 #else
10276 typedef int ynVar;
10277 #endif
10280 ** Each node of an expression in the parse tree is an instance
10281 ** of this structure.
10283 ** Expr.op is the opcode. The integer parser token codes are reused
10284 ** as opcodes here. For example, the parser defines TK_GE to be an integer
10285 ** code representing the ">=" operator. This same integer code is reused
10286 ** to represent the greater-than-or-equal-to operator in the expression
10287 ** tree.
10289 ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
10290 ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
10291 ** the expression is a variable (TK_VARIABLE), then Expr.token contains the
10292 ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
10293 ** then Expr.token contains the name of the function.
10295 ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
10296 ** binary operator. Either or both may be NULL.
10298 ** Expr.x.pList is a list of arguments if the expression is an SQL function,
10299 ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
10300 ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
10301 ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
10302 ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
10303 ** valid.
10305 ** An expression of the form ID or ID.ID refers to a column in a table.
10306 ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
10307 ** the integer cursor number of a VDBE cursor pointing to that table and
10308 ** Expr.iColumn is the column number for the specific column. If the
10309 ** expression is used as a result in an aggregate SELECT, then the
10310 ** value is also stored in the Expr.iAgg column in the aggregate so that
10311 ** it can be accessed after all aggregates are computed.
10313 ** If the expression is an unbound variable marker (a question mark
10314 ** character '?' in the original SQL) then the Expr.iTable holds the index
10315 ** number for that variable.
10317 ** If the expression is a subquery then Expr.iColumn holds an integer
10318 ** register number containing the result of the subquery. If the
10319 ** subquery gives a constant result, then iTable is -1. If the subquery
10320 ** gives a different answer at different times during statement processing
10321 ** then iTable is the address of a subroutine that computes the subquery.
10323 ** If the Expr is of type OP_Column, and the table it is selecting from
10324 ** is a disk table or the "old.*" pseudo-table, then pTab points to the
10325 ** corresponding table definition.
10327 ** ALLOCATION NOTES:
10329 ** Expr objects can use a lot of memory space in database schema. To
10330 ** help reduce memory requirements, sometimes an Expr object will be
10331 ** truncated. And to reduce the number of memory allocations, sometimes
10332 ** two or more Expr objects will be stored in a single memory allocation,
10333 ** together with Expr.zToken strings.
10335 ** If the EP_Reduced and EP_TokenOnly flags are set when
10336 ** an Expr object is truncated. When EP_Reduced is set, then all
10337 ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
10338 ** are contained within the same memory allocation. Note, however, that
10339 ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
10340 ** allocated, regardless of whether or not EP_Reduced is set.
10342 struct Expr {
10343 u8 op; /* Operation performed by this node */
10344 char affinity; /* The affinity of the column or 0 if not a column */
10345 u16 flags; /* Various flags. EP_* See below */
10346 union {
10347 char *zToken; /* Token value. Zero terminated and dequoted */
10348 int iValue; /* Non-negative integer value if EP_IntValue */
10349 } u;
10351 /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
10352 ** space is allocated for the fields below this point. An attempt to
10353 ** access them will result in a segfault or malfunction.
10354 *********************************************************************/
10356 Expr *pLeft; /* Left subnode */
10357 Expr *pRight; /* Right subnode */
10358 union {
10359 ExprList *pList; /* Function arguments or in "<expr> IN (<expr-list)" */
10360 Select *pSelect; /* Used for sub-selects and "<expr> IN (<select>)" */
10361 } x;
10362 CollSeq *pColl; /* The collation type of the column or 0 */
10364 /* If the EP_Reduced flag is set in the Expr.flags mask, then no
10365 ** space is allocated for the fields below this point. An attempt to
10366 ** access them will result in a segfault or malfunction.
10367 *********************************************************************/
10369 int iTable; /* TK_COLUMN: cursor number of table holding column
10370 ** TK_REGISTER: register number
10371 ** TK_TRIGGER: 1 -> new, 0 -> old */
10372 ynVar iColumn; /* TK_COLUMN: column index. -1 for rowid.
10373 ** TK_VARIABLE: variable number (always >= 1). */
10374 i16 iAgg; /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
10375 i16 iRightJoinTable; /* If EP_FromJoin, the right table of the join */
10376 u8 flags2; /* Second set of flags. EP2_... */
10377 u8 op2; /* If a TK_REGISTER, the original value of Expr.op */
10378 AggInfo *pAggInfo; /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
10379 Table *pTab; /* Table for TK_COLUMN expressions. */
10380 #if SQLITE_MAX_EXPR_DEPTH>0
10381 int nHeight; /* Height of the tree headed by this node */
10382 #endif
10386 ** The following are the meanings of bits in the Expr.flags field.
10388 #define EP_FromJoin 0x0001 /* Originated in ON or USING clause of a join */
10389 #define EP_Agg 0x0002 /* Contains one or more aggregate functions */
10390 #define EP_Resolved 0x0004 /* IDs have been resolved to COLUMNs */
10391 #define EP_Error 0x0008 /* Expression contains one or more errors */
10392 #define EP_Distinct 0x0010 /* Aggregate function with DISTINCT keyword */
10393 #define EP_VarSelect 0x0020 /* pSelect is correlated, not constant */
10394 #define EP_DblQuoted 0x0040 /* token.z was originally in "..." */
10395 #define EP_InfixFunc 0x0080 /* True for an infix function: LIKE, GLOB, etc */
10396 #define EP_ExpCollate 0x0100 /* Collating sequence specified explicitly */
10397 #define EP_FixedDest 0x0200 /* Result needed in a specific register */
10398 #define EP_IntValue 0x0400 /* Integer value contained in u.iValue */
10399 #define EP_xIsSelect 0x0800 /* x.pSelect is valid (otherwise x.pList is) */
10401 #define EP_Reduced 0x1000 /* Expr struct is EXPR_REDUCEDSIZE bytes only */
10402 #define EP_TokenOnly 0x2000 /* Expr struct is EXPR_TOKENONLYSIZE bytes only */
10403 #define EP_Static 0x4000 /* Held in memory not obtained from malloc() */
10406 ** The following are the meanings of bits in the Expr.flags2 field.
10408 #define EP2_MallocedToken 0x0001 /* Need to sqlite3DbFree() Expr.zToken */
10409 #define EP2_Irreducible 0x0002 /* Cannot EXPRDUP_REDUCE this Expr */
10412 ** The pseudo-routine sqlite3ExprSetIrreducible sets the EP2_Irreducible
10413 ** flag on an expression structure. This flag is used for VV&A only. The
10414 ** routine is implemented as a macro that only works when in debugging mode,
10415 ** so as not to burden production code.
10417 #ifdef SQLITE_DEBUG
10418 # define ExprSetIrreducible(X) (X)->flags2 |= EP2_Irreducible
10419 #else
10420 # define ExprSetIrreducible(X)
10421 #endif
10424 ** These macros can be used to test, set, or clear bits in the
10425 ** Expr.flags field.
10427 #define ExprHasProperty(E,P) (((E)->flags&(P))==(P))
10428 #define ExprHasAnyProperty(E,P) (((E)->flags&(P))!=0)
10429 #define ExprSetProperty(E,P) (E)->flags|=(P)
10430 #define ExprClearProperty(E,P) (E)->flags&=~(P)
10433 ** Macros to determine the number of bytes required by a normal Expr
10434 ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
10435 ** and an Expr struct with the EP_TokenOnly flag set.
10437 #define EXPR_FULLSIZE sizeof(Expr) /* Full size */
10438 #define EXPR_REDUCEDSIZE offsetof(Expr,iTable) /* Common features */
10439 #define EXPR_TOKENONLYSIZE offsetof(Expr,pLeft) /* Fewer features */
10442 ** Flags passed to the sqlite3ExprDup() function. See the header comment
10443 ** above sqlite3ExprDup() for details.
10445 #define EXPRDUP_REDUCE 0x0001 /* Used reduced-size Expr nodes */
10448 ** A list of expressions. Each expression may optionally have a
10449 ** name. An expr/name combination can be used in several ways, such
10450 ** as the list of "expr AS ID" fields following a "SELECT" or in the
10451 ** list of "ID = expr" items in an UPDATE. A list of expressions can
10452 ** also be used as the argument to a function, in which case the a.zName
10453 ** field is not used.
10455 struct ExprList {
10456 int nExpr; /* Number of expressions on the list */
10457 int nAlloc; /* Number of entries allocated below */
10458 int iECursor; /* VDBE Cursor associated with this ExprList */
10459 struct ExprList_item {
10460 Expr *pExpr; /* The list of expressions */
10461 char *zName; /* Token associated with this expression */
10462 char *zSpan; /* Original text of the expression */
10463 u8 sortOrder; /* 1 for DESC or 0 for ASC */
10464 u8 done; /* A flag to indicate when processing is finished */
10465 u16 iCol; /* For ORDER BY, column number in result set */
10466 u16 iAlias; /* Index into Parse.aAlias[] for zName */
10467 } *a; /* One entry for each expression */
10471 ** An instance of this structure is used by the parser to record both
10472 ** the parse tree for an expression and the span of input text for an
10473 ** expression.
10475 struct ExprSpan {
10476 Expr *pExpr; /* The expression parse tree */
10477 const char *zStart; /* First character of input text */
10478 const char *zEnd; /* One character past the end of input text */
10482 ** An instance of this structure can hold a simple list of identifiers,
10483 ** such as the list "a,b,c" in the following statements:
10485 ** INSERT INTO t(a,b,c) VALUES ...;
10486 ** CREATE INDEX idx ON t(a,b,c);
10487 ** CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
10489 ** The IdList.a.idx field is used when the IdList represents the list of
10490 ** column names after a table name in an INSERT statement. In the statement
10492 ** INSERT INTO t(a,b,c) ...
10494 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
10496 struct IdList {
10497 struct IdList_item {
10498 char *zName; /* Name of the identifier */
10499 int idx; /* Index in some Table.aCol[] of a column named zName */
10500 } *a;
10501 int nId; /* Number of identifiers on the list */
10502 int nAlloc; /* Number of entries allocated for a[] below */
10506 ** The bitmask datatype defined below is used for various optimizations.
10508 ** Changing this from a 64-bit to a 32-bit type limits the number of
10509 ** tables in a join to 32 instead of 64. But it also reduces the size
10510 ** of the library by 738 bytes on ix86.
10512 typedef u64 Bitmask;
10515 ** The number of bits in a Bitmask. "BMS" means "BitMask Size".
10517 #define BMS ((int)(sizeof(Bitmask)*8))
10520 ** The following structure describes the FROM clause of a SELECT statement.
10521 ** Each table or subquery in the FROM clause is a separate element of
10522 ** the SrcList.a[] array.
10524 ** With the addition of multiple database support, the following structure
10525 ** can also be used to describe a particular table such as the table that
10526 ** is modified by an INSERT, DELETE, or UPDATE statement. In standard SQL,
10527 ** such a table must be a simple name: ID. But in SQLite, the table can
10528 ** now be identified by a database name, a dot, then the table name: ID.ID.
10530 ** The jointype starts out showing the join type between the current table
10531 ** and the next table on the list. The parser builds the list this way.
10532 ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
10533 ** jointype expresses the join between the table and the previous table.
10535 ** In the colUsed field, the high-order bit (bit 63) is set if the table
10536 ** contains more than 63 columns and the 64-th or later column is used.
10538 struct SrcList {
10539 i16 nSrc; /* Number of tables or subqueries in the FROM clause */
10540 i16 nAlloc; /* Number of entries allocated in a[] below */
10541 struct SrcList_item {
10542 char *zDatabase; /* Name of database holding this table */
10543 char *zName; /* Name of the table */
10544 char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */
10545 Table *pTab; /* An SQL table corresponding to zName */
10546 Select *pSelect; /* A SELECT statement used in place of a table name */
10547 int addrFillSub; /* Address of subroutine to manifest a subquery */
10548 int regReturn; /* Register holding return address of addrFillSub */
10549 u8 jointype; /* Type of join between this able and the previous */
10550 u8 notIndexed; /* True if there is a NOT INDEXED clause */
10551 u8 isCorrelated; /* True if sub-query is correlated */
10552 #ifndef SQLITE_OMIT_EXPLAIN
10553 u8 iSelectId; /* If pSelect!=0, the id of the sub-select in EQP */
10554 #endif
10555 int iCursor; /* The VDBE cursor number used to access this table */
10556 Expr *pOn; /* The ON clause of a join */
10557 IdList *pUsing; /* The USING clause of a join */
10558 Bitmask colUsed; /* Bit N (1<<N) set if column N of pTab is used */
10559 char *zIndex; /* Identifier from "INDEXED BY <zIndex>" clause */
10560 Index *pIndex; /* Index structure corresponding to zIndex, if any */
10561 } a[1]; /* One entry for each identifier on the list */
10565 ** Permitted values of the SrcList.a.jointype field
10567 #define JT_INNER 0x0001 /* Any kind of inner or cross join */
10568 #define JT_CROSS 0x0002 /* Explicit use of the CROSS keyword */
10569 #define JT_NATURAL 0x0004 /* True for a "natural" join */
10570 #define JT_LEFT 0x0008 /* Left outer join */
10571 #define JT_RIGHT 0x0010 /* Right outer join */
10572 #define JT_OUTER 0x0020 /* The "OUTER" keyword is present */
10573 #define JT_ERROR 0x0040 /* unknown or unsupported join type */
10577 ** A WherePlan object holds information that describes a lookup
10578 ** strategy.
10580 ** This object is intended to be opaque outside of the where.c module.
10581 ** It is included here only so that that compiler will know how big it
10582 ** is. None of the fields in this object should be used outside of
10583 ** the where.c module.
10585 ** Within the union, pIdx is only used when wsFlags&WHERE_INDEXED is true.
10586 ** pTerm is only used when wsFlags&WHERE_MULTI_OR is true. And pVtabIdx
10587 ** is only used when wsFlags&WHERE_VIRTUALTABLE is true. It is never the
10588 ** case that more than one of these conditions is true.
10590 struct WherePlan {
10591 u32 wsFlags; /* WHERE_* flags that describe the strategy */
10592 u32 nEq; /* Number of == constraints */
10593 double nRow; /* Estimated number of rows (for EQP) */
10594 union {
10595 Index *pIdx; /* Index when WHERE_INDEXED is true */
10596 struct WhereTerm *pTerm; /* WHERE clause term for OR-search */
10597 sqlite3_index_info *pVtabIdx; /* Virtual table index to use */
10598 } u;
10602 ** For each nested loop in a WHERE clause implementation, the WhereInfo
10603 ** structure contains a single instance of this structure. This structure
10604 ** is intended to be private the the where.c module and should not be
10605 ** access or modified by other modules.
10607 ** The pIdxInfo field is used to help pick the best index on a
10608 ** virtual table. The pIdxInfo pointer contains indexing
10609 ** information for the i-th table in the FROM clause before reordering.
10610 ** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
10611 ** All other information in the i-th WhereLevel object for the i-th table
10612 ** after FROM clause ordering.
10614 struct WhereLevel {
10615 WherePlan plan; /* query plan for this element of the FROM clause */
10616 int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */
10617 int iTabCur; /* The VDBE cursor used to access the table */
10618 int iIdxCur; /* The VDBE cursor used to access pIdx */
10619 int addrBrk; /* Jump here to break out of the loop */
10620 int addrNxt; /* Jump here to start the next IN combination */
10621 int addrCont; /* Jump here to continue with the next loop cycle */
10622 int addrFirst; /* First instruction of interior of the loop */
10623 u8 iFrom; /* Which entry in the FROM clause */
10624 u8 op, p5; /* Opcode and P5 of the opcode that ends the loop */
10625 int p1, p2; /* Operands of the opcode used to ends the loop */
10626 union { /* Information that depends on plan.wsFlags */
10627 struct {
10628 int nIn; /* Number of entries in aInLoop[] */
10629 struct InLoop {
10630 int iCur; /* The VDBE cursor used by this IN operator */
10631 int addrInTop; /* Top of the IN loop */
10632 } *aInLoop; /* Information about each nested IN operator */
10633 } in; /* Used when plan.wsFlags&WHERE_IN_ABLE */
10634 } u;
10636 /* The following field is really not part of the current level. But
10637 ** we need a place to cache virtual table index information for each
10638 ** virtual table in the FROM clause and the WhereLevel structure is
10639 ** a convenient place since there is one WhereLevel for each FROM clause
10640 ** element.
10642 sqlite3_index_info *pIdxInfo; /* Index info for n-th source table */
10646 ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
10647 ** and the WhereInfo.wctrlFlags member.
10649 #define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */
10650 #define WHERE_ORDERBY_MIN 0x0001 /* ORDER BY processing for min() func */
10651 #define WHERE_ORDERBY_MAX 0x0002 /* ORDER BY processing for max() func */
10652 #define WHERE_ONEPASS_DESIRED 0x0004 /* Want to do one-pass UPDATE/DELETE */
10653 #define WHERE_DUPLICATES_OK 0x0008 /* Ok to return a row more than once */
10654 #define WHERE_OMIT_OPEN_CLOSE 0x0010 /* Table cursors are already open */
10655 #define WHERE_FORCE_TABLE 0x0020 /* Do not use an index-only search */
10656 #define WHERE_ONETABLE_ONLY 0x0040 /* Only code the 1st table in pTabList */
10657 #define WHERE_AND_ONLY 0x0080 /* Don't use indices for OR terms */
10660 ** The WHERE clause processing routine has two halves. The
10661 ** first part does the start of the WHERE loop and the second
10662 ** half does the tail of the WHERE loop. An instance of
10663 ** this structure is returned by the first half and passed
10664 ** into the second half to give some continuity.
10666 struct WhereInfo {
10667 Parse *pParse; /* Parsing and code generating context */
10668 u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */
10669 u8 okOnePass; /* Ok to use one-pass algorithm for UPDATE or DELETE */
10670 u8 untestedTerms; /* Not all WHERE terms resolved by outer loop */
10671 u8 eDistinct;
10672 SrcList *pTabList; /* List of tables in the join */
10673 int iTop; /* The very beginning of the WHERE loop */
10674 int iContinue; /* Jump here to continue with next record */
10675 int iBreak; /* Jump here to break out of the loop */
10676 int nLevel; /* Number of nested loop */
10677 struct WhereClause *pWC; /* Decomposition of the WHERE clause */
10678 double savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */
10679 double nRowOut; /* Estimated number of output rows */
10680 WhereLevel a[1]; /* Information about each nest loop in WHERE */
10683 #define WHERE_DISTINCT_UNIQUE 1
10684 #define WHERE_DISTINCT_ORDERED 2
10687 ** A NameContext defines a context in which to resolve table and column
10688 ** names. The context consists of a list of tables (the pSrcList) field and
10689 ** a list of named expression (pEList). The named expression list may
10690 ** be NULL. The pSrc corresponds to the FROM clause of a SELECT or
10691 ** to the table being operated on by INSERT, UPDATE, or DELETE. The
10692 ** pEList corresponds to the result set of a SELECT and is NULL for
10693 ** other statements.
10695 ** NameContexts can be nested. When resolving names, the inner-most
10696 ** context is searched first. If no match is found, the next outer
10697 ** context is checked. If there is still no match, the next context
10698 ** is checked. This process continues until either a match is found
10699 ** or all contexts are check. When a match is found, the nRef member of
10700 ** the context containing the match is incremented.
10702 ** Each subquery gets a new NameContext. The pNext field points to the
10703 ** NameContext in the parent query. Thus the process of scanning the
10704 ** NameContext list corresponds to searching through successively outer
10705 ** subqueries looking for a match.
10707 struct NameContext {
10708 Parse *pParse; /* The parser */
10709 SrcList *pSrcList; /* One or more tables used to resolve names */
10710 ExprList *pEList; /* Optional list of named expressions */
10711 int nRef; /* Number of names resolved by this context */
10712 int nErr; /* Number of errors encountered while resolving names */
10713 u8 allowAgg; /* Aggregate functions allowed here */
10714 u8 hasAgg; /* True if aggregates are seen */
10715 u8 isCheck; /* True if resolving names in a CHECK constraint */
10716 int nDepth; /* Depth of subquery recursion. 1 for no recursion */
10717 AggInfo *pAggInfo; /* Information about aggregates at this level */
10718 NameContext *pNext; /* Next outer name context. NULL for outermost */
10722 ** An instance of the following structure contains all information
10723 ** needed to generate code for a single SELECT statement.
10725 ** nLimit is set to -1 if there is no LIMIT clause. nOffset is set to 0.
10726 ** If there is a LIMIT clause, the parser sets nLimit to the value of the
10727 ** limit and nOffset to the value of the offset (or 0 if there is not
10728 ** offset). But later on, nLimit and nOffset become the memory locations
10729 ** in the VDBE that record the limit and offset counters.
10731 ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
10732 ** These addresses must be stored so that we can go back and fill in
10733 ** the P4_KEYINFO and P2 parameters later. Neither the KeyInfo nor
10734 ** the number of columns in P2 can be computed at the same time
10735 ** as the OP_OpenEphm instruction is coded because not
10736 ** enough information about the compound query is known at that point.
10737 ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
10738 ** for the result set. The KeyInfo for addrOpenTran[2] contains collating
10739 ** sequences for the ORDER BY clause.
10741 struct Select {
10742 ExprList *pEList; /* The fields of the result */
10743 u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
10744 char affinity; /* MakeRecord with this affinity for SRT_Set */
10745 u16 selFlags; /* Various SF_* values */
10746 SrcList *pSrc; /* The FROM clause */
10747 Expr *pWhere; /* The WHERE clause */
10748 ExprList *pGroupBy; /* The GROUP BY clause */
10749 Expr *pHaving; /* The HAVING clause */
10750 ExprList *pOrderBy; /* The ORDER BY clause */
10751 Select *pPrior; /* Prior select in a compound select statement */
10752 Select *pNext; /* Next select to the left in a compound */
10753 Select *pRightmost; /* Right-most select in a compound select statement */
10754 Expr *pLimit; /* LIMIT expression. NULL means not used. */
10755 Expr *pOffset; /* OFFSET expression. NULL means not used. */
10756 int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */
10757 int addrOpenEphm[3]; /* OP_OpenEphem opcodes related to this select */
10758 double nSelectRow; /* Estimated number of result rows */
10762 ** Allowed values for Select.selFlags. The "SF" prefix stands for
10763 ** "Select Flag".
10765 #define SF_Distinct 0x0001 /* Output should be DISTINCT */
10766 #define SF_Resolved 0x0002 /* Identifiers have been resolved */
10767 #define SF_Aggregate 0x0004 /* Contains aggregate functions */
10768 #define SF_UsesEphemeral 0x0008 /* Uses the OpenEphemeral opcode */
10769 #define SF_Expanded 0x0010 /* sqlite3SelectExpand() called on this */
10770 #define SF_HasTypeInfo 0x0020 /* FROM subqueries have Table metadata */
10771 #define SF_UseSorter 0x0040 /* Sort using a sorter */
10775 ** The results of a select can be distributed in several ways. The
10776 ** "SRT" prefix means "SELECT Result Type".
10778 #define SRT_Union 1 /* Store result as keys in an index */
10779 #define SRT_Except 2 /* Remove result from a UNION index */
10780 #define SRT_Exists 3 /* Store 1 if the result is not empty */
10781 #define SRT_Discard 4 /* Do not save the results anywhere */
10783 /* The ORDER BY clause is ignored for all of the above */
10784 #define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
10786 #define SRT_Output 5 /* Output each row of result */
10787 #define SRT_Mem 6 /* Store result in a memory cell */
10788 #define SRT_Set 7 /* Store results as keys in an index */
10789 #define SRT_Table 8 /* Store result as data with an automatic rowid */
10790 #define SRT_EphemTab 9 /* Create transient tab and store like SRT_Table */
10791 #define SRT_Coroutine 10 /* Generate a single row of result */
10794 ** A structure used to customize the behavior of sqlite3Select(). See
10795 ** comments above sqlite3Select() for details.
10797 typedef struct SelectDest SelectDest;
10798 struct SelectDest {
10799 u8 eDest; /* How to dispose of the results */
10800 u8 affinity; /* Affinity used when eDest==SRT_Set */
10801 int iParm; /* A parameter used by the eDest disposal method */
10802 int iMem; /* Base register where results are written */
10803 int nMem; /* Number of registers allocated */
10807 ** During code generation of statements that do inserts into AUTOINCREMENT
10808 ** tables, the following information is attached to the Table.u.autoInc.p
10809 ** pointer of each autoincrement table to record some side information that
10810 ** the code generator needs. We have to keep per-table autoincrement
10811 ** information in case inserts are down within triggers. Triggers do not
10812 ** normally coordinate their activities, but we do need to coordinate the
10813 ** loading and saving of autoincrement information.
10815 struct AutoincInfo {
10816 AutoincInfo *pNext; /* Next info block in a list of them all */
10817 Table *pTab; /* Table this info block refers to */
10818 int iDb; /* Index in sqlite3.aDb[] of database holding pTab */
10819 int regCtr; /* Memory register holding the rowid counter */
10823 ** Size of the column cache
10825 #ifndef SQLITE_N_COLCACHE
10826 # define SQLITE_N_COLCACHE 10
10827 #endif
10830 ** At least one instance of the following structure is created for each
10831 ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
10832 ** statement. All such objects are stored in the linked list headed at
10833 ** Parse.pTriggerPrg and deleted once statement compilation has been
10834 ** completed.
10836 ** A Vdbe sub-program that implements the body and WHEN clause of trigger
10837 ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
10838 ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
10839 ** The Parse.pTriggerPrg list never contains two entries with the same
10840 ** values for both pTrigger and orconf.
10842 ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
10843 ** accessed (or set to 0 for triggers fired as a result of INSERT
10844 ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
10845 ** a mask of new.* columns used by the program.
10847 struct TriggerPrg {
10848 Trigger *pTrigger; /* Trigger this program was coded from */
10849 int orconf; /* Default ON CONFLICT policy */
10850 SubProgram *pProgram; /* Program implementing pTrigger/orconf */
10851 u32 aColmask[2]; /* Masks of old.*, new.* columns accessed */
10852 TriggerPrg *pNext; /* Next entry in Parse.pTriggerPrg list */
10856 ** The yDbMask datatype for the bitmask of all attached databases.
10858 #if SQLITE_MAX_ATTACHED>30
10859 typedef sqlite3_uint64 yDbMask;
10860 #else
10861 typedef unsigned int yDbMask;
10862 #endif
10865 ** An SQL parser context. A copy of this structure is passed through
10866 ** the parser and down into all the parser action routine in order to
10867 ** carry around information that is global to the entire parse.
10869 ** The structure is divided into two parts. When the parser and code
10870 ** generate call themselves recursively, the first part of the structure
10871 ** is constant but the second part is reset at the beginning and end of
10872 ** each recursion.
10874 ** The nTableLock and aTableLock variables are only used if the shared-cache
10875 ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
10876 ** used to store the set of table-locks required by the statement being
10877 ** compiled. Function sqlite3TableLock() is used to add entries to the
10878 ** list.
10880 struct Parse {
10881 sqlite3 *db; /* The main database structure */
10882 int rc; /* Return code from execution */
10883 char *zErrMsg; /* An error message */
10884 Vdbe *pVdbe; /* An engine for executing database bytecode */
10885 u8 colNamesSet; /* TRUE after OP_ColumnName has been issued to pVdbe */
10886 u8 nameClash; /* A permanent table name clashes with temp table name */
10887 u8 checkSchema; /* Causes schema cookie check after an error */
10888 u8 nested; /* Number of nested calls to the parser/code generator */
10889 u8 parseError; /* True after a parsing error. Ticket #1794 */
10890 u8 nTempReg; /* Number of temporary registers in aTempReg[] */
10891 u8 nTempInUse; /* Number of aTempReg[] currently checked out */
10892 int aTempReg[8]; /* Holding area for temporary registers */
10893 int nRangeReg; /* Size of the temporary register block */
10894 int iRangeReg; /* First register in temporary register block */
10895 int nErr; /* Number of errors seen */
10896 int nTab; /* Number of previously allocated VDBE cursors */
10897 int nMem; /* Number of memory cells used so far */
10898 int nSet; /* Number of sets used so far */
10899 int ckBase; /* Base register of data during check constraints */
10900 int iCacheLevel; /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
10901 int iCacheCnt; /* Counter used to generate aColCache[].lru values */
10902 u8 nColCache; /* Number of entries in the column cache */
10903 u8 iColCache; /* Next entry of the cache to replace */
10904 struct yColCache {
10905 int iTable; /* Table cursor number */
10906 int iColumn; /* Table column number */
10907 u8 tempReg; /* iReg is a temp register that needs to be freed */
10908 int iLevel; /* Nesting level */
10909 int iReg; /* Reg with value of this column. 0 means none. */
10910 int lru; /* Least recently used entry has the smallest value */
10911 } aColCache[SQLITE_N_COLCACHE]; /* One for each column cache entry */
10912 yDbMask writeMask; /* Start a write transaction on these databases */
10913 yDbMask cookieMask; /* Bitmask of schema verified databases */
10914 u8 isMultiWrite; /* True if statement may affect/insert multiple rows */
10915 u8 mayAbort; /* True if statement may throw an ABORT exception */
10916 int cookieGoto; /* Address of OP_Goto to cookie verifier subroutine */
10917 int cookieValue[SQLITE_MAX_ATTACHED+2]; /* Values of cookies to verify */
10918 #ifndef SQLITE_OMIT_SHARED_CACHE
10919 int nTableLock; /* Number of locks in aTableLock */
10920 TableLock *aTableLock; /* Required table locks for shared-cache mode */
10921 #endif
10922 int regRowid; /* Register holding rowid of CREATE TABLE entry */
10923 int regRoot; /* Register holding root page number for new objects */
10924 AutoincInfo *pAinc; /* Information about AUTOINCREMENT counters */
10925 int nMaxArg; /* Max args passed to user function by sub-program */
10927 /* Information used while coding trigger programs. */
10928 Parse *pToplevel; /* Parse structure for main program (or NULL) */
10929 Table *pTriggerTab; /* Table triggers are being coded for */
10930 u32 oldmask; /* Mask of old.* columns referenced */
10931 u32 newmask; /* Mask of new.* columns referenced */
10932 u8 eTriggerOp; /* TK_UPDATE, TK_INSERT or TK_DELETE */
10933 u8 eOrconf; /* Default ON CONFLICT policy for trigger steps */
10934 u8 disableTriggers; /* True to disable triggers */
10935 double nQueryLoop; /* Estimated number of iterations of a query */
10937 /* Above is constant between recursions. Below is reset before and after
10938 ** each recursion */
10940 int nVar; /* Number of '?' variables seen in the SQL so far */
10941 int nzVar; /* Number of available slots in azVar[] */
10942 char **azVar; /* Pointers to names of parameters */
10943 Vdbe *pReprepare; /* VM being reprepared (sqlite3Reprepare()) */
10944 int nAlias; /* Number of aliased result set columns */
10945 int nAliasAlloc; /* Number of allocated slots for aAlias[] */
10946 int *aAlias; /* Register used to hold aliased result */
10947 u8 explain; /* True if the EXPLAIN flag is found on the query */
10948 Token sNameToken; /* Token with unqualified schema object name */
10949 Token sLastToken; /* The last token parsed */
10950 const char *zTail; /* All SQL text past the last semicolon parsed */
10951 Table *pNewTable; /* A table being constructed by CREATE TABLE */
10952 Trigger *pNewTrigger; /* Trigger under construct by a CREATE TRIGGER */
10953 const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
10954 #ifndef SQLITE_OMIT_VIRTUALTABLE
10955 Token sArg; /* Complete text of a module argument */
10956 u8 declareVtab; /* True if inside sqlite3_declare_vtab() */
10957 int nVtabLock; /* Number of virtual tables to lock */
10958 Table **apVtabLock; /* Pointer to virtual tables needing locking */
10959 #endif
10960 int nHeight; /* Expression tree height of current sub-select */
10961 Table *pZombieTab; /* List of Table objects to delete after code gen */
10962 TriggerPrg *pTriggerPrg; /* Linked list of coded triggers */
10964 #ifndef SQLITE_OMIT_EXPLAIN
10965 int iSelectId;
10966 int iNextSelectId;
10967 #endif
10970 #ifdef SQLITE_OMIT_VIRTUALTABLE
10971 #define IN_DECLARE_VTAB 0
10972 #else
10973 #define IN_DECLARE_VTAB (pParse->declareVtab)
10974 #endif
10977 ** An instance of the following structure can be declared on a stack and used
10978 ** to save the Parse.zAuthContext value so that it can be restored later.
10980 struct AuthContext {
10981 const char *zAuthContext; /* Put saved Parse.zAuthContext here */
10982 Parse *pParse; /* The Parse structure */
10986 ** Bitfield flags for P5 value in OP_Insert and OP_Delete
10988 #define OPFLAG_NCHANGE 0x01 /* Set to update db->nChange */
10989 #define OPFLAG_LASTROWID 0x02 /* Set to update db->lastRowid */
10990 #define OPFLAG_ISUPDATE 0x04 /* This OP_Insert is an sql UPDATE */
10991 #define OPFLAG_APPEND 0x08 /* This is likely to be an append */
10992 #define OPFLAG_USESEEKRESULT 0x10 /* Try to avoid a seek in BtreeInsert() */
10993 #define OPFLAG_CLEARCACHE 0x20 /* Clear pseudo-table cache in OP_Column */
10996 * Each trigger present in the database schema is stored as an instance of
10997 * struct Trigger.
10999 * Pointers to instances of struct Trigger are stored in two ways.
11000 * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
11001 * database). This allows Trigger structures to be retrieved by name.
11002 * 2. All triggers associated with a single table form a linked list, using the
11003 * pNext member of struct Trigger. A pointer to the first element of the
11004 * linked list is stored as the "pTrigger" member of the associated
11005 * struct Table.
11007 * The "step_list" member points to the first element of a linked list
11008 * containing the SQL statements specified as the trigger program.
11010 struct Trigger {
11011 char *zName; /* The name of the trigger */
11012 char *table; /* The table or view to which the trigger applies */
11013 u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */
11014 u8 tr_tm; /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
11015 Expr *pWhen; /* The WHEN clause of the expression (may be NULL) */
11016 IdList *pColumns; /* If this is an UPDATE OF <column-list> trigger,
11017 the <column-list> is stored here */
11018 Schema *pSchema; /* Schema containing the trigger */
11019 Schema *pTabSchema; /* Schema containing the table */
11020 TriggerStep *step_list; /* Link list of trigger program steps */
11021 Trigger *pNext; /* Next trigger associated with the table */
11025 ** A trigger is either a BEFORE or an AFTER trigger. The following constants
11026 ** determine which.
11028 ** If there are multiple triggers, you might of some BEFORE and some AFTER.
11029 ** In that cases, the constants below can be ORed together.
11031 #define TRIGGER_BEFORE 1
11032 #define TRIGGER_AFTER 2
11035 * An instance of struct TriggerStep is used to store a single SQL statement
11036 * that is a part of a trigger-program.
11038 * Instances of struct TriggerStep are stored in a singly linked list (linked
11039 * using the "pNext" member) referenced by the "step_list" member of the
11040 * associated struct Trigger instance. The first element of the linked list is
11041 * the first step of the trigger-program.
11043 * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
11044 * "SELECT" statement. The meanings of the other members is determined by the
11045 * value of "op" as follows:
11047 * (op == TK_INSERT)
11048 * orconf -> stores the ON CONFLICT algorithm
11049 * pSelect -> If this is an INSERT INTO ... SELECT ... statement, then
11050 * this stores a pointer to the SELECT statement. Otherwise NULL.
11051 * target -> A token holding the quoted name of the table to insert into.
11052 * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
11053 * this stores values to be inserted. Otherwise NULL.
11054 * pIdList -> If this is an INSERT INTO ... (<column-names>) VALUES ...
11055 * statement, then this stores the column-names to be
11056 * inserted into.
11058 * (op == TK_DELETE)
11059 * target -> A token holding the quoted name of the table to delete from.
11060 * pWhere -> The WHERE clause of the DELETE statement if one is specified.
11061 * Otherwise NULL.
11063 * (op == TK_UPDATE)
11064 * target -> A token holding the quoted name of the table to update rows of.
11065 * pWhere -> The WHERE clause of the UPDATE statement if one is specified.
11066 * Otherwise NULL.
11067 * pExprList -> A list of the columns to update and the expressions to update
11068 * them to. See sqlite3Update() documentation of "pChanges"
11069 * argument.
11072 struct TriggerStep {
11073 u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
11074 u8 orconf; /* OE_Rollback etc. */
11075 Trigger *pTrig; /* The trigger that this step is a part of */
11076 Select *pSelect; /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
11077 Token target; /* Target table for DELETE, UPDATE, INSERT */
11078 Expr *pWhere; /* The WHERE clause for DELETE or UPDATE steps */
11079 ExprList *pExprList; /* SET clause for UPDATE. VALUES clause for INSERT */
11080 IdList *pIdList; /* Column names for INSERT */
11081 TriggerStep *pNext; /* Next in the link-list */
11082 TriggerStep *pLast; /* Last element in link-list. Valid for 1st elem only */
11086 ** The following structure contains information used by the sqliteFix...
11087 ** routines as they walk the parse tree to make database references
11088 ** explicit.
11090 typedef struct DbFixer DbFixer;
11091 struct DbFixer {
11092 Parse *pParse; /* The parsing context. Error messages written here */
11093 const char *zDb; /* Make sure all objects are contained in this database */
11094 const char *zType; /* Type of the container - used for error messages */
11095 const Token *pName; /* Name of the container - used for error messages */
11099 ** An objected used to accumulate the text of a string where we
11100 ** do not necessarily know how big the string will be in the end.
11102 struct StrAccum {
11103 sqlite3 *db; /* Optional database for lookaside. Can be NULL */
11104 char *zBase; /* A base allocation. Not from malloc. */
11105 char *zText; /* The string collected so far */
11106 int nChar; /* Length of the string so far */
11107 int nAlloc; /* Amount of space allocated in zText */
11108 int mxAlloc; /* Maximum allowed string length */
11109 u8 mallocFailed; /* Becomes true if any memory allocation fails */
11110 u8 useMalloc; /* 0: none, 1: sqlite3DbMalloc, 2: sqlite3_malloc */
11111 u8 tooBig; /* Becomes true if string size exceeds limits */
11115 ** A pointer to this structure is used to communicate information
11116 ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
11118 typedef struct {
11119 sqlite3 *db; /* The database being initialized */
11120 int iDb; /* 0 for main database. 1 for TEMP, 2.. for ATTACHed */
11121 char **pzErrMsg; /* Error message stored here */
11122 int rc; /* Result code stored here */
11123 } InitData;
11126 ** Structure containing global configuration data for the SQLite library.
11128 ** This structure also contains some state information.
11130 struct Sqlite3Config {
11131 int bMemstat; /* True to enable memory status */
11132 int bCoreMutex; /* True to enable core mutexing */
11133 int bFullMutex; /* True to enable full mutexing */
11134 int bOpenUri; /* True to interpret filenames as URIs */
11135 int mxStrlen; /* Maximum string length */
11136 int szLookaside; /* Default lookaside buffer size */
11137 int nLookaside; /* Default lookaside buffer count */
11138 sqlite3_mem_methods m; /* Low-level memory allocation interface */
11139 sqlite3_mutex_methods mutex; /* Low-level mutex interface */
11140 sqlite3_pcache_methods pcache; /* Low-level page-cache interface */
11141 void *pHeap; /* Heap storage space */
11142 int nHeap; /* Size of pHeap[] */
11143 int mnReq, mxReq; /* Min and max heap requests sizes */
11144 void *pScratch; /* Scratch memory */
11145 int szScratch; /* Size of each scratch buffer */
11146 int nScratch; /* Number of scratch buffers */
11147 void *pPage; /* Page cache memory */
11148 int szPage; /* Size of each page in pPage[] */
11149 int nPage; /* Number of pages in pPage[] */
11150 int mxParserStack; /* maximum depth of the parser stack */
11151 int sharedCacheEnabled; /* true if shared-cache mode enabled */
11152 /* The above might be initialized to non-zero. The following need to always
11153 ** initially be zero, however. */
11154 int isInit; /* True after initialization has finished */
11155 int inProgress; /* True while initialization in progress */
11156 int isMutexInit; /* True after mutexes are initialized */
11157 int isMallocInit; /* True after malloc is initialized */
11158 int isPCacheInit; /* True after malloc is initialized */
11159 sqlite3_mutex *pInitMutex; /* Mutex used by sqlite3_initialize() */
11160 int nRefInitMutex; /* Number of users of pInitMutex */
11161 void (*xLog)(void*,int,const char*); /* Function for logging */
11162 void *pLogArg; /* First argument to xLog() */
11163 int bLocaltimeFault; /* True to fail localtime() calls */
11167 ** Context pointer passed down through the tree-walk.
11169 struct Walker {
11170 int (*xExprCallback)(Walker*, Expr*); /* Callback for expressions */
11171 int (*xSelectCallback)(Walker*,Select*); /* Callback for SELECTs */
11172 Parse *pParse; /* Parser context. */
11173 union { /* Extra data for callback */
11174 NameContext *pNC; /* Naming context */
11175 int i; /* Integer value */
11176 } u;
11179 /* Forward declarations */
11180 SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
11181 SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
11182 SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
11183 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
11184 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
11187 ** Return code from the parse-tree walking primitives and their
11188 ** callbacks.
11190 #define WRC_Continue 0 /* Continue down into children */
11191 #define WRC_Prune 1 /* Omit children but continue walking siblings */
11192 #define WRC_Abort 2 /* Abandon the tree walk */
11195 ** Assuming zIn points to the first byte of a UTF-8 character,
11196 ** advance zIn to point to the first byte of the next UTF-8 character.
11198 #define SQLITE_SKIP_UTF8(zIn) { \
11199 if( (*(zIn++))>=0xc0 ){ \
11200 while( (*zIn & 0xc0)==0x80 ){ zIn++; } \
11205 ** The SQLITE_*_BKPT macros are substitutes for the error codes with
11206 ** the same name but without the _BKPT suffix. These macros invoke
11207 ** routines that report the line-number on which the error originated
11208 ** using sqlite3_log(). The routines also provide a convenient place
11209 ** to set a debugger breakpoint.
11211 SQLITE_PRIVATE int sqlite3CorruptError(int);
11212 SQLITE_PRIVATE int sqlite3MisuseError(int);
11213 SQLITE_PRIVATE int sqlite3CantopenError(int);
11214 #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
11215 #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
11216 #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
11220 ** FTS4 is really an extension for FTS3. It is enabled using the
11221 ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also all
11222 ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
11224 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
11225 # define SQLITE_ENABLE_FTS3
11226 #endif
11229 ** The ctype.h header is needed for non-ASCII systems. It is also
11230 ** needed by FTS3 when FTS3 is included in the amalgamation.
11232 #if !defined(SQLITE_ASCII) || \
11233 (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
11234 # include <ctype.h>
11235 #endif
11238 ** The following macros mimic the standard library functions toupper(),
11239 ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
11240 ** sqlite versions only work for ASCII characters, regardless of locale.
11242 #ifdef SQLITE_ASCII
11243 # define sqlite3Toupper(x) ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
11244 # define sqlite3Isspace(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
11245 # define sqlite3Isalnum(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
11246 # define sqlite3Isalpha(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
11247 # define sqlite3Isdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
11248 # define sqlite3Isxdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
11249 # define sqlite3Tolower(x) (sqlite3UpperToLower[(unsigned char)(x)])
11250 #else
11251 # define sqlite3Toupper(x) toupper((unsigned char)(x))
11252 # define sqlite3Isspace(x) isspace((unsigned char)(x))
11253 # define sqlite3Isalnum(x) isalnum((unsigned char)(x))
11254 # define sqlite3Isalpha(x) isalpha((unsigned char)(x))
11255 # define sqlite3Isdigit(x) isdigit((unsigned char)(x))
11256 # define sqlite3Isxdigit(x) isxdigit((unsigned char)(x))
11257 # define sqlite3Tolower(x) tolower((unsigned char)(x))
11258 #endif
11261 ** Internal function prototypes
11263 SQLITE_PRIVATE int sqlite3StrICmp(const char *, const char *);
11264 SQLITE_PRIVATE int sqlite3Strlen30(const char*);
11265 #define sqlite3StrNICmp sqlite3_strnicmp
11267 SQLITE_PRIVATE int sqlite3MallocInit(void);
11268 SQLITE_PRIVATE void sqlite3MallocEnd(void);
11269 SQLITE_PRIVATE void *sqlite3Malloc(int);
11270 SQLITE_PRIVATE void *sqlite3MallocZero(int);
11271 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, int);
11272 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, int);
11273 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
11274 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int);
11275 SQLITE_PRIVATE void *sqlite3Realloc(void*, int);
11276 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
11277 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int);
11278 SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
11279 SQLITE_PRIVATE int sqlite3MallocSize(void*);
11280 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
11281 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
11282 SQLITE_PRIVATE void sqlite3ScratchFree(void*);
11283 SQLITE_PRIVATE void *sqlite3PageMalloc(int);
11284 SQLITE_PRIVATE void sqlite3PageFree(void*);
11285 SQLITE_PRIVATE void sqlite3MemSetDefault(void);
11286 SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
11287 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
11290 ** On systems with ample stack space and that support alloca(), make
11291 ** use of alloca() to obtain space for large automatic objects. By default,
11292 ** obtain space from malloc().
11294 ** The alloca() routine never returns NULL. This will cause code paths
11295 ** that deal with sqlite3StackAlloc() failures to be unreachable.
11297 #ifdef SQLITE_USE_ALLOCA
11298 # define sqlite3StackAllocRaw(D,N) alloca(N)
11299 # define sqlite3StackAllocZero(D,N) memset(alloca(N), 0, N)
11300 # define sqlite3StackFree(D,P)
11301 #else
11302 # define sqlite3StackAllocRaw(D,N) sqlite3DbMallocRaw(D,N)
11303 # define sqlite3StackAllocZero(D,N) sqlite3DbMallocZero(D,N)
11304 # define sqlite3StackFree(D,P) sqlite3DbFree(D,P)
11305 #endif
11307 #ifdef SQLITE_ENABLE_MEMSYS3
11308 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
11309 #endif
11310 #ifdef SQLITE_ENABLE_MEMSYS5
11311 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
11312 #endif
11315 #ifndef SQLITE_MUTEX_OMIT
11316 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
11317 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void);
11318 SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int);
11319 SQLITE_PRIVATE int sqlite3MutexInit(void);
11320 SQLITE_PRIVATE int sqlite3MutexEnd(void);
11321 #endif
11323 SQLITE_PRIVATE int sqlite3StatusValue(int);
11324 SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
11325 SQLITE_PRIVATE void sqlite3StatusSet(int, int);
11327 #ifndef SQLITE_OMIT_FLOATING_POINT
11328 SQLITE_PRIVATE int sqlite3IsNaN(double);
11329 #else
11330 # define sqlite3IsNaN(X) 0
11331 #endif
11333 SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, int, const char*, va_list);
11334 #ifndef SQLITE_OMIT_TRACE
11335 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
11336 #endif
11337 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
11338 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
11339 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
11340 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
11341 SQLITE_PRIVATE void sqlite3DebugPrintf(const char*, ...);
11342 #endif
11343 #if defined(SQLITE_TEST)
11344 SQLITE_PRIVATE void *sqlite3TestTextToPtr(const char*);
11345 #endif
11346 SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
11347 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
11348 SQLITE_PRIVATE int sqlite3Dequote(char*);
11349 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
11350 SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
11351 SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
11352 SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
11353 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
11354 SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
11355 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
11356 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
11357 SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
11358 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
11359 SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
11360 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
11361 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
11362 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
11363 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
11364 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
11365 SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
11366 SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
11367 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
11368 SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
11369 SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
11370 SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
11371 SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3*, int);
11372 SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
11373 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
11374 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
11375 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
11376 SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
11377 SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
11378 SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
11379 SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
11380 SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
11381 SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
11382 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
11383 SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
11384 SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,Select*);
11385 SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
11386 sqlite3_vfs**,char**,char **);
11388 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
11389 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
11390 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
11391 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
11392 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
11393 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
11394 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
11396 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
11397 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
11398 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
11399 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, u8 iBatch, i64);
11400 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
11402 SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
11404 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
11405 SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse*,Table*);
11406 #else
11407 # define sqlite3ViewGetColumnNames(A,B) 0
11408 #endif
11410 SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
11411 SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
11412 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
11413 #ifndef SQLITE_OMIT_AUTOINCREMENT
11414 SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse);
11415 SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse);
11416 #else
11417 # define sqlite3AutoincrementBegin(X)
11418 # define sqlite3AutoincrementEnd(X)
11419 #endif
11420 SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
11421 SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int,int*,int*,int*);
11422 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
11423 SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
11424 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
11425 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
11426 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
11427 Token*, Select*, Expr*, IdList*);
11428 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
11429 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
11430 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
11431 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
11432 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
11433 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
11434 SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
11435 Token*, int, int);
11436 SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
11437 SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
11438 SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
11439 Expr*,ExprList*,int,Expr*,Expr*);
11440 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
11441 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
11442 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
11443 SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
11444 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
11445 SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse *, SrcList *, Expr *, ExprList *, Expr *, Expr *, char *);
11446 #endif
11447 SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
11448 SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
11449 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**,ExprList*,u16);
11450 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
11451 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int);
11452 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
11453 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
11454 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, int, int, int);
11455 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
11456 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
11457 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*, int);
11458 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
11459 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
11460 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
11461 SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
11462 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
11463 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
11464 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
11465 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse*, Expr*);
11466 SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int);
11467 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
11468 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
11469 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
11470 SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
11471 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
11472 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
11473 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
11474 SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
11475 SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
11476 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
11477 SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*);
11478 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*);
11479 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
11480 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
11481 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
11482 SQLITE_PRIVATE void sqlite3PrngSaveState(void);
11483 SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
11484 SQLITE_PRIVATE void sqlite3PrngResetState(void);
11485 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*);
11486 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
11487 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
11488 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
11489 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
11490 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
11491 SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
11492 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
11493 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
11494 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
11495 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);
11496 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
11497 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
11498 SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(Vdbe*, const Expr*, int, int);
11499 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
11500 SQLITE_PRIVATE int sqlite3IsRowid(const char*);
11501 SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int, Trigger *, int);
11502 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
11503 SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int);
11504 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
11505 int*,int,int,int,int,int*);
11506 SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int);
11507 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
11508 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
11509 SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
11510 SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
11511 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, char*, int);
11512 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
11513 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
11514 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
11515 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
11516 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
11517 SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
11518 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,int);
11519 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
11520 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
11521 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
11522 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
11523 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
11524 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
11526 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
11527 SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
11528 #endif
11530 #ifndef SQLITE_OMIT_TRIGGER
11531 SQLITE_PRIVATE void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
11532 Expr*,int, int);
11533 SQLITE_PRIVATE void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
11534 SQLITE_PRIVATE void sqlite3DropTrigger(Parse*, SrcList*, int);
11535 SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse*, Trigger*);
11536 SQLITE_PRIVATE Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
11537 SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *, Table *);
11538 SQLITE_PRIVATE void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
11539 int, int, int);
11540 SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
11541 void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
11542 SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
11543 SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
11544 SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
11545 ExprList*,Select*,u8);
11546 SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
11547 SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
11548 SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3*, Trigger*);
11549 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
11550 SQLITE_PRIVATE u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
11551 # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
11552 #else
11553 # define sqlite3TriggersExist(B,C,D,E,F) 0
11554 # define sqlite3DeleteTrigger(A,B)
11555 # define sqlite3DropTriggerPtr(A,B)
11556 # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
11557 # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
11558 # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
11559 # define sqlite3TriggerList(X, Y) 0
11560 # define sqlite3ParseToplevel(p) p
11561 # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
11562 #endif
11564 SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
11565 SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
11566 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
11567 #ifndef SQLITE_OMIT_AUTHORIZATION
11568 SQLITE_PRIVATE void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
11569 SQLITE_PRIVATE int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
11570 SQLITE_PRIVATE void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
11571 SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext*);
11572 SQLITE_PRIVATE int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
11573 #else
11574 # define sqlite3AuthRead(a,b,c,d)
11575 # define sqlite3AuthCheck(a,b,c,d,e) SQLITE_OK
11576 # define sqlite3AuthContextPush(a,b,c)
11577 # define sqlite3AuthContextPop(a) ((void)(a))
11578 #endif
11579 SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
11580 SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
11581 SQLITE_PRIVATE int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
11582 SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
11583 SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
11584 SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
11585 SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
11586 SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
11587 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
11588 SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
11589 SQLITE_PRIVATE int sqlite3Atoi(const char*);
11590 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
11591 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
11592 SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8*, const u8**);
11595 ** Routines to read and write variable-length integers. These used to
11596 ** be defined locally, but now we use the varint routines in the util.c
11597 ** file. Code should use the MACRO forms below, as the Varint32 versions
11598 ** are coded to assume the single byte case is already handled (which
11599 ** the MACRO form does).
11601 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
11602 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char*, u32);
11603 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
11604 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
11605 SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
11608 ** The header of a record consists of a sequence variable-length integers.
11609 ** These integers are almost always small and are encoded as a single byte.
11610 ** The following macros take advantage this fact to provide a fast encode
11611 ** and decode of the integers in a record header. It is faster for the common
11612 ** case where the integer is a single byte. It is a little slower when the
11613 ** integer is two or more bytes. But overall it is faster.
11615 ** The following expressions are equivalent:
11617 ** x = sqlite3GetVarint32( A, &B );
11618 ** x = sqlite3PutVarint32( A, B );
11620 ** x = getVarint32( A, B );
11621 ** x = putVarint32( A, B );
11624 #define getVarint32(A,B) (u8)((*(A)<(u8)0x80) ? ((B) = (u32)*(A)),1 : sqlite3GetVarint32((A), (u32 *)&(B)))
11625 #define putVarint32(A,B) (u8)(((u32)(B)<(u32)0x80) ? (*(A) = (unsigned char)(B)),1 : sqlite3PutVarint32((A), (B)))
11626 #define getVarint sqlite3GetVarint
11627 #define putVarint sqlite3PutVarint
11630 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
11631 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *, Table *);
11632 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
11633 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
11634 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
11635 SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
11636 SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);
11637 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
11638 SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
11639 SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
11640 SQLITE_PRIVATE const char *sqlite3ErrStr(int);
11641 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
11642 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
11643 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
11644 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
11645 SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Expr*, CollSeq*);
11646 SQLITE_PRIVATE Expr *sqlite3ExprSetCollByToken(Parse *pParse, Expr*, Token*);
11647 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
11648 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
11649 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
11650 SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
11651 SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
11652 SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
11653 SQLITE_PRIVATE int sqlite3AbsInt32(int);
11654 #ifdef SQLITE_ENABLE_8_3_NAMES
11655 SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
11656 #else
11657 # define sqlite3FileSuffix3(X,Y)
11658 #endif
11659 SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z);
11661 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
11662 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
11663 SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
11664 void(*)(void*));
11665 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
11666 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
11667 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
11668 #ifdef SQLITE_ENABLE_STAT3
11669 SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *, u8, char *, int, int *);
11670 #endif
11671 SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
11672 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
11673 #ifndef SQLITE_AMALGAMATION
11674 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
11675 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
11676 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
11677 SQLITE_PRIVATE const Token sqlite3IntTokens[];
11678 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
11679 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
11680 #ifndef SQLITE_OMIT_WSD
11681 SQLITE_PRIVATE int sqlite3PendingByte;
11682 #endif
11683 #endif
11684 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
11685 SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
11686 SQLITE_PRIVATE void sqlite3AlterFunctions(void);
11687 SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
11688 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
11689 SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
11690 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
11691 SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
11692 SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
11693 SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
11694 SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
11695 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
11696 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
11697 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
11698 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
11699 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(sqlite3*, u8, CollSeq *, const char*);
11700 SQLITE_PRIVATE char sqlite3AffinityType(const char*);
11701 SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
11702 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
11703 SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
11704 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
11705 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
11706 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
11707 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
11708 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
11709 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
11710 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
11711 SQLITE_PRIVATE void sqlite3SchemaClear(void *);
11712 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
11713 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
11714 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
11715 SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
11716 void (*)(sqlite3_context*,int,sqlite3_value **),
11717 void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
11718 FuncDestructor *pDestructor
11720 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
11721 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
11723 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
11724 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
11725 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
11726 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
11727 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
11728 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
11730 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
11731 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
11734 ** The interface to the LEMON-generated parser
11736 SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));
11737 SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
11738 SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
11739 #ifdef YYTRACKMAXSTACKDEPTH
11740 SQLITE_PRIVATE int sqlite3ParserStackPeak(void*);
11741 #endif
11743 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
11744 #ifndef SQLITE_OMIT_LOAD_EXTENSION
11745 SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3*);
11746 #else
11747 # define sqlite3CloseExtensions(X)
11748 #endif
11750 #ifndef SQLITE_OMIT_SHARED_CACHE
11751 SQLITE_PRIVATE void sqlite3TableLock(Parse *, int, int, u8, const char *);
11752 #else
11753 #define sqlite3TableLock(v,w,x,y,z)
11754 #endif
11756 #ifdef SQLITE_TEST
11757 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char*);
11758 #endif
11760 #ifdef SQLITE_OMIT_VIRTUALTABLE
11761 # define sqlite3VtabClear(Y)
11762 # define sqlite3VtabSync(X,Y) SQLITE_OK
11763 # define sqlite3VtabRollback(X)
11764 # define sqlite3VtabCommit(X)
11765 # define sqlite3VtabInSync(db) 0
11766 # define sqlite3VtabLock(X)
11767 # define sqlite3VtabUnlock(X)
11768 # define sqlite3VtabUnlockList(X)
11769 # define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
11770 # define sqlite3GetVTable(X,Y) ((VTable*)0)
11771 #else
11772 SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table*);
11773 SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, char **);
11774 SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db);
11775 SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db);
11776 SQLITE_PRIVATE void sqlite3VtabLock(VTable *);
11777 SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *);
11778 SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3*);
11779 SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *, int, int);
11780 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
11781 # define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
11782 #endif
11783 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
11784 SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*);
11785 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
11786 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
11787 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
11788 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
11789 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
11790 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
11791 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
11792 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
11793 SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
11794 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
11795 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
11796 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
11797 SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
11798 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
11799 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
11800 SQLITE_PRIVATE const char *sqlite3JournalModename(int);
11801 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
11802 SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
11804 /* Declarations for functions in fkey.c. All of these are replaced by
11805 ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
11806 ** key functionality is available. If OMIT_TRIGGER is defined but
11807 ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
11808 ** this case foreign keys are parsed, but no other functionality is
11809 ** provided (enforcement of FK constraints requires the triggers sub-system).
11811 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
11812 SQLITE_PRIVATE void sqlite3FkCheck(Parse*, Table*, int, int);
11813 SQLITE_PRIVATE void sqlite3FkDropTable(Parse*, SrcList *, Table*);
11814 SQLITE_PRIVATE void sqlite3FkActions(Parse*, Table*, ExprList*, int);
11815 SQLITE_PRIVATE int sqlite3FkRequired(Parse*, Table*, int*, int);
11816 SQLITE_PRIVATE u32 sqlite3FkOldmask(Parse*, Table*);
11817 SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *);
11818 #else
11819 #define sqlite3FkActions(a,b,c,d)
11820 #define sqlite3FkCheck(a,b,c,d)
11821 #define sqlite3FkDropTable(a,b,c)
11822 #define sqlite3FkOldmask(a,b) 0
11823 #define sqlite3FkRequired(a,b,c,d) 0
11824 #endif
11825 #ifndef SQLITE_OMIT_FOREIGN_KEY
11826 SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *, Table*);
11827 #else
11828 #define sqlite3FkDelete(a,b)
11829 #endif
11833 ** Available fault injectors. Should be numbered beginning with 0.
11835 #define SQLITE_FAULTINJECTOR_MALLOC 0
11836 #define SQLITE_FAULTINJECTOR_COUNT 1
11839 ** The interface to the code in fault.c used for identifying "benign"
11840 ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
11841 ** is not defined.
11843 #ifndef SQLITE_OMIT_BUILTIN_TEST
11844 SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void);
11845 SQLITE_PRIVATE void sqlite3EndBenignMalloc(void);
11846 #else
11847 #define sqlite3BeginBenignMalloc()
11848 #define sqlite3EndBenignMalloc()
11849 #endif
11851 #define IN_INDEX_ROWID 1
11852 #define IN_INDEX_EPH 2
11853 #define IN_INDEX_INDEX 3
11854 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int*);
11856 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
11857 SQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
11858 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *);
11859 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *);
11860 #else
11861 #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
11862 #endif
11864 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
11865 SQLITE_PRIVATE int sqlite3MemJournalSize(void);
11866 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
11868 #if SQLITE_MAX_EXPR_DEPTH>0
11869 SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
11870 SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *);
11871 SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse*, int);
11872 #else
11873 #define sqlite3ExprSetHeight(x,y)
11874 #define sqlite3SelectExprHeight(x) 0
11875 #define sqlite3ExprCheckHeight(x,y)
11876 #endif
11878 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
11879 SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
11881 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
11882 SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
11883 SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db);
11884 SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db);
11885 #else
11886 #define sqlite3ConnectionBlocked(x,y)
11887 #define sqlite3ConnectionUnlocked(x)
11888 #define sqlite3ConnectionClosed(x)
11889 #endif
11891 #ifdef SQLITE_DEBUG
11892 SQLITE_PRIVATE void sqlite3ParserTrace(FILE*, char *);
11893 #endif
11896 ** If the SQLITE_ENABLE IOTRACE exists then the global variable
11897 ** sqlite3IoTrace is a pointer to a printf-like routine used to
11898 ** print I/O tracing messages.
11900 #ifdef SQLITE_ENABLE_IOTRACE
11901 # define IOTRACE(A) if( sqlite3IoTrace ){ sqlite3IoTrace A; }
11902 SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe*);
11903 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
11904 #else
11905 # define IOTRACE(A)
11906 # define sqlite3VdbeIOTraceSql(X)
11907 #endif
11910 ** These routines are available for the mem2.c debugging memory allocator
11911 ** only. They are used to verify that different "types" of memory
11912 ** allocations are properly tracked by the system.
11914 ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
11915 ** the MEMTYPE_* macros defined below. The type must be a bitmask with
11916 ** a single bit set.
11918 ** sqlite3MemdebugHasType() returns true if any of the bits in its second
11919 ** argument match the type set by the previous sqlite3MemdebugSetType().
11920 ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
11922 ** sqlite3MemdebugNoType() returns true if none of the bits in its second
11923 ** argument match the type set by the previous sqlite3MemdebugSetType().
11925 ** Perhaps the most important point is the difference between MEMTYPE_HEAP
11926 ** and MEMTYPE_LOOKASIDE. If an allocation is MEMTYPE_LOOKASIDE, that means
11927 ** it might have been allocated by lookaside, except the allocation was
11928 ** too large or lookaside was already full. It is important to verify
11929 ** that allocations that might have been satisfied by lookaside are not
11930 ** passed back to non-lookaside free() routines. Asserts such as the
11931 ** example above are placed on the non-lookaside free() routines to verify
11932 ** this constraint.
11934 ** All of this is no-op for a production build. It only comes into
11935 ** play when the SQLITE_MEMDEBUG compile-time option is used.
11937 #ifdef SQLITE_MEMDEBUG
11938 SQLITE_PRIVATE void sqlite3MemdebugSetType(void*,u8);
11939 SQLITE_PRIVATE int sqlite3MemdebugHasType(void*,u8);
11940 SQLITE_PRIVATE int sqlite3MemdebugNoType(void*,u8);
11941 #else
11942 # define sqlite3MemdebugSetType(X,Y) /* no-op */
11943 # define sqlite3MemdebugHasType(X,Y) 1
11944 # define sqlite3MemdebugNoType(X,Y) 1
11945 #endif
11946 #define MEMTYPE_HEAP 0x01 /* General heap allocations */
11947 #define MEMTYPE_LOOKASIDE 0x02 /* Might have been lookaside memory */
11948 #define MEMTYPE_SCRATCH 0x04 /* Scratch allocations */
11949 #define MEMTYPE_PCACHE 0x08 /* Page cache allocations */
11950 #define MEMTYPE_DB 0x10 /* Uses sqlite3DbMalloc, not sqlite_malloc */
11952 #endif /* _SQLITEINT_H_ */
11954 /************** End of sqliteInt.h *******************************************/
11955 /************** Begin file global.c ******************************************/
11957 ** 2008 June 13
11959 ** The author disclaims copyright to this source code. In place of
11960 ** a legal notice, here is a blessing:
11962 ** May you do good and not evil.
11963 ** May you find forgiveness for yourself and forgive others.
11964 ** May you share freely, never taking more than you give.
11966 *************************************************************************
11968 ** This file contains definitions of global variables and contants.
11971 /* An array to map all upper-case characters into their corresponding
11972 ** lower-case character.
11974 ** SQLite only considers US-ASCII (or EBCDIC) characters. We do not
11975 ** handle case conversions for the UTF character set since the tables
11976 ** involved are nearly as big or bigger than SQLite itself.
11978 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
11979 #ifdef SQLITE_ASCII
11980 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
11981 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
11982 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
11983 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
11984 104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
11985 122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
11986 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
11987 126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
11988 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
11989 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
11990 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
11991 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
11992 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
11993 234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
11994 252,253,254,255
11995 #endif
11996 #ifdef SQLITE_EBCDIC
11997 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* 0x */
11998 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
11999 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
12000 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
12001 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
12002 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
12003 96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
12004 112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
12005 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
12006 144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
12007 160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
12008 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
12009 192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
12010 208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
12011 224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
12012 239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
12013 #endif
12017 ** The following 256 byte lookup table is used to support SQLites built-in
12018 ** equivalents to the following standard library functions:
12020 ** isspace() 0x01
12021 ** isalpha() 0x02
12022 ** isdigit() 0x04
12023 ** isalnum() 0x06
12024 ** isxdigit() 0x08
12025 ** toupper() 0x20
12026 ** SQLite identifier character 0x40
12028 ** Bit 0x20 is set if the mapped character requires translation to upper
12029 ** case. i.e. if the character is a lower-case ASCII character.
12030 ** If x is a lower-case ASCII character, then its upper-case equivalent
12031 ** is (x - 0x20). Therefore toupper() can be implemented as:
12033 ** (x & ~(map[x]&0x20))
12035 ** Standard function tolower() is implemented using the sqlite3UpperToLower[]
12036 ** array. tolower() is used more often than toupper() by SQLite.
12038 ** Bit 0x40 is set if the character non-alphanumeric and can be used in an
12039 ** SQLite identifier. Identifiers are alphanumerics, "_", "$", and any
12040 ** non-ASCII UTF character. Hence the test for whether or not a character is
12041 ** part of an identifier is 0x46.
12043 ** SQLite's versions are identical to the standard versions assuming a
12044 ** locale of "C". They are implemented as macros in sqliteInt.h.
12046 #ifdef SQLITE_ASCII
12047 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
12048 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 00..07 ........ */
12049 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, /* 08..0f ........ */
12050 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 10..17 ........ */
12051 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 18..1f ........ */
12052 0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, /* 20..27 !"#$%&' */
12053 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 28..2f ()*+,-./ */
12054 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, /* 30..37 01234567 */
12055 0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 38..3f 89:;<=>? */
12057 0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02, /* 40..47 @ABCDEFG */
12058 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 48..4f HIJKLMNO */
12059 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 50..57 PQRSTUVW */
12060 0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40, /* 58..5f XYZ[\]^_ */
12061 0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22, /* 60..67 `abcdefg */
12062 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 68..6f hijklmno */
12063 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 70..77 pqrstuvw */
12064 0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, /* 78..7f xyz{|}~. */
12066 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 80..87 ........ */
12067 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 88..8f ........ */
12068 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 90..97 ........ */
12069 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 98..9f ........ */
12070 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a0..a7 ........ */
12071 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a8..af ........ */
12072 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b0..b7 ........ */
12073 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b8..bf ........ */
12075 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c0..c7 ........ */
12076 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c8..cf ........ */
12077 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d0..d7 ........ */
12078 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d8..df ........ */
12079 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e0..e7 ........ */
12080 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e8..ef ........ */
12081 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* f0..f7 ........ */
12082 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40 /* f8..ff ........ */
12084 #endif
12086 #ifndef SQLITE_USE_URI
12087 # define SQLITE_USE_URI 0
12088 #endif
12091 ** The following singleton contains the global configuration for
12092 ** the SQLite library.
12094 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
12095 SQLITE_DEFAULT_MEMSTATUS, /* bMemstat */
12096 1, /* bCoreMutex */
12097 SQLITE_THREADSAFE==1, /* bFullMutex */
12098 SQLITE_USE_URI, /* bOpenUri */
12099 0x7ffffffe, /* mxStrlen */
12100 128, /* szLookaside */
12101 500, /* nLookaside */
12102 {0,0,0,0,0,0,0,0}, /* m */
12103 {0,0,0,0,0,0,0,0,0}, /* mutex */
12104 {0,0,0,0,0,0,0,0,0,0,0}, /* pcache */
12105 (void*)0, /* pHeap */
12106 0, /* nHeap */
12107 0, 0, /* mnHeap, mxHeap */
12108 (void*)0, /* pScratch */
12109 0, /* szScratch */
12110 0, /* nScratch */
12111 (void*)0, /* pPage */
12112 0, /* szPage */
12113 0, /* nPage */
12114 0, /* mxParserStack */
12115 0, /* sharedCacheEnabled */
12116 /* All the rest should always be initialized to zero */
12117 0, /* isInit */
12118 0, /* inProgress */
12119 0, /* isMutexInit */
12120 0, /* isMallocInit */
12121 0, /* isPCacheInit */
12122 0, /* pInitMutex */
12123 0, /* nRefInitMutex */
12124 0, /* xLog */
12125 0, /* pLogArg */
12126 0, /* bLocaltimeFault */
12131 ** Hash table for global functions - functions common to all
12132 ** database connections. After initialization, this table is
12133 ** read-only.
12135 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
12138 ** Constant tokens for values 0 and 1.
12140 SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
12141 { "0", 1 },
12142 { "1", 1 }
12147 ** The value of the "pending" byte must be 0x40000000 (1 byte past the
12148 ** 1-gibabyte boundary) in a compatible database. SQLite never uses
12149 ** the database page that contains the pending byte. It never attempts
12150 ** to read or write that page. The pending byte page is set assign
12151 ** for use by the VFS layers as space for managing file locks.
12153 ** During testing, it is often desirable to move the pending byte to
12154 ** a different position in the file. This allows code that has to
12155 ** deal with the pending byte to run on files that are much smaller
12156 ** than 1 GiB. The sqlite3_test_control() interface can be used to
12157 ** move the pending byte.
12159 ** IMPORTANT: Changing the pending byte to any value other than
12160 ** 0x40000000 results in an incompatible database file format!
12161 ** Changing the pending byte during operating results in undefined
12162 ** and dileterious behavior.
12164 #ifndef SQLITE_OMIT_WSD
12165 SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
12166 #endif
12169 ** Properties of opcodes. The OPFLG_INITIALIZER macro is
12170 ** created by mkopcodeh.awk during compilation. Data is obtained
12171 ** from the comments following the "case OP_xxxx:" statements in
12172 ** the vdbe.c file.
12174 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
12176 /************** End of global.c **********************************************/
12177 /************** Begin file ctime.c *******************************************/
12179 ** 2010 February 23
12181 ** The author disclaims copyright to this source code. In place of
12182 ** a legal notice, here is a blessing:
12184 ** May you do good and not evil.
12185 ** May you find forgiveness for yourself and forgive others.
12186 ** May you share freely, never taking more than you give.
12188 *************************************************************************
12190 ** This file implements routines used to report what compile-time options
12191 ** SQLite was built with.
12194 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
12198 ** An array of names of all compile-time options. This array should
12199 ** be sorted A-Z.
12201 ** This array looks large, but in a typical installation actually uses
12202 ** only a handful of compile-time options, so most times this array is usually
12203 ** rather short and uses little memory space.
12205 static const char * const azCompileOpt[] = {
12207 /* These macros are provided to "stringify" the value of the define
12208 ** for those options in which the value is meaningful. */
12209 #define CTIMEOPT_VAL_(opt) #opt
12210 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
12212 #ifdef SQLITE_32BIT_ROWID
12213 "32BIT_ROWID",
12214 #endif
12215 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
12216 "4_BYTE_ALIGNED_MALLOC",
12217 #endif
12218 #ifdef SQLITE_CASE_SENSITIVE_LIKE
12219 "CASE_SENSITIVE_LIKE",
12220 #endif
12221 #ifdef SQLITE_CHECK_PAGES
12222 "CHECK_PAGES",
12223 #endif
12224 #ifdef SQLITE_COVERAGE_TEST
12225 "COVERAGE_TEST",
12226 #endif
12227 #ifdef SQLITE_DEBUG
12228 "DEBUG",
12229 #endif
12230 #ifdef SQLITE_DEFAULT_LOCKING_MODE
12231 "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
12232 #endif
12233 #ifdef SQLITE_DISABLE_DIRSYNC
12234 "DISABLE_DIRSYNC",
12235 #endif
12236 #ifdef SQLITE_DISABLE_LFS
12237 "DISABLE_LFS",
12238 #endif
12239 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
12240 "ENABLE_ATOMIC_WRITE",
12241 #endif
12242 #ifdef SQLITE_ENABLE_CEROD
12243 "ENABLE_CEROD",
12244 #endif
12245 #ifdef SQLITE_ENABLE_COLUMN_METADATA
12246 "ENABLE_COLUMN_METADATA",
12247 #endif
12248 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
12249 "ENABLE_EXPENSIVE_ASSERT",
12250 #endif
12251 #ifdef SQLITE_ENABLE_FTS1
12252 "ENABLE_FTS1",
12253 #endif
12254 #ifdef SQLITE_ENABLE_FTS2
12255 "ENABLE_FTS2",
12256 #endif
12257 #ifdef SQLITE_ENABLE_FTS3
12258 "ENABLE_FTS3",
12259 #endif
12260 #ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
12261 "ENABLE_FTS3_PARENTHESIS",
12262 #endif
12263 #ifdef SQLITE_ENABLE_FTS4
12264 "ENABLE_FTS4",
12265 #endif
12266 #ifdef SQLITE_ENABLE_ICU
12267 "ENABLE_ICU",
12268 #endif
12269 #ifdef SQLITE_ENABLE_IOTRACE
12270 "ENABLE_IOTRACE",
12271 #endif
12272 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
12273 "ENABLE_LOAD_EXTENSION",
12274 #endif
12275 #ifdef SQLITE_ENABLE_LOCKING_STYLE
12276 "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
12277 #endif
12278 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
12279 "ENABLE_MEMORY_MANAGEMENT",
12280 #endif
12281 #ifdef SQLITE_ENABLE_MEMSYS3
12282 "ENABLE_MEMSYS3",
12283 #endif
12284 #ifdef SQLITE_ENABLE_MEMSYS5
12285 "ENABLE_MEMSYS5",
12286 #endif
12287 #ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK
12288 "ENABLE_OVERSIZE_CELL_CHECK",
12289 #endif
12290 #ifdef SQLITE_ENABLE_RTREE
12291 "ENABLE_RTREE",
12292 #endif
12293 #ifdef SQLITE_ENABLE_STAT3
12294 "ENABLE_STAT3",
12295 #endif
12296 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
12297 "ENABLE_UNLOCK_NOTIFY",
12298 #endif
12299 #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
12300 "ENABLE_UPDATE_DELETE_LIMIT",
12301 #endif
12302 #ifdef SQLITE_HAS_CODEC
12303 "HAS_CODEC",
12304 #endif
12305 #ifdef SQLITE_HAVE_ISNAN
12306 "HAVE_ISNAN",
12307 #endif
12308 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
12309 "HOMEGROWN_RECURSIVE_MUTEX",
12310 #endif
12311 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
12312 "IGNORE_AFP_LOCK_ERRORS",
12313 #endif
12314 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
12315 "IGNORE_FLOCK_LOCK_ERRORS",
12316 #endif
12317 #ifdef SQLITE_INT64_TYPE
12318 "INT64_TYPE",
12319 #endif
12320 #ifdef SQLITE_LOCK_TRACE
12321 "LOCK_TRACE",
12322 #endif
12323 #ifdef SQLITE_MAX_SCHEMA_RETRY
12324 "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
12325 #endif
12326 #ifdef SQLITE_MEMDEBUG
12327 "MEMDEBUG",
12328 #endif
12329 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
12330 "MIXED_ENDIAN_64BIT_FLOAT",
12331 #endif
12332 #ifdef SQLITE_NO_SYNC
12333 "NO_SYNC",
12334 #endif
12335 #ifdef SQLITE_OMIT_ALTERTABLE
12336 "OMIT_ALTERTABLE",
12337 #endif
12338 #ifdef SQLITE_OMIT_ANALYZE
12339 "OMIT_ANALYZE",
12340 #endif
12341 #ifdef SQLITE_OMIT_ATTACH
12342 "OMIT_ATTACH",
12343 #endif
12344 #ifdef SQLITE_OMIT_AUTHORIZATION
12345 "OMIT_AUTHORIZATION",
12346 #endif
12347 #ifdef SQLITE_OMIT_AUTOINCREMENT
12348 "OMIT_AUTOINCREMENT",
12349 #endif
12350 #ifdef SQLITE_OMIT_AUTOINIT
12351 "OMIT_AUTOINIT",
12352 #endif
12353 #ifdef SQLITE_OMIT_AUTOMATIC_INDEX
12354 "OMIT_AUTOMATIC_INDEX",
12355 #endif
12356 #ifdef SQLITE_OMIT_AUTORESET
12357 "OMIT_AUTORESET",
12358 #endif
12359 #ifdef SQLITE_OMIT_AUTOVACUUM
12360 "OMIT_AUTOVACUUM",
12361 #endif
12362 #ifdef SQLITE_OMIT_BETWEEN_OPTIMIZATION
12363 "OMIT_BETWEEN_OPTIMIZATION",
12364 #endif
12365 #ifdef SQLITE_OMIT_BLOB_LITERAL
12366 "OMIT_BLOB_LITERAL",
12367 #endif
12368 #ifdef SQLITE_OMIT_BTREECOUNT
12369 "OMIT_BTREECOUNT",
12370 #endif
12371 #ifdef SQLITE_OMIT_BUILTIN_TEST
12372 "OMIT_BUILTIN_TEST",
12373 #endif
12374 #ifdef SQLITE_OMIT_CAST
12375 "OMIT_CAST",
12376 #endif
12377 #ifdef SQLITE_OMIT_CHECK
12378 "OMIT_CHECK",
12379 #endif
12380 /* // redundant
12381 ** #ifdef SQLITE_OMIT_COMPILEOPTION_DIAGS
12382 ** "OMIT_COMPILEOPTION_DIAGS",
12383 ** #endif
12385 #ifdef SQLITE_OMIT_COMPLETE
12386 "OMIT_COMPLETE",
12387 #endif
12388 #ifdef SQLITE_OMIT_COMPOUND_SELECT
12389 "OMIT_COMPOUND_SELECT",
12390 #endif
12391 #ifdef SQLITE_OMIT_DATETIME_FUNCS
12392 "OMIT_DATETIME_FUNCS",
12393 #endif
12394 #ifdef SQLITE_OMIT_DECLTYPE
12395 "OMIT_DECLTYPE",
12396 #endif
12397 #ifdef SQLITE_OMIT_DEPRECATED
12398 "OMIT_DEPRECATED",
12399 #endif
12400 #ifdef SQLITE_OMIT_DISKIO
12401 "OMIT_DISKIO",
12402 #endif
12403 #ifdef SQLITE_OMIT_EXPLAIN
12404 "OMIT_EXPLAIN",
12405 #endif
12406 #ifdef SQLITE_OMIT_FLAG_PRAGMAS
12407 "OMIT_FLAG_PRAGMAS",
12408 #endif
12409 #ifdef SQLITE_OMIT_FLOATING_POINT
12410 "OMIT_FLOATING_POINT",
12411 #endif
12412 #ifdef SQLITE_OMIT_FOREIGN_KEY
12413 "OMIT_FOREIGN_KEY",
12414 #endif
12415 #ifdef SQLITE_OMIT_GET_TABLE
12416 "OMIT_GET_TABLE",
12417 #endif
12418 #ifdef SQLITE_OMIT_INCRBLOB
12419 "OMIT_INCRBLOB",
12420 #endif
12421 #ifdef SQLITE_OMIT_INTEGRITY_CHECK
12422 "OMIT_INTEGRITY_CHECK",
12423 #endif
12424 #ifdef SQLITE_OMIT_LIKE_OPTIMIZATION
12425 "OMIT_LIKE_OPTIMIZATION",
12426 #endif
12427 #ifdef SQLITE_OMIT_LOAD_EXTENSION
12428 "OMIT_LOAD_EXTENSION",
12429 #endif
12430 #ifdef SQLITE_OMIT_LOCALTIME
12431 "OMIT_LOCALTIME",
12432 #endif
12433 #ifdef SQLITE_OMIT_LOOKASIDE
12434 "OMIT_LOOKASIDE",
12435 #endif
12436 #ifdef SQLITE_OMIT_MEMORYDB
12437 "OMIT_MEMORYDB",
12438 #endif
12439 #ifdef SQLITE_OMIT_MERGE_SORT
12440 "OMIT_MERGE_SORT",
12441 #endif
12442 #ifdef SQLITE_OMIT_OR_OPTIMIZATION
12443 "OMIT_OR_OPTIMIZATION",
12444 #endif
12445 #ifdef SQLITE_OMIT_PAGER_PRAGMAS
12446 "OMIT_PAGER_PRAGMAS",
12447 #endif
12448 #ifdef SQLITE_OMIT_PRAGMA
12449 "OMIT_PRAGMA",
12450 #endif
12451 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
12452 "OMIT_PROGRESS_CALLBACK",
12453 #endif
12454 #ifdef SQLITE_OMIT_QUICKBALANCE
12455 "OMIT_QUICKBALANCE",
12456 #endif
12457 #ifdef SQLITE_OMIT_REINDEX
12458 "OMIT_REINDEX",
12459 #endif
12460 #ifdef SQLITE_OMIT_SCHEMA_PRAGMAS
12461 "OMIT_SCHEMA_PRAGMAS",
12462 #endif
12463 #ifdef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
12464 "OMIT_SCHEMA_VERSION_PRAGMAS",
12465 #endif
12466 #ifdef SQLITE_OMIT_SHARED_CACHE
12467 "OMIT_SHARED_CACHE",
12468 #endif
12469 #ifdef SQLITE_OMIT_SUBQUERY
12470 "OMIT_SUBQUERY",
12471 #endif
12472 #ifdef SQLITE_OMIT_TCL_VARIABLE
12473 "OMIT_TCL_VARIABLE",
12474 #endif
12475 #ifdef SQLITE_OMIT_TEMPDB
12476 "OMIT_TEMPDB",
12477 #endif
12478 #ifdef SQLITE_OMIT_TRACE
12479 "OMIT_TRACE",
12480 #endif
12481 #ifdef SQLITE_OMIT_TRIGGER
12482 "OMIT_TRIGGER",
12483 #endif
12484 #ifdef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
12485 "OMIT_TRUNCATE_OPTIMIZATION",
12486 #endif
12487 #ifdef SQLITE_OMIT_UTF16
12488 "OMIT_UTF16",
12489 #endif
12490 #ifdef SQLITE_OMIT_VACUUM
12491 "OMIT_VACUUM",
12492 #endif
12493 #ifdef SQLITE_OMIT_VIEW
12494 "OMIT_VIEW",
12495 #endif
12496 #ifdef SQLITE_OMIT_VIRTUALTABLE
12497 "OMIT_VIRTUALTABLE",
12498 #endif
12499 #ifdef SQLITE_OMIT_WAL
12500 "OMIT_WAL",
12501 #endif
12502 #ifdef SQLITE_OMIT_WSD
12503 "OMIT_WSD",
12504 #endif
12505 #ifdef SQLITE_OMIT_XFER_OPT
12506 "OMIT_XFER_OPT",
12507 #endif
12508 #ifdef SQLITE_PERFORMANCE_TRACE
12509 "PERFORMANCE_TRACE",
12510 #endif
12511 #ifdef SQLITE_PROXY_DEBUG
12512 "PROXY_DEBUG",
12513 #endif
12514 #ifdef SQLITE_SECURE_DELETE
12515 "SECURE_DELETE",
12516 #endif
12517 #ifdef SQLITE_SMALL_STACK
12518 "SMALL_STACK",
12519 #endif
12520 #ifdef SQLITE_SOUNDEX
12521 "SOUNDEX",
12522 #endif
12523 #ifdef SQLITE_TCL
12524 "TCL",
12525 #endif
12526 #ifdef SQLITE_TEMP_STORE
12527 "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
12528 #endif
12529 #ifdef SQLITE_TEST
12530 "TEST",
12531 #endif
12532 #ifdef SQLITE_THREADSAFE
12533 "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
12534 #endif
12535 #ifdef SQLITE_USE_ALLOCA
12536 "USE_ALLOCA",
12537 #endif
12538 #ifdef SQLITE_ZERO_MALLOC
12539 "ZERO_MALLOC"
12540 #endif
12544 ** Given the name of a compile-time option, return true if that option
12545 ** was used and false if not.
12547 ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
12548 ** is not required for a match.
12550 SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
12551 int i, n;
12552 if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
12553 n = sqlite3Strlen30(zOptName);
12555 /* Since ArraySize(azCompileOpt) is normally in single digits, a
12556 ** linear search is adequate. No need for a binary search. */
12557 for(i=0; i<ArraySize(azCompileOpt); i++){
12558 if( (sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0)
12559 && ( (azCompileOpt[i][n]==0) || (azCompileOpt[i][n]=='=') ) ) return 1;
12561 return 0;
12565 ** Return the N-th compile-time option string. If N is out of range,
12566 ** return a NULL pointer.
12568 SQLITE_API const char *sqlite3_compileoption_get(int N){
12569 if( N>=0 && N<ArraySize(azCompileOpt) ){
12570 return azCompileOpt[N];
12572 return 0;
12575 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
12577 /************** End of ctime.c ***********************************************/
12578 /************** Begin file status.c ******************************************/
12580 ** 2008 June 18
12582 ** The author disclaims copyright to this source code. In place of
12583 ** a legal notice, here is a blessing:
12585 ** May you do good and not evil.
12586 ** May you find forgiveness for yourself and forgive others.
12587 ** May you share freely, never taking more than you give.
12589 *************************************************************************
12591 ** This module implements the sqlite3_status() interface and related
12592 ** functionality.
12594 /************** Include vdbeInt.h in the middle of status.c ******************/
12595 /************** Begin file vdbeInt.h *****************************************/
12597 ** 2003 September 6
12599 ** The author disclaims copyright to this source code. In place of
12600 ** a legal notice, here is a blessing:
12602 ** May you do good and not evil.
12603 ** May you find forgiveness for yourself and forgive others.
12604 ** May you share freely, never taking more than you give.
12606 *************************************************************************
12607 ** This is the header file for information that is private to the
12608 ** VDBE. This information used to all be at the top of the single
12609 ** source code file "vdbe.c". When that file became too big (over
12610 ** 6000 lines long) it was split up into several smaller files and
12611 ** this header information was factored out.
12613 #ifndef _VDBEINT_H_
12614 #define _VDBEINT_H_
12617 ** SQL is translated into a sequence of instructions to be
12618 ** executed by a virtual machine. Each instruction is an instance
12619 ** of the following structure.
12621 typedef struct VdbeOp Op;
12624 ** Boolean values
12626 typedef unsigned char Bool;
12628 /* Opaque type used by code in vdbesort.c */
12629 typedef struct VdbeSorter VdbeSorter;
12632 ** A cursor is a pointer into a single BTree within a database file.
12633 ** The cursor can seek to a BTree entry with a particular key, or
12634 ** loop over all entries of the Btree. You can also insert new BTree
12635 ** entries or retrieve the key or data from the entry that the cursor
12636 ** is currently pointing to.
12638 ** Every cursor that the virtual machine has open is represented by an
12639 ** instance of the following structure.
12641 struct VdbeCursor {
12642 BtCursor *pCursor; /* The cursor structure of the backend */
12643 Btree *pBt; /* Separate file holding temporary table */
12644 KeyInfo *pKeyInfo; /* Info about index keys needed by index cursors */
12645 int iDb; /* Index of cursor database in db->aDb[] (or -1) */
12646 int pseudoTableReg; /* Register holding pseudotable content. */
12647 int nField; /* Number of fields in the header */
12648 Bool zeroed; /* True if zeroed out and ready for reuse */
12649 Bool rowidIsValid; /* True if lastRowid is valid */
12650 Bool atFirst; /* True if pointing to first entry */
12651 Bool useRandomRowid; /* Generate new record numbers semi-randomly */
12652 Bool nullRow; /* True if pointing to a row with no data */
12653 Bool deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */
12654 Bool isTable; /* True if a table requiring integer keys */
12655 Bool isIndex; /* True if an index containing keys only - no data */
12656 Bool isOrdered; /* True if the underlying table is BTREE_UNORDERED */
12657 Bool isSorter; /* True if a new-style sorter */
12658 sqlite3_vtab_cursor *pVtabCursor; /* The cursor for a virtual table */
12659 const sqlite3_module *pModule; /* Module for cursor pVtabCursor */
12660 i64 seqCount; /* Sequence counter */
12661 i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */
12662 i64 lastRowid; /* Last rowid from a Next or NextIdx operation */
12663 VdbeSorter *pSorter; /* Sorter object for OP_SorterOpen cursors */
12665 /* Result of last sqlite3BtreeMoveto() done by an OP_NotExists or
12666 ** OP_IsUnique opcode on this cursor. */
12667 int seekResult;
12669 /* Cached information about the header for the data record that the
12670 ** cursor is currently pointing to. Only valid if cacheStatus matches
12671 ** Vdbe.cacheCtr. Vdbe.cacheCtr will never take on the value of
12672 ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
12673 ** the cache is out of date.
12675 ** aRow might point to (ephemeral) data for the current row, or it might
12676 ** be NULL.
12678 u32 cacheStatus; /* Cache is valid if this matches Vdbe.cacheCtr */
12679 int payloadSize; /* Total number of bytes in the record */
12680 u32 *aType; /* Type values for all entries in the record */
12681 u32 *aOffset; /* Cached offsets to the start of each columns data */
12682 u8 *aRow; /* Data for the current row, if all on one page */
12684 typedef struct VdbeCursor VdbeCursor;
12687 ** When a sub-program is executed (OP_Program), a structure of this type
12688 ** is allocated to store the current value of the program counter, as
12689 ** well as the current memory cell array and various other frame specific
12690 ** values stored in the Vdbe struct. When the sub-program is finished,
12691 ** these values are copied back to the Vdbe from the VdbeFrame structure,
12692 ** restoring the state of the VM to as it was before the sub-program
12693 ** began executing.
12695 ** The memory for a VdbeFrame object is allocated and managed by a memory
12696 ** cell in the parent (calling) frame. When the memory cell is deleted or
12697 ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
12698 ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
12699 ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
12700 ** this instead of deleting the VdbeFrame immediately is to avoid recursive
12701 ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
12702 ** child frame are released.
12704 ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
12705 ** set to NULL if the currently executing frame is the main program.
12707 typedef struct VdbeFrame VdbeFrame;
12708 struct VdbeFrame {
12709 Vdbe *v; /* VM this frame belongs to */
12710 int pc; /* Program Counter in parent (calling) frame */
12711 Op *aOp; /* Program instructions for parent frame */
12712 int nOp; /* Size of aOp array */
12713 Mem *aMem; /* Array of memory cells for parent frame */
12714 int nMem; /* Number of entries in aMem */
12715 VdbeCursor **apCsr; /* Array of Vdbe cursors for parent frame */
12716 u16 nCursor; /* Number of entries in apCsr */
12717 void *token; /* Copy of SubProgram.token */
12718 int nChildMem; /* Number of memory cells for child frame */
12719 int nChildCsr; /* Number of cursors for child frame */
12720 i64 lastRowid; /* Last insert rowid (sqlite3.lastRowid) */
12721 int nChange; /* Statement changes (Vdbe.nChanges) */
12722 VdbeFrame *pParent; /* Parent of this frame, or NULL if parent is main */
12725 #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
12728 ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
12730 #define CACHE_STALE 0
12733 ** Internally, the vdbe manipulates nearly all SQL values as Mem
12734 ** structures. Each Mem struct may cache multiple representations (string,
12735 ** integer etc.) of the same value.
12737 struct Mem {
12738 sqlite3 *db; /* The associated database connection */
12739 char *z; /* String or BLOB value */
12740 double r; /* Real value */
12741 union {
12742 i64 i; /* Integer value used when MEM_Int is set in flags */
12743 int nZero; /* Used when bit MEM_Zero is set in flags */
12744 FuncDef *pDef; /* Used only when flags==MEM_Agg */
12745 RowSet *pRowSet; /* Used only when flags==MEM_RowSet */
12746 VdbeFrame *pFrame; /* Used when flags==MEM_Frame */
12747 } u;
12748 int n; /* Number of characters in string value, excluding '\0' */
12749 u16 flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
12750 u8 type; /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
12751 u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
12752 #ifdef SQLITE_DEBUG
12753 Mem *pScopyFrom; /* This Mem is a shallow copy of pScopyFrom */
12754 void *pFiller; /* So that sizeof(Mem) is a multiple of 8 */
12755 #endif
12756 void (*xDel)(void *); /* If not null, call this function to delete Mem.z */
12757 char *zMalloc; /* Dynamic buffer allocated by sqlite3_malloc() */
12760 /* One or more of the following flags are set to indicate the validOK
12761 ** representations of the value stored in the Mem struct.
12763 ** If the MEM_Null flag is set, then the value is an SQL NULL value.
12764 ** No other flags may be set in this case.
12766 ** If the MEM_Str flag is set then Mem.z points at a string representation.
12767 ** Usually this is encoded in the same unicode encoding as the main
12768 ** database (see below for exceptions). If the MEM_Term flag is also
12769 ** set, then the string is nul terminated. The MEM_Int and MEM_Real
12770 ** flags may coexist with the MEM_Str flag.
12772 #define MEM_Null 0x0001 /* Value is NULL */
12773 #define MEM_Str 0x0002 /* Value is a string */
12774 #define MEM_Int 0x0004 /* Value is an integer */
12775 #define MEM_Real 0x0008 /* Value is a real number */
12776 #define MEM_Blob 0x0010 /* Value is a BLOB */
12777 #define MEM_RowSet 0x0020 /* Value is a RowSet object */
12778 #define MEM_Frame 0x0040 /* Value is a VdbeFrame object */
12779 #define MEM_Invalid 0x0080 /* Value is undefined */
12780 #define MEM_TypeMask 0x00ff /* Mask of type bits */
12782 /* Whenever Mem contains a valid string or blob representation, one of
12783 ** the following flags must be set to determine the memory management
12784 ** policy for Mem.z. The MEM_Term flag tells us whether or not the
12785 ** string is \000 or \u0000 terminated
12787 #define MEM_Term 0x0200 /* String rep is nul terminated */
12788 #define MEM_Dyn 0x0400 /* Need to call sqliteFree() on Mem.z */
12789 #define MEM_Static 0x0800 /* Mem.z points to a static string */
12790 #define MEM_Ephem 0x1000 /* Mem.z points to an ephemeral string */
12791 #define MEM_Agg 0x2000 /* Mem.z points to an agg function context */
12792 #define MEM_Zero 0x4000 /* Mem.i contains count of 0s appended to blob */
12793 #ifdef SQLITE_OMIT_INCRBLOB
12794 #undef MEM_Zero
12795 #define MEM_Zero 0x0000
12796 #endif
12799 ** Clear any existing type flags from a Mem and replace them with f
12801 #define MemSetTypeFlag(p, f) \
12802 ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
12805 ** Return true if a memory cell is not marked as invalid. This macro
12806 ** is for use inside assert() statements only.
12808 #ifdef SQLITE_DEBUG
12809 #define memIsValid(M) ((M)->flags & MEM_Invalid)==0
12810 #endif
12813 /* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains
12814 ** additional information about auxiliary information bound to arguments
12815 ** of the function. This is used to implement the sqlite3_get_auxdata()
12816 ** and sqlite3_set_auxdata() APIs. The "auxdata" is some auxiliary data
12817 ** that can be associated with a constant argument to a function. This
12818 ** allows functions such as "regexp" to compile their constant regular
12819 ** expression argument once and reused the compiled code for multiple
12820 ** invocations.
12822 struct VdbeFunc {
12823 FuncDef *pFunc; /* The definition of the function */
12824 int nAux; /* Number of entries allocated for apAux[] */
12825 struct AuxData {
12826 void *pAux; /* Aux data for the i-th argument */
12827 void (*xDelete)(void *); /* Destructor for the aux data */
12828 } apAux[1]; /* One slot for each function argument */
12832 ** The "context" argument for a installable function. A pointer to an
12833 ** instance of this structure is the first argument to the routines used
12834 ** implement the SQL functions.
12836 ** There is a typedef for this structure in sqlite.h. So all routines,
12837 ** even the public interface to SQLite, can use a pointer to this structure.
12838 ** But this file is the only place where the internal details of this
12839 ** structure are known.
12841 ** This structure is defined inside of vdbeInt.h because it uses substructures
12842 ** (Mem) which are only defined there.
12844 struct sqlite3_context {
12845 FuncDef *pFunc; /* Pointer to function information. MUST BE FIRST */
12846 VdbeFunc *pVdbeFunc; /* Auxilary data, if created. */
12847 Mem s; /* The return value is stored here */
12848 Mem *pMem; /* Memory cell used to store aggregate context */
12849 int isError; /* Error code returned by the function. */
12850 CollSeq *pColl; /* Collating sequence */
12854 ** An instance of the virtual machine. This structure contains the complete
12855 ** state of the virtual machine.
12857 ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
12858 ** is really a pointer to an instance of this structure.
12860 ** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
12861 ** any virtual table method invocations made by the vdbe program. It is
12862 ** set to 2 for xDestroy method calls and 1 for all other methods. This
12863 ** variable is used for two purposes: to allow xDestroy methods to execute
12864 ** "DROP TABLE" statements and to prevent some nasty side effects of
12865 ** malloc failure when SQLite is invoked recursively by a virtual table
12866 ** method function.
12868 struct Vdbe {
12869 sqlite3 *db; /* The database connection that owns this statement */
12870 Op *aOp; /* Space to hold the virtual machine's program */
12871 Mem *aMem; /* The memory locations */
12872 Mem **apArg; /* Arguments to currently executing user function */
12873 Mem *aColName; /* Column names to return */
12874 Mem *pResultSet; /* Pointer to an array of results */
12875 int nMem; /* Number of memory locations currently allocated */
12876 int nOp; /* Number of instructions in the program */
12877 int nOpAlloc; /* Number of slots allocated for aOp[] */
12878 int nLabel; /* Number of labels used */
12879 int nLabelAlloc; /* Number of slots allocated in aLabel[] */
12880 int *aLabel; /* Space to hold the labels */
12881 u16 nResColumn; /* Number of columns in one row of the result set */
12882 u16 nCursor; /* Number of slots in apCsr[] */
12883 u32 magic; /* Magic number for sanity checking */
12884 char *zErrMsg; /* Error message written here */
12885 Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */
12886 VdbeCursor **apCsr; /* One element of this array for each open cursor */
12887 Mem *aVar; /* Values for the OP_Variable opcode. */
12888 char **azVar; /* Name of variables */
12889 ynVar nVar; /* Number of entries in aVar[] */
12890 ynVar nzVar; /* Number of entries in azVar[] */
12891 u32 cacheCtr; /* VdbeCursor row cache generation counter */
12892 int pc; /* The program counter */
12893 int rc; /* Value to return */
12894 u8 errorAction; /* Recovery action to do in case of an error */
12895 u8 explain; /* True if EXPLAIN present on SQL command */
12896 u8 changeCntOn; /* True to update the change-counter */
12897 u8 expired; /* True if the VM needs to be recompiled */
12898 u8 runOnlyOnce; /* Automatically expire on reset */
12899 u8 minWriteFileFormat; /* Minimum file format for writable database files */
12900 u8 inVtabMethod; /* See comments above */
12901 u8 usesStmtJournal; /* True if uses a statement journal */
12902 u8 readOnly; /* True for read-only statements */
12903 u8 isPrepareV2; /* True if prepared with prepare_v2() */
12904 int nChange; /* Number of db changes made since last reset */
12905 yDbMask btreeMask; /* Bitmask of db->aDb[] entries referenced */
12906 yDbMask lockMask; /* Subset of btreeMask that requires a lock */
12907 int iStatement; /* Statement number (or 0 if has not opened stmt) */
12908 int aCounter[3]; /* Counters used by sqlite3_stmt_status() */
12909 #ifndef SQLITE_OMIT_TRACE
12910 i64 startTime; /* Time when query started - used for profiling */
12911 #endif
12912 i64 nFkConstraint; /* Number of imm. FK constraints this VM */
12913 i64 nStmtDefCons; /* Number of def. constraints when stmt started */
12914 char *zSql; /* Text of the SQL statement that generated this */
12915 void *pFree; /* Free this when deleting the vdbe */
12916 #ifdef SQLITE_DEBUG
12917 FILE *trace; /* Write an execution trace here, if not NULL */
12918 #endif
12919 VdbeFrame *pFrame; /* Parent frame */
12920 VdbeFrame *pDelFrame; /* List of frame objects to free on VM reset */
12921 int nFrame; /* Number of frames in pFrame list */
12922 u32 expmask; /* Binding to these vars invalidates VM */
12923 SubProgram *pProgram; /* Linked list of all sub-programs used by VM */
12927 ** The following are allowed values for Vdbe.magic
12929 #define VDBE_MAGIC_INIT 0x26bceaa5 /* Building a VDBE program */
12930 #define VDBE_MAGIC_RUN 0xbdf20da3 /* VDBE is ready to execute */
12931 #define VDBE_MAGIC_HALT 0x519c2973 /* VDBE has completed execution */
12932 #define VDBE_MAGIC_DEAD 0xb606c3c8 /* The VDBE has been deallocated */
12935 ** Function prototypes
12937 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
12938 void sqliteVdbePopStack(Vdbe*,int);
12939 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
12940 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
12941 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
12942 #endif
12943 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
12944 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
12945 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
12946 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
12947 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc*, int);
12949 int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
12950 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*);
12951 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor *, i64 *);
12952 SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
12953 SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
12954 SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
12955 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
12956 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
12957 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
12958 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
12959 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
12960 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
12961 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
12962 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
12963 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
12964 #ifdef SQLITE_OMIT_FLOATING_POINT
12965 # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
12966 #else
12967 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double);
12968 #endif
12969 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
12970 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
12971 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
12972 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
12973 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);
12974 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
12975 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
12976 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
12977 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
12978 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
12979 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
12980 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
12981 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
12982 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p);
12983 #define MemReleaseExt(X) \
12984 if((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame)) \
12985 sqlite3VdbeMemReleaseExternal(X);
12986 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
12987 SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
12988 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
12989 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
12990 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
12991 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
12992 SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem);
12993 SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
12995 #ifdef SQLITE_OMIT_MERGE_SORT
12996 # define sqlite3VdbeSorterInit(Y,Z) SQLITE_OK
12997 # define sqlite3VdbeSorterWrite(X,Y,Z) SQLITE_OK
12998 # define sqlite3VdbeSorterClose(Y,Z)
12999 # define sqlite3VdbeSorterRowkey(Y,Z) SQLITE_OK
13000 # define sqlite3VdbeSorterRewind(X,Y,Z) SQLITE_OK
13001 # define sqlite3VdbeSorterNext(X,Y,Z) SQLITE_OK
13002 # define sqlite3VdbeSorterCompare(X,Y,Z) SQLITE_OK
13003 #else
13004 SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, VdbeCursor *);
13005 SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
13006 SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(VdbeCursor *, Mem *);
13007 SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, VdbeCursor *, int *);
13008 SQLITE_PRIVATE int sqlite3VdbeSorterRewind(sqlite3 *, VdbeCursor *, int *);
13009 SQLITE_PRIVATE int sqlite3VdbeSorterWrite(sqlite3 *, VdbeCursor *, Mem *);
13010 SQLITE_PRIVATE int sqlite3VdbeSorterCompare(VdbeCursor *, Mem *, int *);
13011 #endif
13013 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
13014 SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe*);
13015 SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe*);
13016 #else
13017 # define sqlite3VdbeEnter(X)
13018 # define sqlite3VdbeLeave(X)
13019 #endif
13021 #ifdef SQLITE_DEBUG
13022 SQLITE_PRIVATE void sqlite3VdbeMemPrepareToChange(Vdbe*,Mem*);
13023 #endif
13025 #ifndef SQLITE_OMIT_FOREIGN_KEY
13026 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
13027 #else
13028 # define sqlite3VdbeCheckFk(p,i) 0
13029 #endif
13031 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
13032 #ifdef SQLITE_DEBUG
13033 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe*);
13034 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
13035 #endif
13036 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
13038 #ifndef SQLITE_OMIT_INCRBLOB
13039 SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *);
13040 #else
13041 #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
13042 #endif
13044 #endif /* !defined(_VDBEINT_H_) */
13046 /************** End of vdbeInt.h *********************************************/
13047 /************** Continuing where we left off in status.c *********************/
13050 ** Variables in which to record status information.
13052 typedef struct sqlite3StatType sqlite3StatType;
13053 static SQLITE_WSD struct sqlite3StatType {
13054 int nowValue[10]; /* Current value */
13055 int mxValue[10]; /* Maximum value */
13056 } sqlite3Stat = { {0,}, {0,} };
13059 /* The "wsdStat" macro will resolve to the status information
13060 ** state vector. If writable static data is unsupported on the target,
13061 ** we have to locate the state vector at run-time. In the more common
13062 ** case where writable static data is supported, wsdStat can refer directly
13063 ** to the "sqlite3Stat" state vector declared above.
13065 #ifdef SQLITE_OMIT_WSD
13066 # define wsdStatInit sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
13067 # define wsdStat x[0]
13068 #else
13069 # define wsdStatInit
13070 # define wsdStat sqlite3Stat
13071 #endif
13074 ** Return the current value of a status parameter.
13076 SQLITE_PRIVATE int sqlite3StatusValue(int op){
13077 wsdStatInit;
13078 assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
13079 return wsdStat.nowValue[op];
13083 ** Add N to the value of a status record. It is assumed that the
13084 ** caller holds appropriate locks.
13086 SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
13087 wsdStatInit;
13088 assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
13089 wsdStat.nowValue[op] += N;
13090 if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
13091 wsdStat.mxValue[op] = wsdStat.nowValue[op];
13096 ** Set the value of a status to X.
13098 SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
13099 wsdStatInit;
13100 assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
13101 wsdStat.nowValue[op] = X;
13102 if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
13103 wsdStat.mxValue[op] = wsdStat.nowValue[op];
13108 ** Query status information.
13110 ** This implementation assumes that reading or writing an aligned
13111 ** 32-bit integer is an atomic operation. If that assumption is not true,
13112 ** then this routine is not threadsafe.
13114 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
13115 wsdStatInit;
13116 if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
13117 return SQLITE_MISUSE_BKPT;
13119 *pCurrent = wsdStat.nowValue[op];
13120 *pHighwater = wsdStat.mxValue[op];
13121 if( resetFlag ){
13122 wsdStat.mxValue[op] = wsdStat.nowValue[op];
13124 return SQLITE_OK;
13128 ** Query status information for a single database connection
13130 SQLITE_API int sqlite3_db_status(
13131 sqlite3 *db, /* The database connection whose status is desired */
13132 int op, /* Status verb */
13133 int *pCurrent, /* Write current value here */
13134 int *pHighwater, /* Write high-water mark here */
13135 int resetFlag /* Reset high-water mark if true */
13137 int rc = SQLITE_OK; /* Return code */
13138 sqlite3_mutex_enter(db->mutex);
13139 switch( op ){
13140 case SQLITE_DBSTATUS_LOOKASIDE_USED: {
13141 *pCurrent = db->lookaside.nOut;
13142 *pHighwater = db->lookaside.mxOut;
13143 if( resetFlag ){
13144 db->lookaside.mxOut = db->lookaside.nOut;
13146 break;
13149 case SQLITE_DBSTATUS_LOOKASIDE_HIT:
13150 case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
13151 case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
13152 testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
13153 testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
13154 testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
13155 assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
13156 assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
13157 *pCurrent = 0;
13158 *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
13159 if( resetFlag ){
13160 db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
13162 break;
13166 ** Return an approximation for the amount of memory currently used
13167 ** by all pagers associated with the given database connection. The
13168 ** highwater mark is meaningless and is returned as zero.
13170 case SQLITE_DBSTATUS_CACHE_USED: {
13171 int totalUsed = 0;
13172 int i;
13173 sqlite3BtreeEnterAll(db);
13174 for(i=0; i<db->nDb; i++){
13175 Btree *pBt = db->aDb[i].pBt;
13176 if( pBt ){
13177 Pager *pPager = sqlite3BtreePager(pBt);
13178 totalUsed += sqlite3PagerMemUsed(pPager);
13181 sqlite3BtreeLeaveAll(db);
13182 *pCurrent = totalUsed;
13183 *pHighwater = 0;
13184 break;
13188 ** *pCurrent gets an accurate estimate of the amount of memory used
13189 ** to store the schema for all databases (main, temp, and any ATTACHed
13190 ** databases. *pHighwater is set to zero.
13192 case SQLITE_DBSTATUS_SCHEMA_USED: {
13193 int i; /* Used to iterate through schemas */
13194 int nByte = 0; /* Used to accumulate return value */
13196 sqlite3BtreeEnterAll(db);
13197 db->pnBytesFreed = &nByte;
13198 for(i=0; i<db->nDb; i++){
13199 Schema *pSchema = db->aDb[i].pSchema;
13200 if( ALWAYS(pSchema!=0) ){
13201 HashElem *p;
13203 nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
13204 pSchema->tblHash.count
13205 + pSchema->trigHash.count
13206 + pSchema->idxHash.count
13207 + pSchema->fkeyHash.count
13209 nByte += sqlite3MallocSize(pSchema->tblHash.ht);
13210 nByte += sqlite3MallocSize(pSchema->trigHash.ht);
13211 nByte += sqlite3MallocSize(pSchema->idxHash.ht);
13212 nByte += sqlite3MallocSize(pSchema->fkeyHash.ht);
13214 for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
13215 sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
13217 for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
13218 sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
13222 db->pnBytesFreed = 0;
13223 sqlite3BtreeLeaveAll(db);
13225 *pHighwater = 0;
13226 *pCurrent = nByte;
13227 break;
13231 ** *pCurrent gets an accurate estimate of the amount of memory used
13232 ** to store all prepared statements.
13233 ** *pHighwater is set to zero.
13235 case SQLITE_DBSTATUS_STMT_USED: {
13236 struct Vdbe *pVdbe; /* Used to iterate through VMs */
13237 int nByte = 0; /* Used to accumulate return value */
13239 db->pnBytesFreed = &nByte;
13240 for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
13241 sqlite3VdbeDeleteObject(db, pVdbe);
13243 db->pnBytesFreed = 0;
13245 *pHighwater = 0;
13246 *pCurrent = nByte;
13248 break;
13252 ** Set *pCurrent to the total cache hits or misses encountered by all
13253 ** pagers the database handle is connected to. *pHighwater is always set
13254 ** to zero.
13256 case SQLITE_DBSTATUS_CACHE_HIT:
13257 case SQLITE_DBSTATUS_CACHE_MISS: {
13258 int i;
13259 int nRet = 0;
13260 assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
13262 for(i=0; i<db->nDb; i++){
13263 if( db->aDb[i].pBt ){
13264 Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
13265 sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
13268 *pHighwater = 0;
13269 *pCurrent = nRet;
13270 break;
13273 default: {
13274 rc = SQLITE_ERROR;
13277 sqlite3_mutex_leave(db->mutex);
13278 return rc;
13281 /************** End of status.c **********************************************/
13282 /************** Begin file date.c ********************************************/
13284 ** 2003 October 31
13286 ** The author disclaims copyright to this source code. In place of
13287 ** a legal notice, here is a blessing:
13289 ** May you do good and not evil.
13290 ** May you find forgiveness for yourself and forgive others.
13291 ** May you share freely, never taking more than you give.
13293 *************************************************************************
13294 ** This file contains the C functions that implement date and time
13295 ** functions for SQLite.
13297 ** There is only one exported symbol in this file - the function
13298 ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
13299 ** All other code has file scope.
13301 ** SQLite processes all times and dates as Julian Day numbers. The
13302 ** dates and times are stored as the number of days since noon
13303 ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
13304 ** calendar system.
13306 ** 1970-01-01 00:00:00 is JD 2440587.5
13307 ** 2000-01-01 00:00:00 is JD 2451544.5
13309 ** This implemention requires years to be expressed as a 4-digit number
13310 ** which means that only dates between 0000-01-01 and 9999-12-31 can
13311 ** be represented, even though julian day numbers allow a much wider
13312 ** range of dates.
13314 ** The Gregorian calendar system is used for all dates and times,
13315 ** even those that predate the Gregorian calendar. Historians usually
13316 ** use the Julian calendar for dates prior to 1582-10-15 and for some
13317 ** dates afterwards, depending on locale. Beware of this difference.
13319 ** The conversion algorithms are implemented based on descriptions
13320 ** in the following text:
13322 ** Jean Meeus
13323 ** Astronomical Algorithms, 2nd Edition, 1998
13324 ** ISBM 0-943396-61-1
13325 ** Willmann-Bell, Inc
13326 ** Richmond, Virginia (USA)
13328 /* #include <stdlib.h> */
13329 /* #include <assert.h> */
13330 #include <time.h>
13332 #ifndef SQLITE_OMIT_DATETIME_FUNCS
13336 ** A structure for holding a single date and time.
13338 typedef struct DateTime DateTime;
13339 struct DateTime {
13340 sqlite3_int64 iJD; /* The julian day number times 86400000 */
13341 int Y, M, D; /* Year, month, and day */
13342 int h, m; /* Hour and minutes */
13343 int tz; /* Timezone offset in minutes */
13344 double s; /* Seconds */
13345 char validYMD; /* True (1) if Y,M,D are valid */
13346 char validHMS; /* True (1) if h,m,s are valid */
13347 char validJD; /* True (1) if iJD is valid */
13348 char validTZ; /* True (1) if tz is valid */
13353 ** Convert zDate into one or more integers. Additional arguments
13354 ** come in groups of 5 as follows:
13356 ** N number of digits in the integer
13357 ** min minimum allowed value of the integer
13358 ** max maximum allowed value of the integer
13359 ** nextC first character after the integer
13360 ** pVal where to write the integers value.
13362 ** Conversions continue until one with nextC==0 is encountered.
13363 ** The function returns the number of successful conversions.
13365 static int getDigits(const char *zDate, ...){
13366 va_list ap;
13367 int val;
13368 int N;
13369 int min;
13370 int max;
13371 int nextC;
13372 int *pVal;
13373 int cnt = 0;
13374 va_start(ap, zDate);
13376 N = va_arg(ap, int);
13377 min = va_arg(ap, int);
13378 max = va_arg(ap, int);
13379 nextC = va_arg(ap, int);
13380 pVal = va_arg(ap, int*);
13381 val = 0;
13382 while( N-- ){
13383 if( !sqlite3Isdigit(*zDate) ){
13384 goto end_getDigits;
13386 val = val*10 + *zDate - '0';
13387 zDate++;
13389 if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
13390 goto end_getDigits;
13392 *pVal = val;
13393 zDate++;
13394 cnt++;
13395 }while( nextC );
13396 end_getDigits:
13397 va_end(ap);
13398 return cnt;
13402 ** Parse a timezone extension on the end of a date-time.
13403 ** The extension is of the form:
13405 ** (+/-)HH:MM
13407 ** Or the "zulu" notation:
13409 ** Z
13411 ** If the parse is successful, write the number of minutes
13412 ** of change in p->tz and return 0. If a parser error occurs,
13413 ** return non-zero.
13415 ** A missing specifier is not considered an error.
13417 static int parseTimezone(const char *zDate, DateTime *p){
13418 int sgn = 0;
13419 int nHr, nMn;
13420 int c;
13421 while( sqlite3Isspace(*zDate) ){ zDate++; }
13422 p->tz = 0;
13423 c = *zDate;
13424 if( c=='-' ){
13425 sgn = -1;
13426 }else if( c=='+' ){
13427 sgn = +1;
13428 }else if( c=='Z' || c=='z' ){
13429 zDate++;
13430 goto zulu_time;
13431 }else{
13432 return c!=0;
13434 zDate++;
13435 if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
13436 return 1;
13438 zDate += 5;
13439 p->tz = sgn*(nMn + nHr*60);
13440 zulu_time:
13441 while( sqlite3Isspace(*zDate) ){ zDate++; }
13442 return *zDate!=0;
13446 ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
13447 ** The HH, MM, and SS must each be exactly 2 digits. The
13448 ** fractional seconds FFFF can be one or more digits.
13450 ** Return 1 if there is a parsing error and 0 on success.
13452 static int parseHhMmSs(const char *zDate, DateTime *p){
13453 int h, m, s;
13454 double ms = 0.0;
13455 if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
13456 return 1;
13458 zDate += 5;
13459 if( *zDate==':' ){
13460 zDate++;
13461 if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
13462 return 1;
13464 zDate += 2;
13465 if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
13466 double rScale = 1.0;
13467 zDate++;
13468 while( sqlite3Isdigit(*zDate) ){
13469 ms = ms*10.0 + *zDate - '0';
13470 rScale *= 10.0;
13471 zDate++;
13473 ms /= rScale;
13475 }else{
13476 s = 0;
13478 p->validJD = 0;
13479 p->validHMS = 1;
13480 p->h = h;
13481 p->m = m;
13482 p->s = s + ms;
13483 if( parseTimezone(zDate, p) ) return 1;
13484 p->validTZ = (p->tz!=0)?1:0;
13485 return 0;
13489 ** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
13490 ** that the YYYY-MM-DD is according to the Gregorian calendar.
13492 ** Reference: Meeus page 61
13494 static void computeJD(DateTime *p){
13495 int Y, M, D, A, B, X1, X2;
13497 if( p->validJD ) return;
13498 if( p->validYMD ){
13499 Y = p->Y;
13500 M = p->M;
13501 D = p->D;
13502 }else{
13503 Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */
13504 M = 1;
13505 D = 1;
13507 if( M<=2 ){
13508 Y--;
13509 M += 12;
13511 A = Y/100;
13512 B = 2 - A + (A/4);
13513 X1 = 36525*(Y+4716)/100;
13514 X2 = 306001*(M+1)/10000;
13515 p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
13516 p->validJD = 1;
13517 if( p->validHMS ){
13518 p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
13519 if( p->validTZ ){
13520 p->iJD -= p->tz*60000;
13521 p->validYMD = 0;
13522 p->validHMS = 0;
13523 p->validTZ = 0;
13529 ** Parse dates of the form
13531 ** YYYY-MM-DD HH:MM:SS.FFF
13532 ** YYYY-MM-DD HH:MM:SS
13533 ** YYYY-MM-DD HH:MM
13534 ** YYYY-MM-DD
13536 ** Write the result into the DateTime structure and return 0
13537 ** on success and 1 if the input string is not a well-formed
13538 ** date.
13540 static int parseYyyyMmDd(const char *zDate, DateTime *p){
13541 int Y, M, D, neg;
13543 if( zDate[0]=='-' ){
13544 zDate++;
13545 neg = 1;
13546 }else{
13547 neg = 0;
13549 if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
13550 return 1;
13552 zDate += 10;
13553 while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
13554 if( parseHhMmSs(zDate, p)==0 ){
13555 /* We got the time */
13556 }else if( *zDate==0 ){
13557 p->validHMS = 0;
13558 }else{
13559 return 1;
13561 p->validJD = 0;
13562 p->validYMD = 1;
13563 p->Y = neg ? -Y : Y;
13564 p->M = M;
13565 p->D = D;
13566 if( p->validTZ ){
13567 computeJD(p);
13569 return 0;
13573 ** Set the time to the current time reported by the VFS.
13575 ** Return the number of errors.
13577 static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
13578 sqlite3 *db = sqlite3_context_db_handle(context);
13579 if( sqlite3OsCurrentTimeInt64(db->pVfs, &p->iJD)==SQLITE_OK ){
13580 p->validJD = 1;
13581 return 0;
13582 }else{
13583 return 1;
13588 ** Attempt to parse the given string into a Julian Day Number. Return
13589 ** the number of errors.
13591 ** The following are acceptable forms for the input string:
13593 ** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
13594 ** DDDD.DD
13595 ** now
13597 ** In the first form, the +/-HH:MM is always optional. The fractional
13598 ** seconds extension (the ".FFF") is optional. The seconds portion
13599 ** (":SS.FFF") is option. The year and date can be omitted as long
13600 ** as there is a time string. The time string can be omitted as long
13601 ** as there is a year and date.
13603 static int parseDateOrTime(
13604 sqlite3_context *context,
13605 const char *zDate,
13606 DateTime *p
13608 double r;
13609 if( parseYyyyMmDd(zDate,p)==0 ){
13610 return 0;
13611 }else if( parseHhMmSs(zDate, p)==0 ){
13612 return 0;
13613 }else if( sqlite3StrICmp(zDate,"now")==0){
13614 return setDateTimeToCurrent(context, p);
13615 }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
13616 p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
13617 p->validJD = 1;
13618 return 0;
13620 return 1;
13624 ** Compute the Year, Month, and Day from the julian day number.
13626 static void computeYMD(DateTime *p){
13627 int Z, A, B, C, D, E, X1;
13628 if( p->validYMD ) return;
13629 if( !p->validJD ){
13630 p->Y = 2000;
13631 p->M = 1;
13632 p->D = 1;
13633 }else{
13634 Z = (int)((p->iJD + 43200000)/86400000);
13635 A = (int)((Z - 1867216.25)/36524.25);
13636 A = Z + 1 + A - (A/4);
13637 B = A + 1524;
13638 C = (int)((B - 122.1)/365.25);
13639 D = (36525*C)/100;
13640 E = (int)((B-D)/30.6001);
13641 X1 = (int)(30.6001*E);
13642 p->D = B - D - X1;
13643 p->M = E<14 ? E-1 : E-13;
13644 p->Y = p->M>2 ? C - 4716 : C - 4715;
13646 p->validYMD = 1;
13650 ** Compute the Hour, Minute, and Seconds from the julian day number.
13652 static void computeHMS(DateTime *p){
13653 int s;
13654 if( p->validHMS ) return;
13655 computeJD(p);
13656 s = (int)((p->iJD + 43200000) % 86400000);
13657 p->s = s/1000.0;
13658 s = (int)p->s;
13659 p->s -= s;
13660 p->h = s/3600;
13661 s -= p->h*3600;
13662 p->m = s/60;
13663 p->s += s - p->m*60;
13664 p->validHMS = 1;
13668 ** Compute both YMD and HMS
13670 static void computeYMD_HMS(DateTime *p){
13671 computeYMD(p);
13672 computeHMS(p);
13676 ** Clear the YMD and HMS and the TZ
13678 static void clearYMD_HMS_TZ(DateTime *p){
13679 p->validYMD = 0;
13680 p->validHMS = 0;
13681 p->validTZ = 0;
13685 ** On recent Windows platforms, the localtime_s() function is available
13686 ** as part of the "Secure CRT". It is essentially equivalent to
13687 ** localtime_r() available under most POSIX platforms, except that the
13688 ** order of the parameters is reversed.
13690 ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
13692 ** If the user has not indicated to use localtime_r() or localtime_s()
13693 ** already, check for an MSVC build environment that provides
13694 ** localtime_s().
13696 #if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
13697 defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
13698 #define HAVE_LOCALTIME_S 1
13699 #endif
13701 #ifndef SQLITE_OMIT_LOCALTIME
13703 ** The following routine implements the rough equivalent of localtime_r()
13704 ** using whatever operating-system specific localtime facility that
13705 ** is available. This routine returns 0 on success and
13706 ** non-zero on any kind of error.
13708 ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
13709 ** routine will always fail.
13711 static int osLocaltime(time_t *t, struct tm *pTm){
13712 int rc;
13713 #if (!defined(HAVE_LOCALTIME_R) || !HAVE_LOCALTIME_R) \
13714 && (!defined(HAVE_LOCALTIME_S) || !HAVE_LOCALTIME_S)
13715 struct tm *pX;
13716 #if SQLITE_THREADSAFE>0
13717 sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
13718 #endif
13719 sqlite3_mutex_enter(mutex);
13720 pX = localtime(t);
13721 #ifndef SQLITE_OMIT_BUILTIN_TEST
13722 if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
13723 #endif
13724 if( pX ) *pTm = *pX;
13725 sqlite3_mutex_leave(mutex);
13726 rc = pX==0;
13727 #else
13728 #ifndef SQLITE_OMIT_BUILTIN_TEST
13729 if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
13730 #endif
13731 #if defined(HAVE_LOCALTIME_R) && HAVE_LOCALTIME_R
13732 rc = localtime_r(t, pTm)==0;
13733 #else
13734 rc = localtime_s(pTm, t);
13735 #endif /* HAVE_LOCALTIME_R */
13736 #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
13737 return rc;
13739 #endif /* SQLITE_OMIT_LOCALTIME */
13742 #ifndef SQLITE_OMIT_LOCALTIME
13744 ** Compute the difference (in milliseconds) between localtime and UTC
13745 ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
13746 ** return this value and set *pRc to SQLITE_OK.
13748 ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
13749 ** is undefined in this case.
13751 static sqlite3_int64 localtimeOffset(
13752 DateTime *p, /* Date at which to calculate offset */
13753 sqlite3_context *pCtx, /* Write error here if one occurs */
13754 int *pRc /* OUT: Error code. SQLITE_OK or ERROR */
13756 DateTime x, y;
13757 time_t t;
13758 struct tm sLocal;
13760 /* Initialize the contents of sLocal to avoid a compiler warning. */
13761 memset(&sLocal, 0, sizeof(sLocal));
13763 x = *p;
13764 computeYMD_HMS(&x);
13765 if( x.Y<1971 || x.Y>=2038 ){
13766 x.Y = 2000;
13767 x.M = 1;
13768 x.D = 1;
13769 x.h = 0;
13770 x.m = 0;
13771 x.s = 0.0;
13772 } else {
13773 int s = (int)(x.s + 0.5);
13774 x.s = s;
13776 x.tz = 0;
13777 x.validJD = 0;
13778 computeJD(&x);
13779 t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
13780 if( osLocaltime(&t, &sLocal) ){
13781 sqlite3_result_error(pCtx, "local time unavailable", -1);
13782 *pRc = SQLITE_ERROR;
13783 return 0;
13785 y.Y = sLocal.tm_year + 1900;
13786 y.M = sLocal.tm_mon + 1;
13787 y.D = sLocal.tm_mday;
13788 y.h = sLocal.tm_hour;
13789 y.m = sLocal.tm_min;
13790 y.s = sLocal.tm_sec;
13791 y.validYMD = 1;
13792 y.validHMS = 1;
13793 y.validJD = 0;
13794 y.validTZ = 0;
13795 computeJD(&y);
13796 *pRc = SQLITE_OK;
13797 return y.iJD - x.iJD;
13799 #endif /* SQLITE_OMIT_LOCALTIME */
13802 ** Process a modifier to a date-time stamp. The modifiers are
13803 ** as follows:
13805 ** NNN days
13806 ** NNN hours
13807 ** NNN minutes
13808 ** NNN.NNNN seconds
13809 ** NNN months
13810 ** NNN years
13811 ** start of month
13812 ** start of year
13813 ** start of week
13814 ** start of day
13815 ** weekday N
13816 ** unixepoch
13817 ** localtime
13818 ** utc
13820 ** Return 0 on success and 1 if there is any kind of error. If the error
13821 ** is in a system call (i.e. localtime()), then an error message is written
13822 ** to context pCtx. If the error is an unrecognized modifier, no error is
13823 ** written to pCtx.
13825 static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){
13826 int rc = 1;
13827 int n;
13828 double r;
13829 char *z, zBuf[30];
13830 z = zBuf;
13831 for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
13832 z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
13834 z[n] = 0;
13835 switch( z[0] ){
13836 #ifndef SQLITE_OMIT_LOCALTIME
13837 case 'l': {
13838 /* localtime
13840 ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
13841 ** show local time.
13843 if( strcmp(z, "localtime")==0 ){
13844 computeJD(p);
13845 p->iJD += localtimeOffset(p, pCtx, &rc);
13846 clearYMD_HMS_TZ(p);
13848 break;
13850 #endif
13851 case 'u': {
13853 ** unixepoch
13855 ** Treat the current value of p->iJD as the number of
13856 ** seconds since 1970. Convert to a real julian day number.
13858 if( strcmp(z, "unixepoch")==0 && p->validJD ){
13859 p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
13860 clearYMD_HMS_TZ(p);
13861 rc = 0;
13863 #ifndef SQLITE_OMIT_LOCALTIME
13864 else if( strcmp(z, "utc")==0 ){
13865 sqlite3_int64 c1;
13866 computeJD(p);
13867 c1 = localtimeOffset(p, pCtx, &rc);
13868 if( rc==SQLITE_OK ){
13869 p->iJD -= c1;
13870 clearYMD_HMS_TZ(p);
13871 p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
13874 #endif
13875 break;
13877 case 'w': {
13879 ** weekday N
13881 ** Move the date to the same time on the next occurrence of
13882 ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
13883 ** date is already on the appropriate weekday, this is a no-op.
13885 if( strncmp(z, "weekday ", 8)==0
13886 && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
13887 && (n=(int)r)==r && n>=0 && r<7 ){
13888 sqlite3_int64 Z;
13889 computeYMD_HMS(p);
13890 p->validTZ = 0;
13891 p->validJD = 0;
13892 computeJD(p);
13893 Z = ((p->iJD + 129600000)/86400000) % 7;
13894 if( Z>n ) Z -= 7;
13895 p->iJD += (n - Z)*86400000;
13896 clearYMD_HMS_TZ(p);
13897 rc = 0;
13899 break;
13901 case 's': {
13903 ** start of TTTTT
13905 ** Move the date backwards to the beginning of the current day,
13906 ** or month or year.
13908 if( strncmp(z, "start of ", 9)!=0 ) break;
13909 z += 9;
13910 computeYMD(p);
13911 p->validHMS = 1;
13912 p->h = p->m = 0;
13913 p->s = 0.0;
13914 p->validTZ = 0;
13915 p->validJD = 0;
13916 if( strcmp(z,"month")==0 ){
13917 p->D = 1;
13918 rc = 0;
13919 }else if( strcmp(z,"year")==0 ){
13920 computeYMD(p);
13921 p->M = 1;
13922 p->D = 1;
13923 rc = 0;
13924 }else if( strcmp(z,"day")==0 ){
13925 rc = 0;
13927 break;
13929 case '+':
13930 case '-':
13931 case '0':
13932 case '1':
13933 case '2':
13934 case '3':
13935 case '4':
13936 case '5':
13937 case '6':
13938 case '7':
13939 case '8':
13940 case '9': {
13941 double rRounder;
13942 for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
13943 if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
13944 rc = 1;
13945 break;
13947 if( z[n]==':' ){
13948 /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
13949 ** specified number of hours, minutes, seconds, and fractional seconds
13950 ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be
13951 ** omitted.
13953 const char *z2 = z;
13954 DateTime tx;
13955 sqlite3_int64 day;
13956 if( !sqlite3Isdigit(*z2) ) z2++;
13957 memset(&tx, 0, sizeof(tx));
13958 if( parseHhMmSs(z2, &tx) ) break;
13959 computeJD(&tx);
13960 tx.iJD -= 43200000;
13961 day = tx.iJD/86400000;
13962 tx.iJD -= day*86400000;
13963 if( z[0]=='-' ) tx.iJD = -tx.iJD;
13964 computeJD(p);
13965 clearYMD_HMS_TZ(p);
13966 p->iJD += tx.iJD;
13967 rc = 0;
13968 break;
13970 z += n;
13971 while( sqlite3Isspace(*z) ) z++;
13972 n = sqlite3Strlen30(z);
13973 if( n>10 || n<3 ) break;
13974 if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
13975 computeJD(p);
13976 rc = 0;
13977 rRounder = r<0 ? -0.5 : +0.5;
13978 if( n==3 && strcmp(z,"day")==0 ){
13979 p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
13980 }else if( n==4 && strcmp(z,"hour")==0 ){
13981 p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
13982 }else if( n==6 && strcmp(z,"minute")==0 ){
13983 p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
13984 }else if( n==6 && strcmp(z,"second")==0 ){
13985 p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
13986 }else if( n==5 && strcmp(z,"month")==0 ){
13987 int x, y;
13988 computeYMD_HMS(p);
13989 p->M += (int)r;
13990 x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
13991 p->Y += x;
13992 p->M -= x*12;
13993 p->validJD = 0;
13994 computeJD(p);
13995 y = (int)r;
13996 if( y!=r ){
13997 p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
13999 }else if( n==4 && strcmp(z,"year")==0 ){
14000 int y = (int)r;
14001 computeYMD_HMS(p);
14002 p->Y += y;
14003 p->validJD = 0;
14004 computeJD(p);
14005 if( y!=r ){
14006 p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
14008 }else{
14009 rc = 1;
14011 clearYMD_HMS_TZ(p);
14012 break;
14014 default: {
14015 break;
14018 return rc;
14022 ** Process time function arguments. argv[0] is a date-time stamp.
14023 ** argv[1] and following are modifiers. Parse them all and write
14024 ** the resulting time into the DateTime structure p. Return 0
14025 ** on success and 1 if there are any errors.
14027 ** If there are zero parameters (if even argv[0] is undefined)
14028 ** then assume a default value of "now" for argv[0].
14030 static int isDate(
14031 sqlite3_context *context,
14032 int argc,
14033 sqlite3_value **argv,
14034 DateTime *p
14036 int i;
14037 const unsigned char *z;
14038 int eType;
14039 memset(p, 0, sizeof(*p));
14040 if( argc==0 ){
14041 return setDateTimeToCurrent(context, p);
14043 if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
14044 || eType==SQLITE_INTEGER ){
14045 p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
14046 p->validJD = 1;
14047 }else{
14048 z = sqlite3_value_text(argv[0]);
14049 if( !z || parseDateOrTime(context, (char*)z, p) ){
14050 return 1;
14053 for(i=1; i<argc; i++){
14054 z = sqlite3_value_text(argv[i]);
14055 if( z==0 || parseModifier(context, (char*)z, p) ) return 1;
14057 return 0;
14062 ** The following routines implement the various date and time functions
14063 ** of SQLite.
14067 ** julianday( TIMESTRING, MOD, MOD, ...)
14069 ** Return the julian day number of the date specified in the arguments
14071 static void juliandayFunc(
14072 sqlite3_context *context,
14073 int argc,
14074 sqlite3_value **argv
14076 DateTime x;
14077 if( isDate(context, argc, argv, &x)==0 ){
14078 computeJD(&x);
14079 sqlite3_result_double(context, x.iJD/86400000.0);
14084 ** datetime( TIMESTRING, MOD, MOD, ...)
14086 ** Return YYYY-MM-DD HH:MM:SS
14088 static void datetimeFunc(
14089 sqlite3_context *context,
14090 int argc,
14091 sqlite3_value **argv
14093 DateTime x;
14094 if( isDate(context, argc, argv, &x)==0 ){
14095 char zBuf[100];
14096 computeYMD_HMS(&x);
14097 sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
14098 x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
14099 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
14104 ** time( TIMESTRING, MOD, MOD, ...)
14106 ** Return HH:MM:SS
14108 static void timeFunc(
14109 sqlite3_context *context,
14110 int argc,
14111 sqlite3_value **argv
14113 DateTime x;
14114 if( isDate(context, argc, argv, &x)==0 ){
14115 char zBuf[100];
14116 computeHMS(&x);
14117 sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
14118 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
14123 ** date( TIMESTRING, MOD, MOD, ...)
14125 ** Return YYYY-MM-DD
14127 static void dateFunc(
14128 sqlite3_context *context,
14129 int argc,
14130 sqlite3_value **argv
14132 DateTime x;
14133 if( isDate(context, argc, argv, &x)==0 ){
14134 char zBuf[100];
14135 computeYMD(&x);
14136 sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
14137 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
14142 ** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
14144 ** Return a string described by FORMAT. Conversions as follows:
14146 ** %d day of month
14147 ** %f ** fractional seconds SS.SSS
14148 ** %H hour 00-24
14149 ** %j day of year 000-366
14150 ** %J ** Julian day number
14151 ** %m month 01-12
14152 ** %M minute 00-59
14153 ** %s seconds since 1970-01-01
14154 ** %S seconds 00-59
14155 ** %w day of week 0-6 sunday==0
14156 ** %W week of year 00-53
14157 ** %Y year 0000-9999
14158 ** %% %
14160 static void strftimeFunc(
14161 sqlite3_context *context,
14162 int argc,
14163 sqlite3_value **argv
14165 DateTime x;
14166 u64 n;
14167 size_t i,j;
14168 char *z;
14169 sqlite3 *db;
14170 const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
14171 char zBuf[100];
14172 if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
14173 db = sqlite3_context_db_handle(context);
14174 for(i=0, n=1; zFmt[i]; i++, n++){
14175 if( zFmt[i]=='%' ){
14176 switch( zFmt[i+1] ){
14177 case 'd':
14178 case 'H':
14179 case 'm':
14180 case 'M':
14181 case 'S':
14182 case 'W':
14183 n++;
14184 /* fall thru */
14185 case 'w':
14186 case '%':
14187 break;
14188 case 'f':
14189 n += 8;
14190 break;
14191 case 'j':
14192 n += 3;
14193 break;
14194 case 'Y':
14195 n += 8;
14196 break;
14197 case 's':
14198 case 'J':
14199 n += 50;
14200 break;
14201 default:
14202 return; /* ERROR. return a NULL */
14204 i++;
14207 testcase( n==sizeof(zBuf)-1 );
14208 testcase( n==sizeof(zBuf) );
14209 testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
14210 testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
14211 if( n<sizeof(zBuf) ){
14212 z = zBuf;
14213 }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
14214 sqlite3_result_error_toobig(context);
14215 return;
14216 }else{
14217 z = sqlite3DbMallocRaw(db, (int)n);
14218 if( z==0 ){
14219 sqlite3_result_error_nomem(context);
14220 return;
14223 computeJD(&x);
14224 computeYMD_HMS(&x);
14225 for(i=j=0; zFmt[i]; i++){
14226 if( zFmt[i]!='%' ){
14227 z[j++] = zFmt[i];
14228 }else{
14229 i++;
14230 switch( zFmt[i] ){
14231 case 'd': sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
14232 case 'f': {
14233 double s = x.s;
14234 if( s>59.999 ) s = 59.999;
14235 sqlite3_snprintf(7, &z[j],"%06.3f", s);
14236 j += sqlite3Strlen30(&z[j]);
14237 break;
14239 case 'H': sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
14240 case 'W': /* Fall thru */
14241 case 'j': {
14242 int nDay; /* Number of days since 1st day of year */
14243 DateTime y = x;
14244 y.validJD = 0;
14245 y.M = 1;
14246 y.D = 1;
14247 computeJD(&y);
14248 nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
14249 if( zFmt[i]=='W' ){
14250 int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */
14251 wd = (int)(((x.iJD+43200000)/86400000)%7);
14252 sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
14253 j += 2;
14254 }else{
14255 sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
14256 j += 3;
14258 break;
14260 case 'J': {
14261 sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
14262 j+=sqlite3Strlen30(&z[j]);
14263 break;
14265 case 'm': sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
14266 case 'M': sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
14267 case 's': {
14268 sqlite3_snprintf(30,&z[j],"%lld",
14269 (i64)(x.iJD/1000 - 21086676*(i64)10000));
14270 j += sqlite3Strlen30(&z[j]);
14271 break;
14273 case 'S': sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
14274 case 'w': {
14275 z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
14276 break;
14278 case 'Y': {
14279 sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
14280 break;
14282 default: z[j++] = '%'; break;
14286 z[j] = 0;
14287 sqlite3_result_text(context, z, -1,
14288 z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
14292 ** current_time()
14294 ** This function returns the same value as time('now').
14296 static void ctimeFunc(
14297 sqlite3_context *context,
14298 int NotUsed,
14299 sqlite3_value **NotUsed2
14301 UNUSED_PARAMETER2(NotUsed, NotUsed2);
14302 timeFunc(context, 0, 0);
14306 ** current_date()
14308 ** This function returns the same value as date('now').
14310 static void cdateFunc(
14311 sqlite3_context *context,
14312 int NotUsed,
14313 sqlite3_value **NotUsed2
14315 UNUSED_PARAMETER2(NotUsed, NotUsed2);
14316 dateFunc(context, 0, 0);
14320 ** current_timestamp()
14322 ** This function returns the same value as datetime('now').
14324 static void ctimestampFunc(
14325 sqlite3_context *context,
14326 int NotUsed,
14327 sqlite3_value **NotUsed2
14329 UNUSED_PARAMETER2(NotUsed, NotUsed2);
14330 datetimeFunc(context, 0, 0);
14332 #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
14334 #ifdef SQLITE_OMIT_DATETIME_FUNCS
14336 ** If the library is compiled to omit the full-scale date and time
14337 ** handling (to get a smaller binary), the following minimal version
14338 ** of the functions current_time(), current_date() and current_timestamp()
14339 ** are included instead. This is to support column declarations that
14340 ** include "DEFAULT CURRENT_TIME" etc.
14342 ** This function uses the C-library functions time(), gmtime()
14343 ** and strftime(). The format string to pass to strftime() is supplied
14344 ** as the user-data for the function.
14346 static void currentTimeFunc(
14347 sqlite3_context *context,
14348 int argc,
14349 sqlite3_value **argv
14351 time_t t;
14352 char *zFormat = (char *)sqlite3_user_data(context);
14353 sqlite3 *db;
14354 sqlite3_int64 iT;
14355 struct tm *pTm;
14356 struct tm sNow;
14357 char zBuf[20];
14359 UNUSED_PARAMETER(argc);
14360 UNUSED_PARAMETER(argv);
14362 db = sqlite3_context_db_handle(context);
14363 if( sqlite3OsCurrentTimeInt64(db->pVfs, &iT) ) return;
14364 t = iT/1000 - 10000*(sqlite3_int64)21086676;
14365 #ifdef HAVE_GMTIME_R
14366 pTm = gmtime_r(&t, &sNow);
14367 #else
14368 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
14369 pTm = gmtime(&t);
14370 if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
14371 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
14372 #endif
14373 if( pTm ){
14374 strftime(zBuf, 20, zFormat, &sNow);
14375 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
14378 #endif
14381 ** This function registered all of the above C functions as SQL
14382 ** functions. This should be the only routine in this file with
14383 ** external linkage.
14385 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
14386 static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
14387 #ifndef SQLITE_OMIT_DATETIME_FUNCS
14388 FUNCTION(julianday, -1, 0, 0, juliandayFunc ),
14389 FUNCTION(date, -1, 0, 0, dateFunc ),
14390 FUNCTION(time, -1, 0, 0, timeFunc ),
14391 FUNCTION(datetime, -1, 0, 0, datetimeFunc ),
14392 FUNCTION(strftime, -1, 0, 0, strftimeFunc ),
14393 FUNCTION(current_time, 0, 0, 0, ctimeFunc ),
14394 FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
14395 FUNCTION(current_date, 0, 0, 0, cdateFunc ),
14396 #else
14397 STR_FUNCTION(current_time, 0, "%H:%M:%S", 0, currentTimeFunc),
14398 STR_FUNCTION(current_date, 0, "%Y-%m-%d", 0, currentTimeFunc),
14399 STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
14400 #endif
14402 int i;
14403 FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
14404 FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
14406 for(i=0; i<ArraySize(aDateTimeFuncs); i++){
14407 sqlite3FuncDefInsert(pHash, &aFunc[i]);
14411 /************** End of date.c ************************************************/
14412 /************** Begin file os.c **********************************************/
14414 ** 2005 November 29
14416 ** The author disclaims copyright to this source code. In place of
14417 ** a legal notice, here is a blessing:
14419 ** May you do good and not evil.
14420 ** May you find forgiveness for yourself and forgive others.
14421 ** May you share freely, never taking more than you give.
14423 ******************************************************************************
14425 ** This file contains OS interface code that is common to all
14426 ** architectures.
14428 #define _SQLITE_OS_C_ 1
14429 #undef _SQLITE_OS_C_
14432 ** The default SQLite sqlite3_vfs implementations do not allocate
14433 ** memory (actually, os_unix.c allocates a small amount of memory
14434 ** from within OsOpen()), but some third-party implementations may.
14435 ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
14436 ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
14438 ** The following functions are instrumented for malloc() failure
14439 ** testing:
14441 ** sqlite3OsOpen()
14442 ** sqlite3OsRead()
14443 ** sqlite3OsWrite()
14444 ** sqlite3OsSync()
14445 ** sqlite3OsLock()
14448 #if defined(SQLITE_TEST)
14449 SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
14450 #define DO_OS_MALLOC_TEST(x) \
14451 if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) { \
14452 void *pTstAlloc = sqlite3Malloc(10); \
14453 if (!pTstAlloc) return SQLITE_IOERR_NOMEM; \
14454 sqlite3_free(pTstAlloc); \
14456 #else
14457 #define DO_OS_MALLOC_TEST(x)
14458 #endif
14461 ** The following routines are convenience wrappers around methods
14462 ** of the sqlite3_file object. This is mostly just syntactic sugar. All
14463 ** of this would be completely automatic if SQLite were coded using
14464 ** C++ instead of plain old C.
14466 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
14467 int rc = SQLITE_OK;
14468 if( pId->pMethods ){
14469 rc = pId->pMethods->xClose(pId);
14470 pId->pMethods = 0;
14472 return rc;
14474 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
14475 DO_OS_MALLOC_TEST(id);
14476 return id->pMethods->xRead(id, pBuf, amt, offset);
14478 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
14479 DO_OS_MALLOC_TEST(id);
14480 return id->pMethods->xWrite(id, pBuf, amt, offset);
14482 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
14483 return id->pMethods->xTruncate(id, size);
14485 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
14486 DO_OS_MALLOC_TEST(id);
14487 return id->pMethods->xSync(id, flags);
14489 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
14490 DO_OS_MALLOC_TEST(id);
14491 return id->pMethods->xFileSize(id, pSize);
14493 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
14494 DO_OS_MALLOC_TEST(id);
14495 return id->pMethods->xLock(id, lockType);
14497 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
14498 return id->pMethods->xUnlock(id, lockType);
14500 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
14501 DO_OS_MALLOC_TEST(id);
14502 return id->pMethods->xCheckReservedLock(id, pResOut);
14504 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
14505 return id->pMethods->xFileControl(id, op, pArg);
14507 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
14508 int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
14509 return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
14511 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
14512 return id->pMethods->xDeviceCharacteristics(id);
14514 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
14515 return id->pMethods->xShmLock(id, offset, n, flags);
14517 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
14518 id->pMethods->xShmBarrier(id);
14520 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
14521 return id->pMethods->xShmUnmap(id, deleteFlag);
14523 SQLITE_PRIVATE int sqlite3OsShmMap(
14524 sqlite3_file *id, /* Database file handle */
14525 int iPage,
14526 int pgsz,
14527 int bExtend, /* True to extend file if necessary */
14528 void volatile **pp /* OUT: Pointer to mapping */
14530 return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
14534 ** The next group of routines are convenience wrappers around the
14535 ** VFS methods.
14537 SQLITE_PRIVATE int sqlite3OsOpen(
14538 sqlite3_vfs *pVfs,
14539 const char *zPath,
14540 sqlite3_file *pFile,
14541 int flags,
14542 int *pFlagsOut
14544 int rc;
14545 DO_OS_MALLOC_TEST(0);
14546 /* 0x87f3f is a mask of SQLITE_OPEN_ flags that are valid to be passed
14547 ** down into the VFS layer. Some SQLITE_OPEN_ flags (for example,
14548 ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
14549 ** reaching the VFS. */
14550 rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
14551 assert( rc==SQLITE_OK || pFile->pMethods==0 );
14552 return rc;
14554 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
14555 return pVfs->xDelete(pVfs, zPath, dirSync);
14557 SQLITE_PRIVATE int sqlite3OsAccess(
14558 sqlite3_vfs *pVfs,
14559 const char *zPath,
14560 int flags,
14561 int *pResOut
14563 DO_OS_MALLOC_TEST(0);
14564 return pVfs->xAccess(pVfs, zPath, flags, pResOut);
14566 SQLITE_PRIVATE int sqlite3OsFullPathname(
14567 sqlite3_vfs *pVfs,
14568 const char *zPath,
14569 int nPathOut,
14570 char *zPathOut
14572 zPathOut[0] = 0;
14573 return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
14575 #ifndef SQLITE_OMIT_LOAD_EXTENSION
14576 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
14577 return pVfs->xDlOpen(pVfs, zPath);
14579 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
14580 pVfs->xDlError(pVfs, nByte, zBufOut);
14582 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
14583 return pVfs->xDlSym(pVfs, pHdle, zSym);
14585 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
14586 pVfs->xDlClose(pVfs, pHandle);
14588 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
14589 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
14590 return pVfs->xRandomness(pVfs, nByte, zBufOut);
14592 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
14593 return pVfs->xSleep(pVfs, nMicro);
14595 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
14596 int rc;
14597 /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
14598 ** method to get the current date and time if that method is available
14599 ** (if iVersion is 2 or greater and the function pointer is not NULL) and
14600 ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
14601 ** unavailable.
14603 if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
14604 rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
14605 }else{
14606 double r;
14607 rc = pVfs->xCurrentTime(pVfs, &r);
14608 *pTimeOut = (sqlite3_int64)(r*86400000.0);
14610 return rc;
14613 SQLITE_PRIVATE int sqlite3OsOpenMalloc(
14614 sqlite3_vfs *pVfs,
14615 const char *zFile,
14616 sqlite3_file **ppFile,
14617 int flags,
14618 int *pOutFlags
14620 int rc = SQLITE_NOMEM;
14621 sqlite3_file *pFile;
14622 pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
14623 if( pFile ){
14624 rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
14625 if( rc!=SQLITE_OK ){
14626 sqlite3_free(pFile);
14627 }else{
14628 *ppFile = pFile;
14631 return rc;
14633 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
14634 int rc = SQLITE_OK;
14635 assert( pFile );
14636 rc = sqlite3OsClose(pFile);
14637 sqlite3_free(pFile);
14638 return rc;
14642 ** This function is a wrapper around the OS specific implementation of
14643 ** sqlite3_os_init(). The purpose of the wrapper is to provide the
14644 ** ability to simulate a malloc failure, so that the handling of an
14645 ** error in sqlite3_os_init() by the upper layers can be tested.
14647 SQLITE_PRIVATE int sqlite3OsInit(void){
14648 void *p = sqlite3_malloc(10);
14649 if( p==0 ) return SQLITE_NOMEM;
14650 sqlite3_free(p);
14651 return sqlite3_os_init();
14655 ** The list of all registered VFS implementations.
14657 static sqlite3_vfs * SQLITE_WSD vfsList = 0;
14658 #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
14661 ** Locate a VFS by name. If no name is given, simply return the
14662 ** first VFS on the list.
14664 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
14665 sqlite3_vfs *pVfs = 0;
14666 #if SQLITE_THREADSAFE
14667 sqlite3_mutex *mutex;
14668 #endif
14669 #ifndef SQLITE_OMIT_AUTOINIT
14670 int rc = sqlite3_initialize();
14671 if( rc ) return 0;
14672 #endif
14673 #if SQLITE_THREADSAFE
14674 mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
14675 #endif
14676 sqlite3_mutex_enter(mutex);
14677 for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
14678 if( zVfs==0 ) break;
14679 if( strcmp(zVfs, pVfs->zName)==0 ) break;
14681 sqlite3_mutex_leave(mutex);
14682 return pVfs;
14686 ** Unlink a VFS from the linked list
14688 static void vfsUnlink(sqlite3_vfs *pVfs){
14689 assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
14690 if( pVfs==0 ){
14691 /* No-op */
14692 }else if( vfsList==pVfs ){
14693 vfsList = pVfs->pNext;
14694 }else if( vfsList ){
14695 sqlite3_vfs *p = vfsList;
14696 while( p->pNext && p->pNext!=pVfs ){
14697 p = p->pNext;
14699 if( p->pNext==pVfs ){
14700 p->pNext = pVfs->pNext;
14706 ** Register a VFS with the system. It is harmless to register the same
14707 ** VFS multiple times. The new VFS becomes the default if makeDflt is
14708 ** true.
14710 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
14711 MUTEX_LOGIC(sqlite3_mutex *mutex;)
14712 #ifndef SQLITE_OMIT_AUTOINIT
14713 int rc = sqlite3_initialize();
14714 if( rc ) return rc;
14715 #endif
14716 MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
14717 sqlite3_mutex_enter(mutex);
14718 vfsUnlink(pVfs);
14719 if( makeDflt || vfsList==0 ){
14720 pVfs->pNext = vfsList;
14721 vfsList = pVfs;
14722 }else{
14723 pVfs->pNext = vfsList->pNext;
14724 vfsList->pNext = pVfs;
14726 assert(vfsList);
14727 sqlite3_mutex_leave(mutex);
14728 return SQLITE_OK;
14732 ** Unregister a VFS so that it is no longer accessible.
14734 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
14735 #if SQLITE_THREADSAFE
14736 sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
14737 #endif
14738 sqlite3_mutex_enter(mutex);
14739 vfsUnlink(pVfs);
14740 sqlite3_mutex_leave(mutex);
14741 return SQLITE_OK;
14744 /************** End of os.c **************************************************/
14745 /************** Begin file fault.c *******************************************/
14747 ** 2008 Jan 22
14749 ** The author disclaims copyright to this source code. In place of
14750 ** a legal notice, here is a blessing:
14752 ** May you do good and not evil.
14753 ** May you find forgiveness for yourself and forgive others.
14754 ** May you share freely, never taking more than you give.
14756 *************************************************************************
14758 ** This file contains code to support the concept of "benign"
14759 ** malloc failures (when the xMalloc() or xRealloc() method of the
14760 ** sqlite3_mem_methods structure fails to allocate a block of memory
14761 ** and returns 0).
14763 ** Most malloc failures are non-benign. After they occur, SQLite
14764 ** abandons the current operation and returns an error code (usually
14765 ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
14766 ** fatal. For example, if a malloc fails while resizing a hash table, this
14767 ** is completely recoverable simply by not carrying out the resize. The
14768 ** hash table will continue to function normally. So a malloc failure
14769 ** during a hash table resize is a benign fault.
14773 #ifndef SQLITE_OMIT_BUILTIN_TEST
14776 ** Global variables.
14778 typedef struct BenignMallocHooks BenignMallocHooks;
14779 static SQLITE_WSD struct BenignMallocHooks {
14780 void (*xBenignBegin)(void);
14781 void (*xBenignEnd)(void);
14782 } sqlite3Hooks = { 0, 0 };
14784 /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
14785 ** structure. If writable static data is unsupported on the target,
14786 ** we have to locate the state vector at run-time. In the more common
14787 ** case where writable static data is supported, wsdHooks can refer directly
14788 ** to the "sqlite3Hooks" state vector declared above.
14790 #ifdef SQLITE_OMIT_WSD
14791 # define wsdHooksInit \
14792 BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
14793 # define wsdHooks x[0]
14794 #else
14795 # define wsdHooksInit
14796 # define wsdHooks sqlite3Hooks
14797 #endif
14801 ** Register hooks to call when sqlite3BeginBenignMalloc() and
14802 ** sqlite3EndBenignMalloc() are called, respectively.
14804 SQLITE_PRIVATE void sqlite3BenignMallocHooks(
14805 void (*xBenignBegin)(void),
14806 void (*xBenignEnd)(void)
14808 wsdHooksInit;
14809 wsdHooks.xBenignBegin = xBenignBegin;
14810 wsdHooks.xBenignEnd = xBenignEnd;
14814 ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
14815 ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
14816 ** indicates that subsequent malloc failures are non-benign.
14818 SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
14819 wsdHooksInit;
14820 if( wsdHooks.xBenignBegin ){
14821 wsdHooks.xBenignBegin();
14824 SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
14825 wsdHooksInit;
14826 if( wsdHooks.xBenignEnd ){
14827 wsdHooks.xBenignEnd();
14831 #endif /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
14833 /************** End of fault.c ***********************************************/
14834 /************** Begin file mem0.c ********************************************/
14836 ** 2008 October 28
14838 ** The author disclaims copyright to this source code. In place of
14839 ** a legal notice, here is a blessing:
14841 ** May you do good and not evil.
14842 ** May you find forgiveness for yourself and forgive others.
14843 ** May you share freely, never taking more than you give.
14845 *************************************************************************
14847 ** This file contains a no-op memory allocation drivers for use when
14848 ** SQLITE_ZERO_MALLOC is defined. The allocation drivers implemented
14849 ** here always fail. SQLite will not operate with these drivers. These
14850 ** are merely placeholders. Real drivers must be substituted using
14851 ** sqlite3_config() before SQLite will operate.
14855 ** This version of the memory allocator is the default. It is
14856 ** used when no other memory allocator is specified using compile-time
14857 ** macros.
14859 #ifdef SQLITE_ZERO_MALLOC
14862 ** No-op versions of all memory allocation routines
14864 static void *sqlite3MemMalloc(int nByte){ return 0; }
14865 static void sqlite3MemFree(void *pPrior){ return; }
14866 static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
14867 static int sqlite3MemSize(void *pPrior){ return 0; }
14868 static int sqlite3MemRoundup(int n){ return n; }
14869 static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
14870 static void sqlite3MemShutdown(void *NotUsed){ return; }
14873 ** This routine is the only routine in this file with external linkage.
14875 ** Populate the low-level memory allocation function pointers in
14876 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
14878 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
14879 static const sqlite3_mem_methods defaultMethods = {
14880 sqlite3MemMalloc,
14881 sqlite3MemFree,
14882 sqlite3MemRealloc,
14883 sqlite3MemSize,
14884 sqlite3MemRoundup,
14885 sqlite3MemInit,
14886 sqlite3MemShutdown,
14889 sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
14892 #endif /* SQLITE_ZERO_MALLOC */
14894 /************** End of mem0.c ************************************************/
14895 /************** Begin file mem1.c ********************************************/
14897 ** 2007 August 14
14899 ** The author disclaims copyright to this source code. In place of
14900 ** a legal notice, here is a blessing:
14902 ** May you do good and not evil.
14903 ** May you find forgiveness for yourself and forgive others.
14904 ** May you share freely, never taking more than you give.
14906 *************************************************************************
14908 ** This file contains low-level memory allocation drivers for when
14909 ** SQLite will use the standard C-library malloc/realloc/free interface
14910 ** to obtain the memory it needs.
14912 ** This file contains implementations of the low-level memory allocation
14913 ** routines specified in the sqlite3_mem_methods object.
14917 ** This version of the memory allocator is the default. It is
14918 ** used when no other memory allocator is specified using compile-time
14919 ** macros.
14921 #ifdef SQLITE_SYSTEM_MALLOC
14924 ** Like malloc(), but remember the size of the allocation
14925 ** so that we can find it later using sqlite3MemSize().
14927 ** For this low-level routine, we are guaranteed that nByte>0 because
14928 ** cases of nByte<=0 will be intercepted and dealt with by higher level
14929 ** routines.
14931 static void *sqlite3MemMalloc(int nByte){
14932 sqlite3_int64 *p;
14933 assert( nByte>0 );
14934 nByte = ROUND8(nByte);
14935 p = malloc( nByte+8 );
14936 if( p ){
14937 p[0] = nByte;
14938 p++;
14939 }else{
14940 testcase( sqlite3GlobalConfig.xLog!=0 );
14941 sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
14943 return (void *)p;
14947 ** Like free() but works for allocations obtained from sqlite3MemMalloc()
14948 ** or sqlite3MemRealloc().
14950 ** For this low-level routine, we already know that pPrior!=0 since
14951 ** cases where pPrior==0 will have been intecepted and dealt with
14952 ** by higher-level routines.
14954 static void sqlite3MemFree(void *pPrior){
14955 sqlite3_int64 *p = (sqlite3_int64*)pPrior;
14956 assert( pPrior!=0 );
14957 p--;
14958 free(p);
14962 ** Report the allocated size of a prior return from xMalloc()
14963 ** or xRealloc().
14965 static int sqlite3MemSize(void *pPrior){
14966 sqlite3_int64 *p;
14967 if( pPrior==0 ) return 0;
14968 p = (sqlite3_int64*)pPrior;
14969 p--;
14970 return (int)p[0];
14974 ** Like realloc(). Resize an allocation previously obtained from
14975 ** sqlite3MemMalloc().
14977 ** For this low-level interface, we know that pPrior!=0. Cases where
14978 ** pPrior==0 while have been intercepted by higher-level routine and
14979 ** redirected to xMalloc. Similarly, we know that nByte>0 becauses
14980 ** cases where nByte<=0 will have been intercepted by higher-level
14981 ** routines and redirected to xFree.
14983 static void *sqlite3MemRealloc(void *pPrior, int nByte){
14984 sqlite3_int64 *p = (sqlite3_int64*)pPrior;
14985 assert( pPrior!=0 && nByte>0 );
14986 assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
14987 p--;
14988 p = realloc(p, nByte+8 );
14989 if( p ){
14990 p[0] = nByte;
14991 p++;
14992 }else{
14993 testcase( sqlite3GlobalConfig.xLog!=0 );
14994 sqlite3_log(SQLITE_NOMEM,
14995 "failed memory resize %u to %u bytes",
14996 sqlite3MemSize(pPrior), nByte);
14998 return (void*)p;
15002 ** Round up a request size to the next valid allocation size.
15004 static int sqlite3MemRoundup(int n){
15005 return ROUND8(n);
15009 ** Initialize this module.
15011 static int sqlite3MemInit(void *NotUsed){
15012 UNUSED_PARAMETER(NotUsed);
15013 return SQLITE_OK;
15017 ** Deinitialize this module.
15019 static void sqlite3MemShutdown(void *NotUsed){
15020 UNUSED_PARAMETER(NotUsed);
15021 return;
15025 ** This routine is the only routine in this file with external linkage.
15027 ** Populate the low-level memory allocation function pointers in
15028 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
15030 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
15031 static const sqlite3_mem_methods defaultMethods = {
15032 sqlite3MemMalloc,
15033 sqlite3MemFree,
15034 sqlite3MemRealloc,
15035 sqlite3MemSize,
15036 sqlite3MemRoundup,
15037 sqlite3MemInit,
15038 sqlite3MemShutdown,
15041 sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
15044 #endif /* SQLITE_SYSTEM_MALLOC */
15046 /************** End of mem1.c ************************************************/
15047 /************** Begin file mem2.c ********************************************/
15049 ** 2007 August 15
15051 ** The author disclaims copyright to this source code. In place of
15052 ** a legal notice, here is a blessing:
15054 ** May you do good and not evil.
15055 ** May you find forgiveness for yourself and forgive others.
15056 ** May you share freely, never taking more than you give.
15058 *************************************************************************
15060 ** This file contains low-level memory allocation drivers for when
15061 ** SQLite will use the standard C-library malloc/realloc/free interface
15062 ** to obtain the memory it needs while adding lots of additional debugging
15063 ** information to each allocation in order to help detect and fix memory
15064 ** leaks and memory usage errors.
15066 ** This file contains implementations of the low-level memory allocation
15067 ** routines specified in the sqlite3_mem_methods object.
15071 ** This version of the memory allocator is used only if the
15072 ** SQLITE_MEMDEBUG macro is defined
15074 #ifdef SQLITE_MEMDEBUG
15077 ** The backtrace functionality is only available with GLIBC
15079 #ifdef __GLIBC__
15080 extern int backtrace(void**,int);
15081 extern void backtrace_symbols_fd(void*const*,int,int);
15082 #else
15083 # define backtrace(A,B) 1
15084 # define backtrace_symbols_fd(A,B,C)
15085 #endif
15086 /* #include <stdio.h> */
15089 ** Each memory allocation looks like this:
15091 ** ------------------------------------------------------------------------
15092 ** | Title | backtrace pointers | MemBlockHdr | allocation | EndGuard |
15093 ** ------------------------------------------------------------------------
15095 ** The application code sees only a pointer to the allocation. We have
15096 ** to back up from the allocation pointer to find the MemBlockHdr. The
15097 ** MemBlockHdr tells us the size of the allocation and the number of
15098 ** backtrace pointers. There is also a guard word at the end of the
15099 ** MemBlockHdr.
15101 struct MemBlockHdr {
15102 i64 iSize; /* Size of this allocation */
15103 struct MemBlockHdr *pNext, *pPrev; /* Linked list of all unfreed memory */
15104 char nBacktrace; /* Number of backtraces on this alloc */
15105 char nBacktraceSlots; /* Available backtrace slots */
15106 u8 nTitle; /* Bytes of title; includes '\0' */
15107 u8 eType; /* Allocation type code */
15108 int iForeGuard; /* Guard word for sanity */
15112 ** Guard words
15114 #define FOREGUARD 0x80F5E153
15115 #define REARGUARD 0xE4676B53
15118 ** Number of malloc size increments to track.
15120 #define NCSIZE 1000
15123 ** All of the static variables used by this module are collected
15124 ** into a single structure named "mem". This is to keep the
15125 ** static variables organized and to reduce namespace pollution
15126 ** when this module is combined with other in the amalgamation.
15128 static struct {
15131 ** Mutex to control access to the memory allocation subsystem.
15133 sqlite3_mutex *mutex;
15136 ** Head and tail of a linked list of all outstanding allocations
15138 struct MemBlockHdr *pFirst;
15139 struct MemBlockHdr *pLast;
15142 ** The number of levels of backtrace to save in new allocations.
15144 int nBacktrace;
15145 void (*xBacktrace)(int, int, void **);
15148 ** Title text to insert in front of each block
15150 int nTitle; /* Bytes of zTitle to save. Includes '\0' and padding */
15151 char zTitle[100]; /* The title text */
15154 ** sqlite3MallocDisallow() increments the following counter.
15155 ** sqlite3MallocAllow() decrements it.
15157 int disallow; /* Do not allow memory allocation */
15160 ** Gather statistics on the sizes of memory allocations.
15161 ** nAlloc[i] is the number of allocation attempts of i*8
15162 ** bytes. i==NCSIZE is the number of allocation attempts for
15163 ** sizes more than NCSIZE*8 bytes.
15165 int nAlloc[NCSIZE]; /* Total number of allocations */
15166 int nCurrent[NCSIZE]; /* Current number of allocations */
15167 int mxCurrent[NCSIZE]; /* Highwater mark for nCurrent */
15169 } mem;
15173 ** Adjust memory usage statistics
15175 static void adjustStats(int iSize, int increment){
15176 int i = ROUND8(iSize)/8;
15177 if( i>NCSIZE-1 ){
15178 i = NCSIZE - 1;
15180 if( increment>0 ){
15181 mem.nAlloc[i]++;
15182 mem.nCurrent[i]++;
15183 if( mem.nCurrent[i]>mem.mxCurrent[i] ){
15184 mem.mxCurrent[i] = mem.nCurrent[i];
15186 }else{
15187 mem.nCurrent[i]--;
15188 assert( mem.nCurrent[i]>=0 );
15193 ** Given an allocation, find the MemBlockHdr for that allocation.
15195 ** This routine checks the guards at either end of the allocation and
15196 ** if they are incorrect it asserts.
15198 static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
15199 struct MemBlockHdr *p;
15200 int *pInt;
15201 u8 *pU8;
15202 int nReserve;
15204 p = (struct MemBlockHdr*)pAllocation;
15205 p--;
15206 assert( p->iForeGuard==(int)FOREGUARD );
15207 nReserve = ROUND8(p->iSize);
15208 pInt = (int*)pAllocation;
15209 pU8 = (u8*)pAllocation;
15210 assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
15211 /* This checks any of the "extra" bytes allocated due
15212 ** to rounding up to an 8 byte boundary to ensure
15213 ** they haven't been overwritten.
15215 while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
15216 return p;
15220 ** Return the number of bytes currently allocated at address p.
15222 static int sqlite3MemSize(void *p){
15223 struct MemBlockHdr *pHdr;
15224 if( !p ){
15225 return 0;
15227 pHdr = sqlite3MemsysGetHeader(p);
15228 return pHdr->iSize;
15232 ** Initialize the memory allocation subsystem.
15234 static int sqlite3MemInit(void *NotUsed){
15235 UNUSED_PARAMETER(NotUsed);
15236 assert( (sizeof(struct MemBlockHdr)&7) == 0 );
15237 if( !sqlite3GlobalConfig.bMemstat ){
15238 /* If memory status is enabled, then the malloc.c wrapper will already
15239 ** hold the STATIC_MEM mutex when the routines here are invoked. */
15240 mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
15242 return SQLITE_OK;
15246 ** Deinitialize the memory allocation subsystem.
15248 static void sqlite3MemShutdown(void *NotUsed){
15249 UNUSED_PARAMETER(NotUsed);
15250 mem.mutex = 0;
15254 ** Round up a request size to the next valid allocation size.
15256 static int sqlite3MemRoundup(int n){
15257 return ROUND8(n);
15261 ** Fill a buffer with pseudo-random bytes. This is used to preset
15262 ** the content of a new memory allocation to unpredictable values and
15263 ** to clear the content of a freed allocation to unpredictable values.
15265 static void randomFill(char *pBuf, int nByte){
15266 unsigned int x, y, r;
15267 x = SQLITE_PTR_TO_INT(pBuf);
15268 y = nByte | 1;
15269 while( nByte >= 4 ){
15270 x = (x>>1) ^ (-(x&1) & 0xd0000001);
15271 y = y*1103515245 + 12345;
15272 r = x ^ y;
15273 *(int*)pBuf = r;
15274 pBuf += 4;
15275 nByte -= 4;
15277 while( nByte-- > 0 ){
15278 x = (x>>1) ^ (-(x&1) & 0xd0000001);
15279 y = y*1103515245 + 12345;
15280 r = x ^ y;
15281 *(pBuf++) = r & 0xff;
15286 ** Allocate nByte bytes of memory.
15288 static void *sqlite3MemMalloc(int nByte){
15289 struct MemBlockHdr *pHdr;
15290 void **pBt;
15291 char *z;
15292 int *pInt;
15293 void *p = 0;
15294 int totalSize;
15295 int nReserve;
15296 sqlite3_mutex_enter(mem.mutex);
15297 assert( mem.disallow==0 );
15298 nReserve = ROUND8(nByte);
15299 totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
15300 mem.nBacktrace*sizeof(void*) + mem.nTitle;
15301 p = malloc(totalSize);
15302 if( p ){
15303 z = p;
15304 pBt = (void**)&z[mem.nTitle];
15305 pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
15306 pHdr->pNext = 0;
15307 pHdr->pPrev = mem.pLast;
15308 if( mem.pLast ){
15309 mem.pLast->pNext = pHdr;
15310 }else{
15311 mem.pFirst = pHdr;
15313 mem.pLast = pHdr;
15314 pHdr->iForeGuard = FOREGUARD;
15315 pHdr->eType = MEMTYPE_HEAP;
15316 pHdr->nBacktraceSlots = mem.nBacktrace;
15317 pHdr->nTitle = mem.nTitle;
15318 if( mem.nBacktrace ){
15319 void *aAddr[40];
15320 pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
15321 memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
15322 assert(pBt[0]);
15323 if( mem.xBacktrace ){
15324 mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
15326 }else{
15327 pHdr->nBacktrace = 0;
15329 if( mem.nTitle ){
15330 memcpy(z, mem.zTitle, mem.nTitle);
15332 pHdr->iSize = nByte;
15333 adjustStats(nByte, +1);
15334 pInt = (int*)&pHdr[1];
15335 pInt[nReserve/sizeof(int)] = REARGUARD;
15336 randomFill((char*)pInt, nByte);
15337 memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
15338 p = (void*)pInt;
15340 sqlite3_mutex_leave(mem.mutex);
15341 return p;
15345 ** Free memory.
15347 static void sqlite3MemFree(void *pPrior){
15348 struct MemBlockHdr *pHdr;
15349 void **pBt;
15350 char *z;
15351 assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
15352 || mem.mutex!=0 );
15353 pHdr = sqlite3MemsysGetHeader(pPrior);
15354 pBt = (void**)pHdr;
15355 pBt -= pHdr->nBacktraceSlots;
15356 sqlite3_mutex_enter(mem.mutex);
15357 if( pHdr->pPrev ){
15358 assert( pHdr->pPrev->pNext==pHdr );
15359 pHdr->pPrev->pNext = pHdr->pNext;
15360 }else{
15361 assert( mem.pFirst==pHdr );
15362 mem.pFirst = pHdr->pNext;
15364 if( pHdr->pNext ){
15365 assert( pHdr->pNext->pPrev==pHdr );
15366 pHdr->pNext->pPrev = pHdr->pPrev;
15367 }else{
15368 assert( mem.pLast==pHdr );
15369 mem.pLast = pHdr->pPrev;
15371 z = (char*)pBt;
15372 z -= pHdr->nTitle;
15373 adjustStats(pHdr->iSize, -1);
15374 randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
15375 pHdr->iSize + sizeof(int) + pHdr->nTitle);
15376 free(z);
15377 sqlite3_mutex_leave(mem.mutex);
15381 ** Change the size of an existing memory allocation.
15383 ** For this debugging implementation, we *always* make a copy of the
15384 ** allocation into a new place in memory. In this way, if the
15385 ** higher level code is using pointer to the old allocation, it is
15386 ** much more likely to break and we are much more liking to find
15387 ** the error.
15389 static void *sqlite3MemRealloc(void *pPrior, int nByte){
15390 struct MemBlockHdr *pOldHdr;
15391 void *pNew;
15392 assert( mem.disallow==0 );
15393 assert( (nByte & 7)==0 ); /* EV: R-46199-30249 */
15394 pOldHdr = sqlite3MemsysGetHeader(pPrior);
15395 pNew = sqlite3MemMalloc(nByte);
15396 if( pNew ){
15397 memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
15398 if( nByte>pOldHdr->iSize ){
15399 randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - pOldHdr->iSize);
15401 sqlite3MemFree(pPrior);
15403 return pNew;
15407 ** Populate the low-level memory allocation function pointers in
15408 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
15410 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
15411 static const sqlite3_mem_methods defaultMethods = {
15412 sqlite3MemMalloc,
15413 sqlite3MemFree,
15414 sqlite3MemRealloc,
15415 sqlite3MemSize,
15416 sqlite3MemRoundup,
15417 sqlite3MemInit,
15418 sqlite3MemShutdown,
15421 sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
15425 ** Set the "type" of an allocation.
15427 SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
15428 if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
15429 struct MemBlockHdr *pHdr;
15430 pHdr = sqlite3MemsysGetHeader(p);
15431 assert( pHdr->iForeGuard==FOREGUARD );
15432 pHdr->eType = eType;
15437 ** Return TRUE if the mask of type in eType matches the type of the
15438 ** allocation p. Also return true if p==NULL.
15440 ** This routine is designed for use within an assert() statement, to
15441 ** verify the type of an allocation. For example:
15443 ** assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
15445 SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
15446 int rc = 1;
15447 if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
15448 struct MemBlockHdr *pHdr;
15449 pHdr = sqlite3MemsysGetHeader(p);
15450 assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
15451 if( (pHdr->eType&eType)==0 ){
15452 rc = 0;
15455 return rc;
15459 ** Return TRUE if the mask of type in eType matches no bits of the type of the
15460 ** allocation p. Also return true if p==NULL.
15462 ** This routine is designed for use within an assert() statement, to
15463 ** verify the type of an allocation. For example:
15465 ** assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
15467 SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
15468 int rc = 1;
15469 if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
15470 struct MemBlockHdr *pHdr;
15471 pHdr = sqlite3MemsysGetHeader(p);
15472 assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
15473 if( (pHdr->eType&eType)!=0 ){
15474 rc = 0;
15477 return rc;
15481 ** Set the number of backtrace levels kept for each allocation.
15482 ** A value of zero turns off backtracing. The number is always rounded
15483 ** up to a multiple of 2.
15485 SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
15486 if( depth<0 ){ depth = 0; }
15487 if( depth>20 ){ depth = 20; }
15488 depth = (depth+1)&0xfe;
15489 mem.nBacktrace = depth;
15492 SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
15493 mem.xBacktrace = xBacktrace;
15497 ** Set the title string for subsequent allocations.
15499 SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
15500 unsigned int n = sqlite3Strlen30(zTitle) + 1;
15501 sqlite3_mutex_enter(mem.mutex);
15502 if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
15503 memcpy(mem.zTitle, zTitle, n);
15504 mem.zTitle[n] = 0;
15505 mem.nTitle = ROUND8(n);
15506 sqlite3_mutex_leave(mem.mutex);
15509 SQLITE_PRIVATE void sqlite3MemdebugSync(){
15510 struct MemBlockHdr *pHdr;
15511 for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
15512 void **pBt = (void**)pHdr;
15513 pBt -= pHdr->nBacktraceSlots;
15514 mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
15519 ** Open the file indicated and write a log of all unfreed memory
15520 ** allocations into that log.
15522 SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
15523 FILE *out;
15524 struct MemBlockHdr *pHdr;
15525 void **pBt;
15526 int i;
15527 out = fopen(zFilename, "w");
15528 if( out==0 ){
15529 fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
15530 zFilename);
15531 return;
15533 for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
15534 char *z = (char*)pHdr;
15535 z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
15536 fprintf(out, "**** %lld bytes at %p from %s ****\n",
15537 pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
15538 if( pHdr->nBacktrace ){
15539 fflush(out);
15540 pBt = (void**)pHdr;
15541 pBt -= pHdr->nBacktraceSlots;
15542 backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
15543 fprintf(out, "\n");
15546 fprintf(out, "COUNTS:\n");
15547 for(i=0; i<NCSIZE-1; i++){
15548 if( mem.nAlloc[i] ){
15549 fprintf(out, " %5d: %10d %10d %10d\n",
15550 i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
15553 if( mem.nAlloc[NCSIZE-1] ){
15554 fprintf(out, " %5d: %10d %10d %10d\n",
15555 NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
15556 mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
15558 fclose(out);
15562 ** Return the number of times sqlite3MemMalloc() has been called.
15564 SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
15565 int i;
15566 int nTotal = 0;
15567 for(i=0; i<NCSIZE; i++){
15568 nTotal += mem.nAlloc[i];
15570 return nTotal;
15574 #endif /* SQLITE_MEMDEBUG */
15576 /************** End of mem2.c ************************************************/
15577 /************** Begin file mem3.c ********************************************/
15579 ** 2007 October 14
15581 ** The author disclaims copyright to this source code. In place of
15582 ** a legal notice, here is a blessing:
15584 ** May you do good and not evil.
15585 ** May you find forgiveness for yourself and forgive others.
15586 ** May you share freely, never taking more than you give.
15588 *************************************************************************
15589 ** This file contains the C functions that implement a memory
15590 ** allocation subsystem for use by SQLite.
15592 ** This version of the memory allocation subsystem omits all
15593 ** use of malloc(). The SQLite user supplies a block of memory
15594 ** before calling sqlite3_initialize() from which allocations
15595 ** are made and returned by the xMalloc() and xRealloc()
15596 ** implementations. Once sqlite3_initialize() has been called,
15597 ** the amount of memory available to SQLite is fixed and cannot
15598 ** be changed.
15600 ** This version of the memory allocation subsystem is included
15601 ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
15605 ** This version of the memory allocator is only built into the library
15606 ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
15607 ** mean that the library will use a memory-pool by default, just that
15608 ** it is available. The mempool allocator is activated by calling
15609 ** sqlite3_config().
15611 #ifdef SQLITE_ENABLE_MEMSYS3
15614 ** Maximum size (in Mem3Blocks) of a "small" chunk.
15616 #define MX_SMALL 10
15620 ** Number of freelist hash slots
15622 #define N_HASH 61
15625 ** A memory allocation (also called a "chunk") consists of two or
15626 ** more blocks where each block is 8 bytes. The first 8 bytes are
15627 ** a header that is not returned to the user.
15629 ** A chunk is two or more blocks that is either checked out or
15630 ** free. The first block has format u.hdr. u.hdr.size4x is 4 times the
15631 ** size of the allocation in blocks if the allocation is free.
15632 ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
15633 ** false if the chunk is on the freelist. The u.hdr.size4x&2 bit
15634 ** is true if the previous chunk is checked out and false if the
15635 ** previous chunk is free. The u.hdr.prevSize field is the size of
15636 ** the previous chunk in blocks if the previous chunk is on the
15637 ** freelist. If the previous chunk is checked out, then
15638 ** u.hdr.prevSize can be part of the data for that chunk and should
15639 ** not be read or written.
15641 ** We often identify a chunk by its index in mem3.aPool[]. When
15642 ** this is done, the chunk index refers to the second block of
15643 ** the chunk. In this way, the first chunk has an index of 1.
15644 ** A chunk index of 0 means "no such chunk" and is the equivalent
15645 ** of a NULL pointer.
15647 ** The second block of free chunks is of the form u.list. The
15648 ** two fields form a double-linked list of chunks of related sizes.
15649 ** Pointers to the head of the list are stored in mem3.aiSmall[]
15650 ** for smaller chunks and mem3.aiHash[] for larger chunks.
15652 ** The second block of a chunk is user data if the chunk is checked
15653 ** out. If a chunk is checked out, the user data may extend into
15654 ** the u.hdr.prevSize value of the following chunk.
15656 typedef struct Mem3Block Mem3Block;
15657 struct Mem3Block {
15658 union {
15659 struct {
15660 u32 prevSize; /* Size of previous chunk in Mem3Block elements */
15661 u32 size4x; /* 4x the size of current chunk in Mem3Block elements */
15662 } hdr;
15663 struct {
15664 u32 next; /* Index in mem3.aPool[] of next free chunk */
15665 u32 prev; /* Index in mem3.aPool[] of previous free chunk */
15666 } list;
15667 } u;
15671 ** All of the static variables used by this module are collected
15672 ** into a single structure named "mem3". This is to keep the
15673 ** static variables organized and to reduce namespace pollution
15674 ** when this module is combined with other in the amalgamation.
15676 static SQLITE_WSD struct Mem3Global {
15678 ** Memory available for allocation. nPool is the size of the array
15679 ** (in Mem3Blocks) pointed to by aPool less 2.
15681 u32 nPool;
15682 Mem3Block *aPool;
15685 ** True if we are evaluating an out-of-memory callback.
15687 int alarmBusy;
15690 ** Mutex to control access to the memory allocation subsystem.
15692 sqlite3_mutex *mutex;
15695 ** The minimum amount of free space that we have seen.
15697 u32 mnMaster;
15700 ** iMaster is the index of the master chunk. Most new allocations
15701 ** occur off of this chunk. szMaster is the size (in Mem3Blocks)
15702 ** of the current master. iMaster is 0 if there is not master chunk.
15703 ** The master chunk is not in either the aiHash[] or aiSmall[].
15705 u32 iMaster;
15706 u32 szMaster;
15709 ** Array of lists of free blocks according to the block size
15710 ** for smaller chunks, or a hash on the block size for larger
15711 ** chunks.
15713 u32 aiSmall[MX_SMALL-1]; /* For sizes 2 through MX_SMALL, inclusive */
15714 u32 aiHash[N_HASH]; /* For sizes MX_SMALL+1 and larger */
15715 } mem3 = { 97535575 };
15717 #define mem3 GLOBAL(struct Mem3Global, mem3)
15720 ** Unlink the chunk at mem3.aPool[i] from list it is currently
15721 ** on. *pRoot is the list that i is a member of.
15723 static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
15724 u32 next = mem3.aPool[i].u.list.next;
15725 u32 prev = mem3.aPool[i].u.list.prev;
15726 assert( sqlite3_mutex_held(mem3.mutex) );
15727 if( prev==0 ){
15728 *pRoot = next;
15729 }else{
15730 mem3.aPool[prev].u.list.next = next;
15732 if( next ){
15733 mem3.aPool[next].u.list.prev = prev;
15735 mem3.aPool[i].u.list.next = 0;
15736 mem3.aPool[i].u.list.prev = 0;
15740 ** Unlink the chunk at index i from
15741 ** whatever list is currently a member of.
15743 static void memsys3Unlink(u32 i){
15744 u32 size, hash;
15745 assert( sqlite3_mutex_held(mem3.mutex) );
15746 assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
15747 assert( i>=1 );
15748 size = mem3.aPool[i-1].u.hdr.size4x/4;
15749 assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
15750 assert( size>=2 );
15751 if( size <= MX_SMALL ){
15752 memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
15753 }else{
15754 hash = size % N_HASH;
15755 memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
15760 ** Link the chunk at mem3.aPool[i] so that is on the list rooted
15761 ** at *pRoot.
15763 static void memsys3LinkIntoList(u32 i, u32 *pRoot){
15764 assert( sqlite3_mutex_held(mem3.mutex) );
15765 mem3.aPool[i].u.list.next = *pRoot;
15766 mem3.aPool[i].u.list.prev = 0;
15767 if( *pRoot ){
15768 mem3.aPool[*pRoot].u.list.prev = i;
15770 *pRoot = i;
15774 ** Link the chunk at index i into either the appropriate
15775 ** small chunk list, or into the large chunk hash table.
15777 static void memsys3Link(u32 i){
15778 u32 size, hash;
15779 assert( sqlite3_mutex_held(mem3.mutex) );
15780 assert( i>=1 );
15781 assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
15782 size = mem3.aPool[i-1].u.hdr.size4x/4;
15783 assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
15784 assert( size>=2 );
15785 if( size <= MX_SMALL ){
15786 memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
15787 }else{
15788 hash = size % N_HASH;
15789 memsys3LinkIntoList(i, &mem3.aiHash[hash]);
15794 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
15795 ** will already be held (obtained by code in malloc.c) if
15796 ** sqlite3GlobalConfig.bMemStat is true.
15798 static void memsys3Enter(void){
15799 if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
15800 mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
15802 sqlite3_mutex_enter(mem3.mutex);
15804 static void memsys3Leave(void){
15805 sqlite3_mutex_leave(mem3.mutex);
15809 ** Called when we are unable to satisfy an allocation of nBytes.
15811 static void memsys3OutOfMemory(int nByte){
15812 if( !mem3.alarmBusy ){
15813 mem3.alarmBusy = 1;
15814 assert( sqlite3_mutex_held(mem3.mutex) );
15815 sqlite3_mutex_leave(mem3.mutex);
15816 sqlite3_release_memory(nByte);
15817 sqlite3_mutex_enter(mem3.mutex);
15818 mem3.alarmBusy = 0;
15824 ** Chunk i is a free chunk that has been unlinked. Adjust its
15825 ** size parameters for check-out and return a pointer to the
15826 ** user portion of the chunk.
15828 static void *memsys3Checkout(u32 i, u32 nBlock){
15829 u32 x;
15830 assert( sqlite3_mutex_held(mem3.mutex) );
15831 assert( i>=1 );
15832 assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
15833 assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
15834 x = mem3.aPool[i-1].u.hdr.size4x;
15835 mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
15836 mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
15837 mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
15838 return &mem3.aPool[i];
15842 ** Carve a piece off of the end of the mem3.iMaster free chunk.
15843 ** Return a pointer to the new allocation. Or, if the master chunk
15844 ** is not large enough, return 0.
15846 static void *memsys3FromMaster(u32 nBlock){
15847 assert( sqlite3_mutex_held(mem3.mutex) );
15848 assert( mem3.szMaster>=nBlock );
15849 if( nBlock>=mem3.szMaster-1 ){
15850 /* Use the entire master */
15851 void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
15852 mem3.iMaster = 0;
15853 mem3.szMaster = 0;
15854 mem3.mnMaster = 0;
15855 return p;
15856 }else{
15857 /* Split the master block. Return the tail. */
15858 u32 newi, x;
15859 newi = mem3.iMaster + mem3.szMaster - nBlock;
15860 assert( newi > mem3.iMaster+1 );
15861 mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
15862 mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
15863 mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
15864 mem3.szMaster -= nBlock;
15865 mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
15866 x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
15867 mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
15868 if( mem3.szMaster < mem3.mnMaster ){
15869 mem3.mnMaster = mem3.szMaster;
15871 return (void*)&mem3.aPool[newi];
15876 ** *pRoot is the head of a list of free chunks of the same size
15877 ** or same size hash. In other words, *pRoot is an entry in either
15878 ** mem3.aiSmall[] or mem3.aiHash[].
15880 ** This routine examines all entries on the given list and tries
15881 ** to coalesce each entries with adjacent free chunks.
15883 ** If it sees a chunk that is larger than mem3.iMaster, it replaces
15884 ** the current mem3.iMaster with the new larger chunk. In order for
15885 ** this mem3.iMaster replacement to work, the master chunk must be
15886 ** linked into the hash tables. That is not the normal state of
15887 ** affairs, of course. The calling routine must link the master
15888 ** chunk before invoking this routine, then must unlink the (possibly
15889 ** changed) master chunk once this routine has finished.
15891 static void memsys3Merge(u32 *pRoot){
15892 u32 iNext, prev, size, i, x;
15894 assert( sqlite3_mutex_held(mem3.mutex) );
15895 for(i=*pRoot; i>0; i=iNext){
15896 iNext = mem3.aPool[i].u.list.next;
15897 size = mem3.aPool[i-1].u.hdr.size4x;
15898 assert( (size&1)==0 );
15899 if( (size&2)==0 ){
15900 memsys3UnlinkFromList(i, pRoot);
15901 assert( i > mem3.aPool[i-1].u.hdr.prevSize );
15902 prev = i - mem3.aPool[i-1].u.hdr.prevSize;
15903 if( prev==iNext ){
15904 iNext = mem3.aPool[prev].u.list.next;
15906 memsys3Unlink(prev);
15907 size = i + size/4 - prev;
15908 x = mem3.aPool[prev-1].u.hdr.size4x & 2;
15909 mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
15910 mem3.aPool[prev+size-1].u.hdr.prevSize = size;
15911 memsys3Link(prev);
15912 i = prev;
15913 }else{
15914 size /= 4;
15916 if( size>mem3.szMaster ){
15917 mem3.iMaster = i;
15918 mem3.szMaster = size;
15924 ** Return a block of memory of at least nBytes in size.
15925 ** Return NULL if unable.
15927 ** This function assumes that the necessary mutexes, if any, are
15928 ** already held by the caller. Hence "Unsafe".
15930 static void *memsys3MallocUnsafe(int nByte){
15931 u32 i;
15932 u32 nBlock;
15933 u32 toFree;
15935 assert( sqlite3_mutex_held(mem3.mutex) );
15936 assert( sizeof(Mem3Block)==8 );
15937 if( nByte<=12 ){
15938 nBlock = 2;
15939 }else{
15940 nBlock = (nByte + 11)/8;
15942 assert( nBlock>=2 );
15944 /* STEP 1:
15945 ** Look for an entry of the correct size in either the small
15946 ** chunk table or in the large chunk hash table. This is
15947 ** successful most of the time (about 9 times out of 10).
15949 if( nBlock <= MX_SMALL ){
15950 i = mem3.aiSmall[nBlock-2];
15951 if( i>0 ){
15952 memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
15953 return memsys3Checkout(i, nBlock);
15955 }else{
15956 int hash = nBlock % N_HASH;
15957 for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
15958 if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
15959 memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
15960 return memsys3Checkout(i, nBlock);
15965 /* STEP 2:
15966 ** Try to satisfy the allocation by carving a piece off of the end
15967 ** of the master chunk. This step usually works if step 1 fails.
15969 if( mem3.szMaster>=nBlock ){
15970 return memsys3FromMaster(nBlock);
15974 /* STEP 3:
15975 ** Loop through the entire memory pool. Coalesce adjacent free
15976 ** chunks. Recompute the master chunk as the largest free chunk.
15977 ** Then try again to satisfy the allocation by carving a piece off
15978 ** of the end of the master chunk. This step happens very
15979 ** rarely (we hope!)
15981 for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
15982 memsys3OutOfMemory(toFree);
15983 if( mem3.iMaster ){
15984 memsys3Link(mem3.iMaster);
15985 mem3.iMaster = 0;
15986 mem3.szMaster = 0;
15988 for(i=0; i<N_HASH; i++){
15989 memsys3Merge(&mem3.aiHash[i]);
15991 for(i=0; i<MX_SMALL-1; i++){
15992 memsys3Merge(&mem3.aiSmall[i]);
15994 if( mem3.szMaster ){
15995 memsys3Unlink(mem3.iMaster);
15996 if( mem3.szMaster>=nBlock ){
15997 return memsys3FromMaster(nBlock);
16002 /* If none of the above worked, then we fail. */
16003 return 0;
16007 ** Free an outstanding memory allocation.
16009 ** This function assumes that the necessary mutexes, if any, are
16010 ** already held by the caller. Hence "Unsafe".
16012 static void memsys3FreeUnsafe(void *pOld){
16013 Mem3Block *p = (Mem3Block*)pOld;
16014 int i;
16015 u32 size, x;
16016 assert( sqlite3_mutex_held(mem3.mutex) );
16017 assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
16018 i = p - mem3.aPool;
16019 assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
16020 size = mem3.aPool[i-1].u.hdr.size4x/4;
16021 assert( i+size<=mem3.nPool+1 );
16022 mem3.aPool[i-1].u.hdr.size4x &= ~1;
16023 mem3.aPool[i+size-1].u.hdr.prevSize = size;
16024 mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
16025 memsys3Link(i);
16027 /* Try to expand the master using the newly freed chunk */
16028 if( mem3.iMaster ){
16029 while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
16030 size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
16031 mem3.iMaster -= size;
16032 mem3.szMaster += size;
16033 memsys3Unlink(mem3.iMaster);
16034 x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
16035 mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
16036 mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
16038 x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
16039 while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
16040 memsys3Unlink(mem3.iMaster+mem3.szMaster);
16041 mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
16042 mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
16043 mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
16049 ** Return the size of an outstanding allocation, in bytes. The
16050 ** size returned omits the 8-byte header overhead. This only
16051 ** works for chunks that are currently checked out.
16053 static int memsys3Size(void *p){
16054 Mem3Block *pBlock;
16055 if( p==0 ) return 0;
16056 pBlock = (Mem3Block*)p;
16057 assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
16058 return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
16062 ** Round up a request size to the next valid allocation size.
16064 static int memsys3Roundup(int n){
16065 if( n<=12 ){
16066 return 12;
16067 }else{
16068 return ((n+11)&~7) - 4;
16073 ** Allocate nBytes of memory.
16075 static void *memsys3Malloc(int nBytes){
16076 sqlite3_int64 *p;
16077 assert( nBytes>0 ); /* malloc.c filters out 0 byte requests */
16078 memsys3Enter();
16079 p = memsys3MallocUnsafe(nBytes);
16080 memsys3Leave();
16081 return (void*)p;
16085 ** Free memory.
16087 static void memsys3Free(void *pPrior){
16088 assert( pPrior );
16089 memsys3Enter();
16090 memsys3FreeUnsafe(pPrior);
16091 memsys3Leave();
16095 ** Change the size of an existing memory allocation
16097 static void *memsys3Realloc(void *pPrior, int nBytes){
16098 int nOld;
16099 void *p;
16100 if( pPrior==0 ){
16101 return sqlite3_malloc(nBytes);
16103 if( nBytes<=0 ){
16104 sqlite3_free(pPrior);
16105 return 0;
16107 nOld = memsys3Size(pPrior);
16108 if( nBytes<=nOld && nBytes>=nOld-128 ){
16109 return pPrior;
16111 memsys3Enter();
16112 p = memsys3MallocUnsafe(nBytes);
16113 if( p ){
16114 if( nOld<nBytes ){
16115 memcpy(p, pPrior, nOld);
16116 }else{
16117 memcpy(p, pPrior, nBytes);
16119 memsys3FreeUnsafe(pPrior);
16121 memsys3Leave();
16122 return p;
16126 ** Initialize this module.
16128 static int memsys3Init(void *NotUsed){
16129 UNUSED_PARAMETER(NotUsed);
16130 if( !sqlite3GlobalConfig.pHeap ){
16131 return SQLITE_ERROR;
16134 /* Store a pointer to the memory block in global structure mem3. */
16135 assert( sizeof(Mem3Block)==8 );
16136 mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
16137 mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
16139 /* Initialize the master block. */
16140 mem3.szMaster = mem3.nPool;
16141 mem3.mnMaster = mem3.szMaster;
16142 mem3.iMaster = 1;
16143 mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
16144 mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
16145 mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
16147 return SQLITE_OK;
16151 ** Deinitialize this module.
16153 static void memsys3Shutdown(void *NotUsed){
16154 UNUSED_PARAMETER(NotUsed);
16155 mem3.mutex = 0;
16156 return;
16162 ** Open the file indicated and write a log of all unfreed memory
16163 ** allocations into that log.
16165 SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
16166 #ifdef SQLITE_DEBUG
16167 FILE *out;
16168 u32 i, j;
16169 u32 size;
16170 if( zFilename==0 || zFilename[0]==0 ){
16171 out = stdout;
16172 }else{
16173 out = fopen(zFilename, "w");
16174 if( out==0 ){
16175 fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
16176 zFilename);
16177 return;
16180 memsys3Enter();
16181 fprintf(out, "CHUNKS:\n");
16182 for(i=1; i<=mem3.nPool; i+=size/4){
16183 size = mem3.aPool[i-1].u.hdr.size4x;
16184 if( size/4<=1 ){
16185 fprintf(out, "%p size error\n", &mem3.aPool[i]);
16186 assert( 0 );
16187 break;
16189 if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
16190 fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
16191 assert( 0 );
16192 break;
16194 if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
16195 fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
16196 assert( 0 );
16197 break;
16199 if( size&1 ){
16200 fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
16201 }else{
16202 fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
16203 i==mem3.iMaster ? " **master**" : "");
16206 for(i=0; i<MX_SMALL-1; i++){
16207 if( mem3.aiSmall[i]==0 ) continue;
16208 fprintf(out, "small(%2d):", i);
16209 for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
16210 fprintf(out, " %p(%d)", &mem3.aPool[j],
16211 (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
16213 fprintf(out, "\n");
16215 for(i=0; i<N_HASH; i++){
16216 if( mem3.aiHash[i]==0 ) continue;
16217 fprintf(out, "hash(%2d):", i);
16218 for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
16219 fprintf(out, " %p(%d)", &mem3.aPool[j],
16220 (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
16222 fprintf(out, "\n");
16224 fprintf(out, "master=%d\n", mem3.iMaster);
16225 fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
16226 fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
16227 sqlite3_mutex_leave(mem3.mutex);
16228 if( out==stdout ){
16229 fflush(stdout);
16230 }else{
16231 fclose(out);
16233 #else
16234 UNUSED_PARAMETER(zFilename);
16235 #endif
16239 ** This routine is the only routine in this file with external
16240 ** linkage.
16242 ** Populate the low-level memory allocation function pointers in
16243 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
16244 ** arguments specify the block of memory to manage.
16246 ** This routine is only called by sqlite3_config(), and therefore
16247 ** is not required to be threadsafe (it is not).
16249 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
16250 static const sqlite3_mem_methods mempoolMethods = {
16251 memsys3Malloc,
16252 memsys3Free,
16253 memsys3Realloc,
16254 memsys3Size,
16255 memsys3Roundup,
16256 memsys3Init,
16257 memsys3Shutdown,
16260 return &mempoolMethods;
16263 #endif /* SQLITE_ENABLE_MEMSYS3 */
16265 /************** End of mem3.c ************************************************/
16266 /************** Begin file mem5.c ********************************************/
16268 ** 2007 October 14
16270 ** The author disclaims copyright to this source code. In place of
16271 ** a legal notice, here is a blessing:
16273 ** May you do good and not evil.
16274 ** May you find forgiveness for yourself and forgive others.
16275 ** May you share freely, never taking more than you give.
16277 *************************************************************************
16278 ** This file contains the C functions that implement a memory
16279 ** allocation subsystem for use by SQLite.
16281 ** This version of the memory allocation subsystem omits all
16282 ** use of malloc(). The application gives SQLite a block of memory
16283 ** before calling sqlite3_initialize() from which allocations
16284 ** are made and returned by the xMalloc() and xRealloc()
16285 ** implementations. Once sqlite3_initialize() has been called,
16286 ** the amount of memory available to SQLite is fixed and cannot
16287 ** be changed.
16289 ** This version of the memory allocation subsystem is included
16290 ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
16292 ** This memory allocator uses the following algorithm:
16294 ** 1. All memory allocations sizes are rounded up to a power of 2.
16296 ** 2. If two adjacent free blocks are the halves of a larger block,
16297 ** then the two blocks are coalesed into the single larger block.
16299 ** 3. New memory is allocated from the first available free block.
16301 ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
16302 ** Concerning Dynamic Storage Allocation". Journal of the Association for
16303 ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
16305 ** Let n be the size of the largest allocation divided by the minimum
16306 ** allocation size (after rounding all sizes up to a power of 2.) Let M
16307 ** be the maximum amount of memory ever outstanding at one time. Let
16308 ** N be the total amount of memory available for allocation. Robson
16309 ** proved that this memory allocator will never breakdown due to
16310 ** fragmentation as long as the following constraint holds:
16312 ** N >= M*(1 + log2(n)/2) - n + 1
16314 ** The sqlite3_status() logic tracks the maximum values of n and M so
16315 ** that an application can, at any time, verify this constraint.
16319 ** This version of the memory allocator is used only when
16320 ** SQLITE_ENABLE_MEMSYS5 is defined.
16322 #ifdef SQLITE_ENABLE_MEMSYS5
16325 ** A minimum allocation is an instance of the following structure.
16326 ** Larger allocations are an array of these structures where the
16327 ** size of the array is a power of 2.
16329 ** The size of this object must be a power of two. That fact is
16330 ** verified in memsys5Init().
16332 typedef struct Mem5Link Mem5Link;
16333 struct Mem5Link {
16334 int next; /* Index of next free chunk */
16335 int prev; /* Index of previous free chunk */
16339 ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
16340 ** mem5.szAtom is always at least 8 and 32-bit integers are used,
16341 ** it is not actually possible to reach this limit.
16343 #define LOGMAX 30
16346 ** Masks used for mem5.aCtrl[] elements.
16348 #define CTRL_LOGSIZE 0x1f /* Log2 Size of this block */
16349 #define CTRL_FREE 0x20 /* True if not checked out */
16352 ** All of the static variables used by this module are collected
16353 ** into a single structure named "mem5". This is to keep the
16354 ** static variables organized and to reduce namespace pollution
16355 ** when this module is combined with other in the amalgamation.
16357 static SQLITE_WSD struct Mem5Global {
16359 ** Memory available for allocation
16361 int szAtom; /* Smallest possible allocation in bytes */
16362 int nBlock; /* Number of szAtom sized blocks in zPool */
16363 u8 *zPool; /* Memory available to be allocated */
16366 ** Mutex to control access to the memory allocation subsystem.
16368 sqlite3_mutex *mutex;
16371 ** Performance statistics
16373 u64 nAlloc; /* Total number of calls to malloc */
16374 u64 totalAlloc; /* Total of all malloc calls - includes internal frag */
16375 u64 totalExcess; /* Total internal fragmentation */
16376 u32 currentOut; /* Current checkout, including internal fragmentation */
16377 u32 currentCount; /* Current number of distinct checkouts */
16378 u32 maxOut; /* Maximum instantaneous currentOut */
16379 u32 maxCount; /* Maximum instantaneous currentCount */
16380 u32 maxRequest; /* Largest allocation (exclusive of internal frag) */
16383 ** Lists of free blocks. aiFreelist[0] is a list of free blocks of
16384 ** size mem5.szAtom. aiFreelist[1] holds blocks of size szAtom*2.
16385 ** and so forth.
16387 int aiFreelist[LOGMAX+1];
16390 ** Space for tracking which blocks are checked out and the size
16391 ** of each block. One byte per block.
16393 u8 *aCtrl;
16395 } mem5;
16398 ** Access the static variable through a macro for SQLITE_OMIT_WSD
16400 #define mem5 GLOBAL(struct Mem5Global, mem5)
16403 ** Assuming mem5.zPool is divided up into an array of Mem5Link
16404 ** structures, return a pointer to the idx-th such lik.
16406 #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
16409 ** Unlink the chunk at mem5.aPool[i] from list it is currently
16410 ** on. It should be found on mem5.aiFreelist[iLogsize].
16412 static void memsys5Unlink(int i, int iLogsize){
16413 int next, prev;
16414 assert( i>=0 && i<mem5.nBlock );
16415 assert( iLogsize>=0 && iLogsize<=LOGMAX );
16416 assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
16418 next = MEM5LINK(i)->next;
16419 prev = MEM5LINK(i)->prev;
16420 if( prev<0 ){
16421 mem5.aiFreelist[iLogsize] = next;
16422 }else{
16423 MEM5LINK(prev)->next = next;
16425 if( next>=0 ){
16426 MEM5LINK(next)->prev = prev;
16431 ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
16432 ** free list.
16434 static void memsys5Link(int i, int iLogsize){
16435 int x;
16436 assert( sqlite3_mutex_held(mem5.mutex) );
16437 assert( i>=0 && i<mem5.nBlock );
16438 assert( iLogsize>=0 && iLogsize<=LOGMAX );
16439 assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
16441 x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
16442 MEM5LINK(i)->prev = -1;
16443 if( x>=0 ){
16444 assert( x<mem5.nBlock );
16445 MEM5LINK(x)->prev = i;
16447 mem5.aiFreelist[iLogsize] = i;
16451 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
16452 ** will already be held (obtained by code in malloc.c) if
16453 ** sqlite3GlobalConfig.bMemStat is true.
16455 static void memsys5Enter(void){
16456 sqlite3_mutex_enter(mem5.mutex);
16458 static void memsys5Leave(void){
16459 sqlite3_mutex_leave(mem5.mutex);
16463 ** Return the size of an outstanding allocation, in bytes. The
16464 ** size returned omits the 8-byte header overhead. This only
16465 ** works for chunks that are currently checked out.
16467 static int memsys5Size(void *p){
16468 int iSize = 0;
16469 if( p ){
16470 int i = ((u8 *)p-mem5.zPool)/mem5.szAtom;
16471 assert( i>=0 && i<mem5.nBlock );
16472 iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
16474 return iSize;
16478 ** Find the first entry on the freelist iLogsize. Unlink that
16479 ** entry and return its index.
16481 static int memsys5UnlinkFirst(int iLogsize){
16482 int i;
16483 int iFirst;
16485 assert( iLogsize>=0 && iLogsize<=LOGMAX );
16486 i = iFirst = mem5.aiFreelist[iLogsize];
16487 assert( iFirst>=0 );
16488 while( i>0 ){
16489 if( i<iFirst ) iFirst = i;
16490 i = MEM5LINK(i)->next;
16492 memsys5Unlink(iFirst, iLogsize);
16493 return iFirst;
16497 ** Return a block of memory of at least nBytes in size.
16498 ** Return NULL if unable. Return NULL if nBytes==0.
16500 ** The caller guarantees that nByte positive.
16502 ** The caller has obtained a mutex prior to invoking this
16503 ** routine so there is never any chance that two or more
16504 ** threads can be in this routine at the same time.
16506 static void *memsys5MallocUnsafe(int nByte){
16507 int i; /* Index of a mem5.aPool[] slot */
16508 int iBin; /* Index into mem5.aiFreelist[] */
16509 int iFullSz; /* Size of allocation rounded up to power of 2 */
16510 int iLogsize; /* Log2 of iFullSz/POW2_MIN */
16512 /* nByte must be a positive */
16513 assert( nByte>0 );
16515 /* Keep track of the maximum allocation request. Even unfulfilled
16516 ** requests are counted */
16517 if( (u32)nByte>mem5.maxRequest ){
16518 mem5.maxRequest = nByte;
16521 /* Abort if the requested allocation size is larger than the largest
16522 ** power of two that we can represent using 32-bit signed integers.
16524 if( nByte > 0x40000000 ){
16525 return 0;
16528 /* Round nByte up to the next valid power of two */
16529 for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
16531 /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
16532 ** block. If not, then split a block of the next larger power of
16533 ** two in order to create a new free block of size iLogsize.
16535 for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
16536 if( iBin>LOGMAX ){
16537 testcase( sqlite3GlobalConfig.xLog!=0 );
16538 sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
16539 return 0;
16541 i = memsys5UnlinkFirst(iBin);
16542 while( iBin>iLogsize ){
16543 int newSize;
16545 iBin--;
16546 newSize = 1 << iBin;
16547 mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
16548 memsys5Link(i+newSize, iBin);
16550 mem5.aCtrl[i] = iLogsize;
16552 /* Update allocator performance statistics. */
16553 mem5.nAlloc++;
16554 mem5.totalAlloc += iFullSz;
16555 mem5.totalExcess += iFullSz - nByte;
16556 mem5.currentCount++;
16557 mem5.currentOut += iFullSz;
16558 if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
16559 if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
16561 /* Return a pointer to the allocated memory. */
16562 return (void*)&mem5.zPool[i*mem5.szAtom];
16566 ** Free an outstanding memory allocation.
16568 static void memsys5FreeUnsafe(void *pOld){
16569 u32 size, iLogsize;
16570 int iBlock;
16572 /* Set iBlock to the index of the block pointed to by pOld in
16573 ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
16575 iBlock = ((u8 *)pOld-mem5.zPool)/mem5.szAtom;
16577 /* Check that the pointer pOld points to a valid, non-free block. */
16578 assert( iBlock>=0 && iBlock<mem5.nBlock );
16579 assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
16580 assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
16582 iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
16583 size = 1<<iLogsize;
16584 assert( iBlock+size-1<(u32)mem5.nBlock );
16586 mem5.aCtrl[iBlock] |= CTRL_FREE;
16587 mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
16588 assert( mem5.currentCount>0 );
16589 assert( mem5.currentOut>=(size*mem5.szAtom) );
16590 mem5.currentCount--;
16591 mem5.currentOut -= size*mem5.szAtom;
16592 assert( mem5.currentOut>0 || mem5.currentCount==0 );
16593 assert( mem5.currentCount>0 || mem5.currentOut==0 );
16595 mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
16596 while( ALWAYS(iLogsize<LOGMAX) ){
16597 int iBuddy;
16598 if( (iBlock>>iLogsize) & 1 ){
16599 iBuddy = iBlock - size;
16600 }else{
16601 iBuddy = iBlock + size;
16603 assert( iBuddy>=0 );
16604 if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
16605 if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
16606 memsys5Unlink(iBuddy, iLogsize);
16607 iLogsize++;
16608 if( iBuddy<iBlock ){
16609 mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
16610 mem5.aCtrl[iBlock] = 0;
16611 iBlock = iBuddy;
16612 }else{
16613 mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
16614 mem5.aCtrl[iBuddy] = 0;
16616 size *= 2;
16618 memsys5Link(iBlock, iLogsize);
16622 ** Allocate nBytes of memory
16624 static void *memsys5Malloc(int nBytes){
16625 sqlite3_int64 *p = 0;
16626 if( nBytes>0 ){
16627 memsys5Enter();
16628 p = memsys5MallocUnsafe(nBytes);
16629 memsys5Leave();
16631 return (void*)p;
16635 ** Free memory.
16637 ** The outer layer memory allocator prevents this routine from
16638 ** being called with pPrior==0.
16640 static void memsys5Free(void *pPrior){
16641 assert( pPrior!=0 );
16642 memsys5Enter();
16643 memsys5FreeUnsafe(pPrior);
16644 memsys5Leave();
16648 ** Change the size of an existing memory allocation.
16650 ** The outer layer memory allocator prevents this routine from
16651 ** being called with pPrior==0.
16653 ** nBytes is always a value obtained from a prior call to
16654 ** memsys5Round(). Hence nBytes is always a non-negative power
16655 ** of two. If nBytes==0 that means that an oversize allocation
16656 ** (an allocation larger than 0x40000000) was requested and this
16657 ** routine should return 0 without freeing pPrior.
16659 static void *memsys5Realloc(void *pPrior, int nBytes){
16660 int nOld;
16661 void *p;
16662 assert( pPrior!=0 );
16663 assert( (nBytes&(nBytes-1))==0 ); /* EV: R-46199-30249 */
16664 assert( nBytes>=0 );
16665 if( nBytes==0 ){
16666 return 0;
16668 nOld = memsys5Size(pPrior);
16669 if( nBytes<=nOld ){
16670 return pPrior;
16672 memsys5Enter();
16673 p = memsys5MallocUnsafe(nBytes);
16674 if( p ){
16675 memcpy(p, pPrior, nOld);
16676 memsys5FreeUnsafe(pPrior);
16678 memsys5Leave();
16679 return p;
16683 ** Round up a request size to the next valid allocation size. If
16684 ** the allocation is too large to be handled by this allocation system,
16685 ** return 0.
16687 ** All allocations must be a power of two and must be expressed by a
16688 ** 32-bit signed integer. Hence the largest allocation is 0x40000000
16689 ** or 1073741824 bytes.
16691 static int memsys5Roundup(int n){
16692 int iFullSz;
16693 if( n > 0x40000000 ) return 0;
16694 for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
16695 return iFullSz;
16699 ** Return the ceiling of the logarithm base 2 of iValue.
16701 ** Examples: memsys5Log(1) -> 0
16702 ** memsys5Log(2) -> 1
16703 ** memsys5Log(4) -> 2
16704 ** memsys5Log(5) -> 3
16705 ** memsys5Log(8) -> 3
16706 ** memsys5Log(9) -> 4
16708 static int memsys5Log(int iValue){
16709 int iLog;
16710 for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
16711 return iLog;
16715 ** Initialize the memory allocator.
16717 ** This routine is not threadsafe. The caller must be holding a mutex
16718 ** to prevent multiple threads from entering at the same time.
16720 static int memsys5Init(void *NotUsed){
16721 int ii; /* Loop counter */
16722 int nByte; /* Number of bytes of memory available to this allocator */
16723 u8 *zByte; /* Memory usable by this allocator */
16724 int nMinLog; /* Log base 2 of minimum allocation size in bytes */
16725 int iOffset; /* An offset into mem5.aCtrl[] */
16727 UNUSED_PARAMETER(NotUsed);
16729 /* For the purposes of this routine, disable the mutex */
16730 mem5.mutex = 0;
16732 /* The size of a Mem5Link object must be a power of two. Verify that
16733 ** this is case.
16735 assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
16737 nByte = sqlite3GlobalConfig.nHeap;
16738 zByte = (u8*)sqlite3GlobalConfig.pHeap;
16739 assert( zByte!=0 ); /* sqlite3_config() does not allow otherwise */
16741 /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
16742 nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
16743 mem5.szAtom = (1<<nMinLog);
16744 while( (int)sizeof(Mem5Link)>mem5.szAtom ){
16745 mem5.szAtom = mem5.szAtom << 1;
16748 mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
16749 mem5.zPool = zByte;
16750 mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
16752 for(ii=0; ii<=LOGMAX; ii++){
16753 mem5.aiFreelist[ii] = -1;
16756 iOffset = 0;
16757 for(ii=LOGMAX; ii>=0; ii--){
16758 int nAlloc = (1<<ii);
16759 if( (iOffset+nAlloc)<=mem5.nBlock ){
16760 mem5.aCtrl[iOffset] = ii | CTRL_FREE;
16761 memsys5Link(iOffset, ii);
16762 iOffset += nAlloc;
16764 assert((iOffset+nAlloc)>mem5.nBlock);
16767 /* If a mutex is required for normal operation, allocate one */
16768 if( sqlite3GlobalConfig.bMemstat==0 ){
16769 mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
16772 return SQLITE_OK;
16776 ** Deinitialize this module.
16778 static void memsys5Shutdown(void *NotUsed){
16779 UNUSED_PARAMETER(NotUsed);
16780 mem5.mutex = 0;
16781 return;
16784 #ifdef SQLITE_TEST
16786 ** Open the file indicated and write a log of all unfreed memory
16787 ** allocations into that log.
16789 SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
16790 FILE *out;
16791 int i, j, n;
16792 int nMinLog;
16794 if( zFilename==0 || zFilename[0]==0 ){
16795 out = stdout;
16796 }else{
16797 out = fopen(zFilename, "w");
16798 if( out==0 ){
16799 fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
16800 zFilename);
16801 return;
16804 memsys5Enter();
16805 nMinLog = memsys5Log(mem5.szAtom);
16806 for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
16807 for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
16808 fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
16810 fprintf(out, "mem5.nAlloc = %llu\n", mem5.nAlloc);
16811 fprintf(out, "mem5.totalAlloc = %llu\n", mem5.totalAlloc);
16812 fprintf(out, "mem5.totalExcess = %llu\n", mem5.totalExcess);
16813 fprintf(out, "mem5.currentOut = %u\n", mem5.currentOut);
16814 fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
16815 fprintf(out, "mem5.maxOut = %u\n", mem5.maxOut);
16816 fprintf(out, "mem5.maxCount = %u\n", mem5.maxCount);
16817 fprintf(out, "mem5.maxRequest = %u\n", mem5.maxRequest);
16818 memsys5Leave();
16819 if( out==stdout ){
16820 fflush(stdout);
16821 }else{
16822 fclose(out);
16825 #endif
16828 ** This routine is the only routine in this file with external
16829 ** linkage. It returns a pointer to a static sqlite3_mem_methods
16830 ** struct populated with the memsys5 methods.
16832 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
16833 static const sqlite3_mem_methods memsys5Methods = {
16834 memsys5Malloc,
16835 memsys5Free,
16836 memsys5Realloc,
16837 memsys5Size,
16838 memsys5Roundup,
16839 memsys5Init,
16840 memsys5Shutdown,
16843 return &memsys5Methods;
16846 #endif /* SQLITE_ENABLE_MEMSYS5 */
16848 /************** End of mem5.c ************************************************/
16849 /************** Begin file mutex.c *******************************************/
16851 ** 2007 August 14
16853 ** The author disclaims copyright to this source code. In place of
16854 ** a legal notice, here is a blessing:
16856 ** May you do good and not evil.
16857 ** May you find forgiveness for yourself and forgive others.
16858 ** May you share freely, never taking more than you give.
16860 *************************************************************************
16861 ** This file contains the C functions that implement mutexes.
16863 ** This file contains code that is common across all mutex implementations.
16866 #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
16868 ** For debugging purposes, record when the mutex subsystem is initialized
16869 ** and uninitialized so that we can assert() if there is an attempt to
16870 ** allocate a mutex while the system is uninitialized.
16872 static SQLITE_WSD int mutexIsInit = 0;
16873 #endif /* SQLITE_DEBUG */
16876 #ifndef SQLITE_MUTEX_OMIT
16878 ** Initialize the mutex system.
16880 SQLITE_PRIVATE int sqlite3MutexInit(void){
16881 int rc = SQLITE_OK;
16882 if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
16883 /* If the xMutexAlloc method has not been set, then the user did not
16884 ** install a mutex implementation via sqlite3_config() prior to
16885 ** sqlite3_initialize() being called. This block copies pointers to
16886 ** the default implementation into the sqlite3GlobalConfig structure.
16888 sqlite3_mutex_methods const *pFrom;
16889 sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
16891 if( sqlite3GlobalConfig.bCoreMutex ){
16892 pFrom = sqlite3DefaultMutex();
16893 }else{
16894 pFrom = sqlite3NoopMutex();
16896 memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
16897 memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
16898 sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
16899 pTo->xMutexAlloc = pFrom->xMutexAlloc;
16901 rc = sqlite3GlobalConfig.mutex.xMutexInit();
16903 #ifdef SQLITE_DEBUG
16904 GLOBAL(int, mutexIsInit) = 1;
16905 #endif
16907 return rc;
16911 ** Shutdown the mutex system. This call frees resources allocated by
16912 ** sqlite3MutexInit().
16914 SQLITE_PRIVATE int sqlite3MutexEnd(void){
16915 int rc = SQLITE_OK;
16916 if( sqlite3GlobalConfig.mutex.xMutexEnd ){
16917 rc = sqlite3GlobalConfig.mutex.xMutexEnd();
16920 #ifdef SQLITE_DEBUG
16921 GLOBAL(int, mutexIsInit) = 0;
16922 #endif
16924 return rc;
16928 ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
16930 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
16931 #ifndef SQLITE_OMIT_AUTOINIT
16932 if( sqlite3_initialize() ) return 0;
16933 #endif
16934 return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
16937 SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
16938 if( !sqlite3GlobalConfig.bCoreMutex ){
16939 return 0;
16941 assert( GLOBAL(int, mutexIsInit) );
16942 return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
16946 ** Free a dynamic mutex.
16948 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
16949 if( p ){
16950 sqlite3GlobalConfig.mutex.xMutexFree(p);
16955 ** Obtain the mutex p. If some other thread already has the mutex, block
16956 ** until it can be obtained.
16958 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
16959 if( p ){
16960 sqlite3GlobalConfig.mutex.xMutexEnter(p);
16965 ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
16966 ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
16968 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
16969 int rc = SQLITE_OK;
16970 if( p ){
16971 return sqlite3GlobalConfig.mutex.xMutexTry(p);
16973 return rc;
16977 ** The sqlite3_mutex_leave() routine exits a mutex that was previously
16978 ** entered by the same thread. The behavior is undefined if the mutex
16979 ** is not currently entered. If a NULL pointer is passed as an argument
16980 ** this function is a no-op.
16982 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
16983 if( p ){
16984 sqlite3GlobalConfig.mutex.xMutexLeave(p);
16988 #ifndef NDEBUG
16990 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
16991 ** intended for use inside assert() statements.
16993 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
16994 return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
16996 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
16997 return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
16999 #endif
17001 #endif /* SQLITE_MUTEX_OMIT */
17003 /************** End of mutex.c ***********************************************/
17004 /************** Begin file mutex_noop.c **************************************/
17006 ** 2008 October 07
17008 ** The author disclaims copyright to this source code. In place of
17009 ** a legal notice, here is a blessing:
17011 ** May you do good and not evil.
17012 ** May you find forgiveness for yourself and forgive others.
17013 ** May you share freely, never taking more than you give.
17015 *************************************************************************
17016 ** This file contains the C functions that implement mutexes.
17018 ** This implementation in this file does not provide any mutual
17019 ** exclusion and is thus suitable for use only in applications
17020 ** that use SQLite in a single thread. The routines defined
17021 ** here are place-holders. Applications can substitute working
17022 ** mutex routines at start-time using the
17024 ** sqlite3_config(SQLITE_CONFIG_MUTEX,...)
17026 ** interface.
17028 ** If compiled with SQLITE_DEBUG, then additional logic is inserted
17029 ** that does error checking on mutexes to make sure they are being
17030 ** called correctly.
17033 #ifndef SQLITE_MUTEX_OMIT
17035 #ifndef SQLITE_DEBUG
17037 ** Stub routines for all mutex methods.
17039 ** This routines provide no mutual exclusion or error checking.
17041 static int noopMutexInit(void){ return SQLITE_OK; }
17042 static int noopMutexEnd(void){ return SQLITE_OK; }
17043 static sqlite3_mutex *noopMutexAlloc(int id){
17044 UNUSED_PARAMETER(id);
17045 return (sqlite3_mutex*)8;
17047 static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
17048 static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
17049 static int noopMutexTry(sqlite3_mutex *p){
17050 UNUSED_PARAMETER(p);
17051 return SQLITE_OK;
17053 static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
17055 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
17056 static const sqlite3_mutex_methods sMutex = {
17057 noopMutexInit,
17058 noopMutexEnd,
17059 noopMutexAlloc,
17060 noopMutexFree,
17061 noopMutexEnter,
17062 noopMutexTry,
17063 noopMutexLeave,
17069 return &sMutex;
17071 #endif /* !SQLITE_DEBUG */
17073 #ifdef SQLITE_DEBUG
17075 ** In this implementation, error checking is provided for testing
17076 ** and debugging purposes. The mutexes still do not provide any
17077 ** mutual exclusion.
17081 ** The mutex object
17083 typedef struct sqlite3_debug_mutex {
17084 int id; /* The mutex type */
17085 int cnt; /* Number of entries without a matching leave */
17086 } sqlite3_debug_mutex;
17089 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
17090 ** intended for use inside assert() statements.
17092 static int debugMutexHeld(sqlite3_mutex *pX){
17093 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17094 return p==0 || p->cnt>0;
17096 static int debugMutexNotheld(sqlite3_mutex *pX){
17097 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17098 return p==0 || p->cnt==0;
17102 ** Initialize and deinitialize the mutex subsystem.
17104 static int debugMutexInit(void){ return SQLITE_OK; }
17105 static int debugMutexEnd(void){ return SQLITE_OK; }
17108 ** The sqlite3_mutex_alloc() routine allocates a new
17109 ** mutex and returns a pointer to it. If it returns NULL
17110 ** that means that a mutex could not be allocated.
17112 static sqlite3_mutex *debugMutexAlloc(int id){
17113 static sqlite3_debug_mutex aStatic[6];
17114 sqlite3_debug_mutex *pNew = 0;
17115 switch( id ){
17116 case SQLITE_MUTEX_FAST:
17117 case SQLITE_MUTEX_RECURSIVE: {
17118 pNew = sqlite3Malloc(sizeof(*pNew));
17119 if( pNew ){
17120 pNew->id = id;
17121 pNew->cnt = 0;
17123 break;
17125 default: {
17126 assert( id-2 >= 0 );
17127 assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
17128 pNew = &aStatic[id-2];
17129 pNew->id = id;
17130 break;
17133 return (sqlite3_mutex*)pNew;
17137 ** This routine deallocates a previously allocated mutex.
17139 static void debugMutexFree(sqlite3_mutex *pX){
17140 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17141 assert( p->cnt==0 );
17142 assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
17143 sqlite3_free(p);
17147 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
17148 ** to enter a mutex. If another thread is already within the mutex,
17149 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
17150 ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
17151 ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
17152 ** be entered multiple times by the same thread. In such cases the,
17153 ** mutex must be exited an equal number of times before another thread
17154 ** can enter. If the same thread tries to enter any other kind of mutex
17155 ** more than once, the behavior is undefined.
17157 static void debugMutexEnter(sqlite3_mutex *pX){
17158 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17159 assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
17160 p->cnt++;
17162 static int debugMutexTry(sqlite3_mutex *pX){
17163 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17164 assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
17165 p->cnt++;
17166 return SQLITE_OK;
17170 ** The sqlite3_mutex_leave() routine exits a mutex that was
17171 ** previously entered by the same thread. The behavior
17172 ** is undefined if the mutex is not currently entered or
17173 ** is not currently allocated. SQLite will never do either.
17175 static void debugMutexLeave(sqlite3_mutex *pX){
17176 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17177 assert( debugMutexHeld(pX) );
17178 p->cnt--;
17179 assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
17182 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
17183 static const sqlite3_mutex_methods sMutex = {
17184 debugMutexInit,
17185 debugMutexEnd,
17186 debugMutexAlloc,
17187 debugMutexFree,
17188 debugMutexEnter,
17189 debugMutexTry,
17190 debugMutexLeave,
17192 debugMutexHeld,
17193 debugMutexNotheld
17196 return &sMutex;
17198 #endif /* SQLITE_DEBUG */
17201 ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
17202 ** is used regardless of the run-time threadsafety setting.
17204 #ifdef SQLITE_MUTEX_NOOP
17205 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
17206 return sqlite3NoopMutex();
17208 #endif /* SQLITE_MUTEX_NOOP */
17209 #endif /* SQLITE_MUTEX_OMIT */
17211 /************** End of mutex_noop.c ******************************************/
17212 /************** Begin file mutex_os2.c ***************************************/
17214 ** 2007 August 28
17216 ** The author disclaims copyright to this source code. In place of
17217 ** a legal notice, here is a blessing:
17219 ** May you do good and not evil.
17220 ** May you find forgiveness for yourself and forgive others.
17221 ** May you share freely, never taking more than you give.
17223 *************************************************************************
17224 ** This file contains the C functions that implement mutexes for OS/2
17228 ** The code in this file is only used if SQLITE_MUTEX_OS2 is defined.
17229 ** See the mutex.h file for details.
17231 #ifdef SQLITE_MUTEX_OS2
17233 /********************** OS/2 Mutex Implementation **********************
17235 ** This implementation of mutexes is built using the OS/2 API.
17239 ** The mutex object
17240 ** Each recursive mutex is an instance of the following structure.
17242 struct sqlite3_mutex {
17243 HMTX mutex; /* Mutex controlling the lock */
17244 int id; /* Mutex type */
17245 #ifdef SQLITE_DEBUG
17246 int trace; /* True to trace changes */
17247 #endif
17250 #ifdef SQLITE_DEBUG
17251 #define SQLITE3_MUTEX_INITIALIZER { 0, 0, 0 }
17252 #else
17253 #define SQLITE3_MUTEX_INITIALIZER { 0, 0 }
17254 #endif
17257 ** Initialize and deinitialize the mutex subsystem.
17259 static int os2MutexInit(void){ return SQLITE_OK; }
17260 static int os2MutexEnd(void){ return SQLITE_OK; }
17263 ** The sqlite3_mutex_alloc() routine allocates a new
17264 ** mutex and returns a pointer to it. If it returns NULL
17265 ** that means that a mutex could not be allocated.
17266 ** SQLite will unwind its stack and return an error. The argument
17267 ** to sqlite3_mutex_alloc() is one of these integer constants:
17269 ** <ul>
17270 ** <li> SQLITE_MUTEX_FAST
17271 ** <li> SQLITE_MUTEX_RECURSIVE
17272 ** <li> SQLITE_MUTEX_STATIC_MASTER
17273 ** <li> SQLITE_MUTEX_STATIC_MEM
17274 ** <li> SQLITE_MUTEX_STATIC_MEM2
17275 ** <li> SQLITE_MUTEX_STATIC_PRNG
17276 ** <li> SQLITE_MUTEX_STATIC_LRU
17277 ** <li> SQLITE_MUTEX_STATIC_LRU2
17278 ** </ul>
17280 ** The first two constants cause sqlite3_mutex_alloc() to create
17281 ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
17282 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
17283 ** The mutex implementation does not need to make a distinction
17284 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
17285 ** not want to. But SQLite will only request a recursive mutex in
17286 ** cases where it really needs one. If a faster non-recursive mutex
17287 ** implementation is available on the host platform, the mutex subsystem
17288 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
17290 ** The other allowed parameters to sqlite3_mutex_alloc() each return
17291 ** a pointer to a static preexisting mutex. Six static mutexes are
17292 ** used by the current version of SQLite. Future versions of SQLite
17293 ** may add additional static mutexes. Static mutexes are for internal
17294 ** use by SQLite only. Applications that use SQLite mutexes should
17295 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
17296 ** SQLITE_MUTEX_RECURSIVE.
17298 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
17299 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
17300 ** returns a different mutex on every call. But for the static
17301 ** mutex types, the same mutex is returned on every call that has
17302 ** the same type number.
17304 static sqlite3_mutex *os2MutexAlloc(int iType){
17305 sqlite3_mutex *p = NULL;
17306 switch( iType ){
17307 case SQLITE_MUTEX_FAST:
17308 case SQLITE_MUTEX_RECURSIVE: {
17309 p = sqlite3MallocZero( sizeof(*p) );
17310 if( p ){
17311 p->id = iType;
17312 if( DosCreateMutexSem( 0, &p->mutex, 0, FALSE ) != NO_ERROR ){
17313 sqlite3_free( p );
17314 p = NULL;
17317 break;
17319 default: {
17320 static volatile int isInit = 0;
17321 static sqlite3_mutex staticMutexes[6] = {
17322 SQLITE3_MUTEX_INITIALIZER,
17323 SQLITE3_MUTEX_INITIALIZER,
17324 SQLITE3_MUTEX_INITIALIZER,
17325 SQLITE3_MUTEX_INITIALIZER,
17326 SQLITE3_MUTEX_INITIALIZER,
17327 SQLITE3_MUTEX_INITIALIZER,
17329 if ( !isInit ){
17330 APIRET rc;
17331 PTIB ptib;
17332 PPIB ppib;
17333 HMTX mutex;
17334 char name[32];
17335 DosGetInfoBlocks( &ptib, &ppib );
17336 sqlite3_snprintf( sizeof(name), name, "\\SEM32\\SQLITE%04x",
17337 ppib->pib_ulpid );
17338 while( !isInit ){
17339 mutex = 0;
17340 rc = DosCreateMutexSem( name, &mutex, 0, FALSE);
17341 if( rc == NO_ERROR ){
17342 unsigned int i;
17343 if( !isInit ){
17344 for( i = 0; i < sizeof(staticMutexes)/sizeof(staticMutexes[0]); i++ ){
17345 DosCreateMutexSem( 0, &staticMutexes[i].mutex, 0, FALSE );
17347 isInit = 1;
17349 DosCloseMutexSem( mutex );
17350 }else if( rc == ERROR_DUPLICATE_NAME ){
17351 DosSleep( 1 );
17352 }else{
17353 return p;
17357 assert( iType-2 >= 0 );
17358 assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
17359 p = &staticMutexes[iType-2];
17360 p->id = iType;
17361 break;
17364 return p;
17369 ** This routine deallocates a previously allocated mutex.
17370 ** SQLite is careful to deallocate every mutex that it allocates.
17372 static void os2MutexFree(sqlite3_mutex *p){
17373 #ifdef SQLITE_DEBUG
17374 TID tid;
17375 PID pid;
17376 ULONG ulCount;
17377 DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
17378 assert( ulCount==0 );
17379 assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
17380 #endif
17381 DosCloseMutexSem( p->mutex );
17382 sqlite3_free( p );
17385 #ifdef SQLITE_DEBUG
17387 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
17388 ** intended for use inside assert() statements.
17390 static int os2MutexHeld(sqlite3_mutex *p){
17391 TID tid;
17392 PID pid;
17393 ULONG ulCount;
17394 PTIB ptib;
17395 DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
17396 if( ulCount==0 || ( ulCount>1 && p->id!=SQLITE_MUTEX_RECURSIVE ) )
17397 return 0;
17398 DosGetInfoBlocks(&ptib, NULL);
17399 return tid==ptib->tib_ptib2->tib2_ultid;
17401 static int os2MutexNotheld(sqlite3_mutex *p){
17402 TID tid;
17403 PID pid;
17404 ULONG ulCount;
17405 PTIB ptib;
17406 DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
17407 if( ulCount==0 )
17408 return 1;
17409 DosGetInfoBlocks(&ptib, NULL);
17410 return tid!=ptib->tib_ptib2->tib2_ultid;
17412 static void os2MutexTrace(sqlite3_mutex *p, char *pAction){
17413 TID tid;
17414 PID pid;
17415 ULONG ulCount;
17416 DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
17417 printf("%s mutex %p (%d) with nRef=%ld\n", pAction, (void*)p, p->trace, ulCount);
17419 #endif
17422 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
17423 ** to enter a mutex. If another thread is already within the mutex,
17424 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
17425 ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
17426 ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
17427 ** be entered multiple times by the same thread. In such cases the,
17428 ** mutex must be exited an equal number of times before another thread
17429 ** can enter. If the same thread tries to enter any other kind of mutex
17430 ** more than once, the behavior is undefined.
17432 static void os2MutexEnter(sqlite3_mutex *p){
17433 assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
17434 DosRequestMutexSem(p->mutex, SEM_INDEFINITE_WAIT);
17435 #ifdef SQLITE_DEBUG
17436 if( p->trace ) os2MutexTrace(p, "enter");
17437 #endif
17439 static int os2MutexTry(sqlite3_mutex *p){
17440 int rc = SQLITE_BUSY;
17441 assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
17442 if( DosRequestMutexSem(p->mutex, SEM_IMMEDIATE_RETURN) == NO_ERROR ) {
17443 rc = SQLITE_OK;
17444 #ifdef SQLITE_DEBUG
17445 if( p->trace ) os2MutexTrace(p, "try");
17446 #endif
17448 return rc;
17452 ** The sqlite3_mutex_leave() routine exits a mutex that was
17453 ** previously entered by the same thread. The behavior
17454 ** is undefined if the mutex is not currently entered or
17455 ** is not currently allocated. SQLite will never do either.
17457 static void os2MutexLeave(sqlite3_mutex *p){
17458 assert( os2MutexHeld(p) );
17459 DosReleaseMutexSem(p->mutex);
17460 #ifdef SQLITE_DEBUG
17461 if( p->trace ) os2MutexTrace(p, "leave");
17462 #endif
17465 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
17466 static const sqlite3_mutex_methods sMutex = {
17467 os2MutexInit,
17468 os2MutexEnd,
17469 os2MutexAlloc,
17470 os2MutexFree,
17471 os2MutexEnter,
17472 os2MutexTry,
17473 os2MutexLeave,
17474 #ifdef SQLITE_DEBUG
17475 os2MutexHeld,
17476 os2MutexNotheld
17477 #else
17480 #endif
17483 return &sMutex;
17485 #endif /* SQLITE_MUTEX_OS2 */
17487 /************** End of mutex_os2.c *******************************************/
17488 /************** Begin file mutex_unix.c **************************************/
17490 ** 2007 August 28
17492 ** The author disclaims copyright to this source code. In place of
17493 ** a legal notice, here is a blessing:
17495 ** May you do good and not evil.
17496 ** May you find forgiveness for yourself and forgive others.
17497 ** May you share freely, never taking more than you give.
17499 *************************************************************************
17500 ** This file contains the C functions that implement mutexes for pthreads
17504 ** The code in this file is only used if we are compiling threadsafe
17505 ** under unix with pthreads.
17507 ** Note that this implementation requires a version of pthreads that
17508 ** supports recursive mutexes.
17510 #ifdef SQLITE_MUTEX_PTHREADS
17512 #include <pthread.h>
17515 ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
17516 ** are necessary under two condidtions: (1) Debug builds and (2) using
17517 ** home-grown mutexes. Encapsulate these conditions into a single #define.
17519 #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
17520 # define SQLITE_MUTEX_NREF 1
17521 #else
17522 # define SQLITE_MUTEX_NREF 0
17523 #endif
17526 ** Each recursive mutex is an instance of the following structure.
17528 struct sqlite3_mutex {
17529 pthread_mutex_t mutex; /* Mutex controlling the lock */
17530 #if SQLITE_MUTEX_NREF
17531 int id; /* Mutex type */
17532 volatile int nRef; /* Number of entrances */
17533 volatile pthread_t owner; /* Thread that is within this mutex */
17534 int trace; /* True to trace changes */
17535 #endif
17537 #if SQLITE_MUTEX_NREF
17538 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
17539 #else
17540 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
17541 #endif
17544 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
17545 ** intended for use only inside assert() statements. On some platforms,
17546 ** there might be race conditions that can cause these routines to
17547 ** deliver incorrect results. In particular, if pthread_equal() is
17548 ** not an atomic operation, then these routines might delivery
17549 ** incorrect results. On most platforms, pthread_equal() is a
17550 ** comparison of two integers and is therefore atomic. But we are
17551 ** told that HPUX is not such a platform. If so, then these routines
17552 ** will not always work correctly on HPUX.
17554 ** On those platforms where pthread_equal() is not atomic, SQLite
17555 ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
17556 ** make sure no assert() statements are evaluated and hence these
17557 ** routines are never called.
17559 #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
17560 static int pthreadMutexHeld(sqlite3_mutex *p){
17561 return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
17563 static int pthreadMutexNotheld(sqlite3_mutex *p){
17564 return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
17566 #endif
17569 ** Initialize and deinitialize the mutex subsystem.
17571 static int pthreadMutexInit(void){ return SQLITE_OK; }
17572 static int pthreadMutexEnd(void){ return SQLITE_OK; }
17575 ** The sqlite3_mutex_alloc() routine allocates a new
17576 ** mutex and returns a pointer to it. If it returns NULL
17577 ** that means that a mutex could not be allocated. SQLite
17578 ** will unwind its stack and return an error. The argument
17579 ** to sqlite3_mutex_alloc() is one of these integer constants:
17581 ** <ul>
17582 ** <li> SQLITE_MUTEX_FAST
17583 ** <li> SQLITE_MUTEX_RECURSIVE
17584 ** <li> SQLITE_MUTEX_STATIC_MASTER
17585 ** <li> SQLITE_MUTEX_STATIC_MEM
17586 ** <li> SQLITE_MUTEX_STATIC_MEM2
17587 ** <li> SQLITE_MUTEX_STATIC_PRNG
17588 ** <li> SQLITE_MUTEX_STATIC_LRU
17589 ** <li> SQLITE_MUTEX_STATIC_PMEM
17590 ** </ul>
17592 ** The first two constants cause sqlite3_mutex_alloc() to create
17593 ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
17594 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
17595 ** The mutex implementation does not need to make a distinction
17596 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
17597 ** not want to. But SQLite will only request a recursive mutex in
17598 ** cases where it really needs one. If a faster non-recursive mutex
17599 ** implementation is available on the host platform, the mutex subsystem
17600 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
17602 ** The other allowed parameters to sqlite3_mutex_alloc() each return
17603 ** a pointer to a static preexisting mutex. Six static mutexes are
17604 ** used by the current version of SQLite. Future versions of SQLite
17605 ** may add additional static mutexes. Static mutexes are for internal
17606 ** use by SQLite only. Applications that use SQLite mutexes should
17607 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
17608 ** SQLITE_MUTEX_RECURSIVE.
17610 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
17611 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
17612 ** returns a different mutex on every call. But for the static
17613 ** mutex types, the same mutex is returned on every call that has
17614 ** the same type number.
17616 static sqlite3_mutex *pthreadMutexAlloc(int iType){
17617 static sqlite3_mutex staticMutexes[] = {
17618 SQLITE3_MUTEX_INITIALIZER,
17619 SQLITE3_MUTEX_INITIALIZER,
17620 SQLITE3_MUTEX_INITIALIZER,
17621 SQLITE3_MUTEX_INITIALIZER,
17622 SQLITE3_MUTEX_INITIALIZER,
17623 SQLITE3_MUTEX_INITIALIZER
17625 sqlite3_mutex *p;
17626 switch( iType ){
17627 case SQLITE_MUTEX_RECURSIVE: {
17628 p = sqlite3MallocZero( sizeof(*p) );
17629 if( p ){
17630 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
17631 /* If recursive mutexes are not available, we will have to
17632 ** build our own. See below. */
17633 pthread_mutex_init(&p->mutex, 0);
17634 #else
17635 /* Use a recursive mutex if it is available */
17636 pthread_mutexattr_t recursiveAttr;
17637 pthread_mutexattr_init(&recursiveAttr);
17638 pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
17639 pthread_mutex_init(&p->mutex, &recursiveAttr);
17640 pthread_mutexattr_destroy(&recursiveAttr);
17641 #endif
17642 #if SQLITE_MUTEX_NREF
17643 p->id = iType;
17644 #endif
17646 break;
17648 case SQLITE_MUTEX_FAST: {
17649 p = sqlite3MallocZero( sizeof(*p) );
17650 if( p ){
17651 #if SQLITE_MUTEX_NREF
17652 p->id = iType;
17653 #endif
17654 pthread_mutex_init(&p->mutex, 0);
17656 break;
17658 default: {
17659 assert( iType-2 >= 0 );
17660 assert( iType-2 < ArraySize(staticMutexes) );
17661 p = &staticMutexes[iType-2];
17662 #if SQLITE_MUTEX_NREF
17663 p->id = iType;
17664 #endif
17665 break;
17668 return p;
17673 ** This routine deallocates a previously
17674 ** allocated mutex. SQLite is careful to deallocate every
17675 ** mutex that it allocates.
17677 static void pthreadMutexFree(sqlite3_mutex *p){
17678 assert( p->nRef==0 );
17679 assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
17680 pthread_mutex_destroy(&p->mutex);
17681 sqlite3_free(p);
17685 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
17686 ** to enter a mutex. If another thread is already within the mutex,
17687 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
17688 ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
17689 ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
17690 ** be entered multiple times by the same thread. In such cases the,
17691 ** mutex must be exited an equal number of times before another thread
17692 ** can enter. If the same thread tries to enter any other kind of mutex
17693 ** more than once, the behavior is undefined.
17695 static void pthreadMutexEnter(sqlite3_mutex *p){
17696 assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
17698 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
17699 /* If recursive mutexes are not available, then we have to grow
17700 ** our own. This implementation assumes that pthread_equal()
17701 ** is atomic - that it cannot be deceived into thinking self
17702 ** and p->owner are equal if p->owner changes between two values
17703 ** that are not equal to self while the comparison is taking place.
17704 ** This implementation also assumes a coherent cache - that
17705 ** separate processes cannot read different values from the same
17706 ** address at the same time. If either of these two conditions
17707 ** are not met, then the mutexes will fail and problems will result.
17710 pthread_t self = pthread_self();
17711 if( p->nRef>0 && pthread_equal(p->owner, self) ){
17712 p->nRef++;
17713 }else{
17714 pthread_mutex_lock(&p->mutex);
17715 assert( p->nRef==0 );
17716 p->owner = self;
17717 p->nRef = 1;
17720 #else
17721 /* Use the built-in recursive mutexes if they are available.
17723 pthread_mutex_lock(&p->mutex);
17724 #if SQLITE_MUTEX_NREF
17725 assert( p->nRef>0 || p->owner==0 );
17726 p->owner = pthread_self();
17727 p->nRef++;
17728 #endif
17729 #endif
17731 #ifdef SQLITE_DEBUG
17732 if( p->trace ){
17733 printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17735 #endif
17737 static int pthreadMutexTry(sqlite3_mutex *p){
17738 int rc;
17739 assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
17741 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
17742 /* If recursive mutexes are not available, then we have to grow
17743 ** our own. This implementation assumes that pthread_equal()
17744 ** is atomic - that it cannot be deceived into thinking self
17745 ** and p->owner are equal if p->owner changes between two values
17746 ** that are not equal to self while the comparison is taking place.
17747 ** This implementation also assumes a coherent cache - that
17748 ** separate processes cannot read different values from the same
17749 ** address at the same time. If either of these two conditions
17750 ** are not met, then the mutexes will fail and problems will result.
17753 pthread_t self = pthread_self();
17754 if( p->nRef>0 && pthread_equal(p->owner, self) ){
17755 p->nRef++;
17756 rc = SQLITE_OK;
17757 }else if( pthread_mutex_trylock(&p->mutex)==0 ){
17758 assert( p->nRef==0 );
17759 p->owner = self;
17760 p->nRef = 1;
17761 rc = SQLITE_OK;
17762 }else{
17763 rc = SQLITE_BUSY;
17766 #else
17767 /* Use the built-in recursive mutexes if they are available.
17769 if( pthread_mutex_trylock(&p->mutex)==0 ){
17770 #if SQLITE_MUTEX_NREF
17771 p->owner = pthread_self();
17772 p->nRef++;
17773 #endif
17774 rc = SQLITE_OK;
17775 }else{
17776 rc = SQLITE_BUSY;
17778 #endif
17780 #ifdef SQLITE_DEBUG
17781 if( rc==SQLITE_OK && p->trace ){
17782 printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17784 #endif
17785 return rc;
17789 ** The sqlite3_mutex_leave() routine exits a mutex that was
17790 ** previously entered by the same thread. The behavior
17791 ** is undefined if the mutex is not currently entered or
17792 ** is not currently allocated. SQLite will never do either.
17794 static void pthreadMutexLeave(sqlite3_mutex *p){
17795 assert( pthreadMutexHeld(p) );
17796 #if SQLITE_MUTEX_NREF
17797 p->nRef--;
17798 if( p->nRef==0 ) p->owner = 0;
17799 #endif
17800 assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
17802 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
17803 if( p->nRef==0 ){
17804 pthread_mutex_unlock(&p->mutex);
17806 #else
17807 pthread_mutex_unlock(&p->mutex);
17808 #endif
17810 #ifdef SQLITE_DEBUG
17811 if( p->trace ){
17812 printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17814 #endif
17817 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
17818 static const sqlite3_mutex_methods sMutex = {
17819 pthreadMutexInit,
17820 pthreadMutexEnd,
17821 pthreadMutexAlloc,
17822 pthreadMutexFree,
17823 pthreadMutexEnter,
17824 pthreadMutexTry,
17825 pthreadMutexLeave,
17826 #ifdef SQLITE_DEBUG
17827 pthreadMutexHeld,
17828 pthreadMutexNotheld
17829 #else
17832 #endif
17835 return &sMutex;
17838 #endif /* SQLITE_MUTEX_PTHREAD */
17840 /************** End of mutex_unix.c ******************************************/
17841 /************** Begin file mutex_w32.c ***************************************/
17843 ** 2007 August 14
17845 ** The author disclaims copyright to this source code. In place of
17846 ** a legal notice, here is a blessing:
17848 ** May you do good and not evil.
17849 ** May you find forgiveness for yourself and forgive others.
17850 ** May you share freely, never taking more than you give.
17852 *************************************************************************
17853 ** This file contains the C functions that implement mutexes for win32
17857 ** The code in this file is only used if we are compiling multithreaded
17858 ** on a win32 system.
17860 #ifdef SQLITE_MUTEX_W32
17863 ** Each recursive mutex is an instance of the following structure.
17865 struct sqlite3_mutex {
17866 CRITICAL_SECTION mutex; /* Mutex controlling the lock */
17867 int id; /* Mutex type */
17868 #ifdef SQLITE_DEBUG
17869 volatile int nRef; /* Number of enterances */
17870 volatile DWORD owner; /* Thread holding this mutex */
17871 int trace; /* True to trace changes */
17872 #endif
17874 #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
17875 #ifdef SQLITE_DEBUG
17876 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, 0L, (DWORD)0, 0 }
17877 #else
17878 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
17879 #endif
17882 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
17883 ** or WinCE. Return false (zero) for Win95, Win98, or WinME.
17885 ** Here is an interesting observation: Win95, Win98, and WinME lack
17886 ** the LockFileEx() API. But we can still statically link against that
17887 ** API as long as we don't call it win running Win95/98/ME. A call to
17888 ** this routine is used to determine if the host is Win95/98/ME or
17889 ** WinNT/2K/XP so that we will know whether or not we can safely call
17890 ** the LockFileEx() API.
17892 ** mutexIsNT() is only used for the TryEnterCriticalSection() API call,
17893 ** which is only available if your application was compiled with
17894 ** _WIN32_WINNT defined to a value >= 0x0400. Currently, the only
17895 ** call to TryEnterCriticalSection() is #ifdef'ed out, so #ifdef
17896 ** this out as well.
17898 #if 0
17899 #if SQLITE_OS_WINCE
17900 # define mutexIsNT() (1)
17901 #else
17902 static int mutexIsNT(void){
17903 static int osType = 0;
17904 if( osType==0 ){
17905 OSVERSIONINFO sInfo;
17906 sInfo.dwOSVersionInfoSize = sizeof(sInfo);
17907 GetVersionEx(&sInfo);
17908 osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
17910 return osType==2;
17912 #endif /* SQLITE_OS_WINCE */
17913 #endif
17915 #ifdef SQLITE_DEBUG
17917 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
17918 ** intended for use only inside assert() statements.
17920 static int winMutexHeld(sqlite3_mutex *p){
17921 return p->nRef!=0 && p->owner==GetCurrentThreadId();
17923 static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
17924 return p->nRef==0 || p->owner!=tid;
17926 static int winMutexNotheld(sqlite3_mutex *p){
17927 DWORD tid = GetCurrentThreadId();
17928 return winMutexNotheld2(p, tid);
17930 #endif
17934 ** Initialize and deinitialize the mutex subsystem.
17936 static sqlite3_mutex winMutex_staticMutexes[6] = {
17937 SQLITE3_MUTEX_INITIALIZER,
17938 SQLITE3_MUTEX_INITIALIZER,
17939 SQLITE3_MUTEX_INITIALIZER,
17940 SQLITE3_MUTEX_INITIALIZER,
17941 SQLITE3_MUTEX_INITIALIZER,
17942 SQLITE3_MUTEX_INITIALIZER
17944 static int winMutex_isInit = 0;
17945 /* As winMutexInit() and winMutexEnd() are called as part
17946 ** of the sqlite3_initialize and sqlite3_shutdown()
17947 ** processing, the "interlocked" magic is probably not
17948 ** strictly necessary.
17950 static long winMutex_lock = 0;
17952 static int winMutexInit(void){
17953 /* The first to increment to 1 does actual initialization */
17954 if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
17955 int i;
17956 for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
17957 InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
17959 winMutex_isInit = 1;
17960 }else{
17961 /* Someone else is in the process of initing the static mutexes */
17962 while( !winMutex_isInit ){
17963 Sleep(1);
17966 return SQLITE_OK;
17969 static int winMutexEnd(void){
17970 /* The first to decrement to 0 does actual shutdown
17971 ** (which should be the last to shutdown.) */
17972 if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
17973 if( winMutex_isInit==1 ){
17974 int i;
17975 for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
17976 DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
17978 winMutex_isInit = 0;
17981 return SQLITE_OK;
17985 ** The sqlite3_mutex_alloc() routine allocates a new
17986 ** mutex and returns a pointer to it. If it returns NULL
17987 ** that means that a mutex could not be allocated. SQLite
17988 ** will unwind its stack and return an error. The argument
17989 ** to sqlite3_mutex_alloc() is one of these integer constants:
17991 ** <ul>
17992 ** <li> SQLITE_MUTEX_FAST
17993 ** <li> SQLITE_MUTEX_RECURSIVE
17994 ** <li> SQLITE_MUTEX_STATIC_MASTER
17995 ** <li> SQLITE_MUTEX_STATIC_MEM
17996 ** <li> SQLITE_MUTEX_STATIC_MEM2
17997 ** <li> SQLITE_MUTEX_STATIC_PRNG
17998 ** <li> SQLITE_MUTEX_STATIC_LRU
17999 ** <li> SQLITE_MUTEX_STATIC_PMEM
18000 ** </ul>
18002 ** The first two constants cause sqlite3_mutex_alloc() to create
18003 ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
18004 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
18005 ** The mutex implementation does not need to make a distinction
18006 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
18007 ** not want to. But SQLite will only request a recursive mutex in
18008 ** cases where it really needs one. If a faster non-recursive mutex
18009 ** implementation is available on the host platform, the mutex subsystem
18010 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
18012 ** The other allowed parameters to sqlite3_mutex_alloc() each return
18013 ** a pointer to a static preexisting mutex. Six static mutexes are
18014 ** used by the current version of SQLite. Future versions of SQLite
18015 ** may add additional static mutexes. Static mutexes are for internal
18016 ** use by SQLite only. Applications that use SQLite mutexes should
18017 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
18018 ** SQLITE_MUTEX_RECURSIVE.
18020 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
18021 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
18022 ** returns a different mutex on every call. But for the static
18023 ** mutex types, the same mutex is returned on every call that has
18024 ** the same type number.
18026 static sqlite3_mutex *winMutexAlloc(int iType){
18027 sqlite3_mutex *p;
18029 switch( iType ){
18030 case SQLITE_MUTEX_FAST:
18031 case SQLITE_MUTEX_RECURSIVE: {
18032 p = sqlite3MallocZero( sizeof(*p) );
18033 if( p ){
18034 #ifdef SQLITE_DEBUG
18035 p->id = iType;
18036 #endif
18037 InitializeCriticalSection(&p->mutex);
18039 break;
18041 default: {
18042 assert( winMutex_isInit==1 );
18043 assert( iType-2 >= 0 );
18044 assert( iType-2 < ArraySize(winMutex_staticMutexes) );
18045 p = &winMutex_staticMutexes[iType-2];
18046 #ifdef SQLITE_DEBUG
18047 p->id = iType;
18048 #endif
18049 break;
18052 return p;
18057 ** This routine deallocates a previously
18058 ** allocated mutex. SQLite is careful to deallocate every
18059 ** mutex that it allocates.
18061 static void winMutexFree(sqlite3_mutex *p){
18062 assert( p );
18063 assert( p->nRef==0 && p->owner==0 );
18064 assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
18065 DeleteCriticalSection(&p->mutex);
18066 sqlite3_free(p);
18070 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
18071 ** to enter a mutex. If another thread is already within the mutex,
18072 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
18073 ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
18074 ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
18075 ** be entered multiple times by the same thread. In such cases the,
18076 ** mutex must be exited an equal number of times before another thread
18077 ** can enter. If the same thread tries to enter any other kind of mutex
18078 ** more than once, the behavior is undefined.
18080 static void winMutexEnter(sqlite3_mutex *p){
18081 #ifdef SQLITE_DEBUG
18082 DWORD tid = GetCurrentThreadId();
18083 assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
18084 #endif
18085 EnterCriticalSection(&p->mutex);
18086 #ifdef SQLITE_DEBUG
18087 assert( p->nRef>0 || p->owner==0 );
18088 p->owner = tid;
18089 p->nRef++;
18090 if( p->trace ){
18091 printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18093 #endif
18095 static int winMutexTry(sqlite3_mutex *p){
18096 #ifndef NDEBUG
18097 DWORD tid = GetCurrentThreadId();
18098 #endif
18099 int rc = SQLITE_BUSY;
18100 assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
18102 ** The sqlite3_mutex_try() routine is very rarely used, and when it
18103 ** is used it is merely an optimization. So it is OK for it to always
18104 ** fail.
18106 ** The TryEnterCriticalSection() interface is only available on WinNT.
18107 ** And some windows compilers complain if you try to use it without
18108 ** first doing some #defines that prevent SQLite from building on Win98.
18109 ** For that reason, we will omit this optimization for now. See
18110 ** ticket #2685.
18112 #if 0
18113 if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
18114 p->owner = tid;
18115 p->nRef++;
18116 rc = SQLITE_OK;
18118 #else
18119 UNUSED_PARAMETER(p);
18120 #endif
18121 #ifdef SQLITE_DEBUG
18122 if( rc==SQLITE_OK && p->trace ){
18123 printf("try mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18125 #endif
18126 return rc;
18130 ** The sqlite3_mutex_leave() routine exits a mutex that was
18131 ** previously entered by the same thread. The behavior
18132 ** is undefined if the mutex is not currently entered or
18133 ** is not currently allocated. SQLite will never do either.
18135 static void winMutexLeave(sqlite3_mutex *p){
18136 #ifndef NDEBUG
18137 DWORD tid = GetCurrentThreadId();
18138 assert( p->nRef>0 );
18139 assert( p->owner==tid );
18140 p->nRef--;
18141 if( p->nRef==0 ) p->owner = 0;
18142 assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
18143 #endif
18144 LeaveCriticalSection(&p->mutex);
18145 #ifdef SQLITE_DEBUG
18146 if( p->trace ){
18147 printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18149 #endif
18152 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
18153 static const sqlite3_mutex_methods sMutex = {
18154 winMutexInit,
18155 winMutexEnd,
18156 winMutexAlloc,
18157 winMutexFree,
18158 winMutexEnter,
18159 winMutexTry,
18160 winMutexLeave,
18161 #ifdef SQLITE_DEBUG
18162 winMutexHeld,
18163 winMutexNotheld
18164 #else
18167 #endif
18170 return &sMutex;
18172 #endif /* SQLITE_MUTEX_W32 */
18174 /************** End of mutex_w32.c *******************************************/
18175 /************** Begin file malloc.c ******************************************/
18177 ** 2001 September 15
18179 ** The author disclaims copyright to this source code. In place of
18180 ** a legal notice, here is a blessing:
18182 ** May you do good and not evil.
18183 ** May you find forgiveness for yourself and forgive others.
18184 ** May you share freely, never taking more than you give.
18186 *************************************************************************
18188 ** Memory allocation functions used throughout sqlite.
18190 /* #include <stdarg.h> */
18193 ** Attempt to release up to n bytes of non-essential memory currently
18194 ** held by SQLite. An example of non-essential memory is memory used to
18195 ** cache database pages that are not currently in use.
18197 SQLITE_API int sqlite3_release_memory(int n){
18198 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
18199 return sqlite3PcacheReleaseMemory(n);
18200 #else
18201 /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
18202 ** is a no-op returning zero if SQLite is not compiled with
18203 ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
18204 UNUSED_PARAMETER(n);
18205 return 0;
18206 #endif
18210 ** An instance of the following object records the location of
18211 ** each unused scratch buffer.
18213 typedef struct ScratchFreeslot {
18214 struct ScratchFreeslot *pNext; /* Next unused scratch buffer */
18215 } ScratchFreeslot;
18218 ** State information local to the memory allocation subsystem.
18220 static SQLITE_WSD struct Mem0Global {
18221 sqlite3_mutex *mutex; /* Mutex to serialize access */
18224 ** The alarm callback and its arguments. The mem0.mutex lock will
18225 ** be held while the callback is running. Recursive calls into
18226 ** the memory subsystem are allowed, but no new callbacks will be
18227 ** issued.
18229 sqlite3_int64 alarmThreshold;
18230 void (*alarmCallback)(void*, sqlite3_int64,int);
18231 void *alarmArg;
18234 ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
18235 ** (so that a range test can be used to determine if an allocation
18236 ** being freed came from pScratch) and a pointer to the list of
18237 ** unused scratch allocations.
18239 void *pScratchEnd;
18240 ScratchFreeslot *pScratchFree;
18241 u32 nScratchFree;
18244 ** True if heap is nearly "full" where "full" is defined by the
18245 ** sqlite3_soft_heap_limit() setting.
18247 int nearlyFull;
18248 } mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
18250 #define mem0 GLOBAL(struct Mem0Global, mem0)
18253 ** This routine runs when the memory allocator sees that the
18254 ** total memory allocation is about to exceed the soft heap
18255 ** limit.
18257 static void softHeapLimitEnforcer(
18258 void *NotUsed,
18259 sqlite3_int64 NotUsed2,
18260 int allocSize
18262 UNUSED_PARAMETER2(NotUsed, NotUsed2);
18263 sqlite3_release_memory(allocSize);
18267 ** Change the alarm callback
18269 static int sqlite3MemoryAlarm(
18270 void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
18271 void *pArg,
18272 sqlite3_int64 iThreshold
18274 int nUsed;
18275 sqlite3_mutex_enter(mem0.mutex);
18276 mem0.alarmCallback = xCallback;
18277 mem0.alarmArg = pArg;
18278 mem0.alarmThreshold = iThreshold;
18279 nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
18280 mem0.nearlyFull = (iThreshold>0 && iThreshold<=nUsed);
18281 sqlite3_mutex_leave(mem0.mutex);
18282 return SQLITE_OK;
18285 #ifndef SQLITE_OMIT_DEPRECATED
18287 ** Deprecated external interface. Internal/core SQLite code
18288 ** should call sqlite3MemoryAlarm.
18290 SQLITE_API int sqlite3_memory_alarm(
18291 void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
18292 void *pArg,
18293 sqlite3_int64 iThreshold
18295 return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
18297 #endif
18300 ** Set the soft heap-size limit for the library. Passing a zero or
18301 ** negative value indicates no limit.
18303 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
18304 sqlite3_int64 priorLimit;
18305 sqlite3_int64 excess;
18306 #ifndef SQLITE_OMIT_AUTOINIT
18307 sqlite3_initialize();
18308 #endif
18309 sqlite3_mutex_enter(mem0.mutex);
18310 priorLimit = mem0.alarmThreshold;
18311 sqlite3_mutex_leave(mem0.mutex);
18312 if( n<0 ) return priorLimit;
18313 if( n>0 ){
18314 sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, n);
18315 }else{
18316 sqlite3MemoryAlarm(0, 0, 0);
18318 excess = sqlite3_memory_used() - n;
18319 if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
18320 return priorLimit;
18322 SQLITE_API void sqlite3_soft_heap_limit(int n){
18323 if( n<0 ) n = 0;
18324 sqlite3_soft_heap_limit64(n);
18328 ** Initialize the memory allocation subsystem.
18330 SQLITE_PRIVATE int sqlite3MallocInit(void){
18331 if( sqlite3GlobalConfig.m.xMalloc==0 ){
18332 sqlite3MemSetDefault();
18334 memset(&mem0, 0, sizeof(mem0));
18335 if( sqlite3GlobalConfig.bCoreMutex ){
18336 mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
18338 if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
18339 && sqlite3GlobalConfig.nScratch>0 ){
18340 int i, n, sz;
18341 ScratchFreeslot *pSlot;
18342 sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
18343 sqlite3GlobalConfig.szScratch = sz;
18344 pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
18345 n = sqlite3GlobalConfig.nScratch;
18346 mem0.pScratchFree = pSlot;
18347 mem0.nScratchFree = n;
18348 for(i=0; i<n-1; i++){
18349 pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
18350 pSlot = pSlot->pNext;
18352 pSlot->pNext = 0;
18353 mem0.pScratchEnd = (void*)&pSlot[1];
18354 }else{
18355 mem0.pScratchEnd = 0;
18356 sqlite3GlobalConfig.pScratch = 0;
18357 sqlite3GlobalConfig.szScratch = 0;
18358 sqlite3GlobalConfig.nScratch = 0;
18360 if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
18361 || sqlite3GlobalConfig.nPage<1 ){
18362 sqlite3GlobalConfig.pPage = 0;
18363 sqlite3GlobalConfig.szPage = 0;
18364 sqlite3GlobalConfig.nPage = 0;
18366 return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
18370 ** Return true if the heap is currently under memory pressure - in other
18371 ** words if the amount of heap used is close to the limit set by
18372 ** sqlite3_soft_heap_limit().
18374 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
18375 return mem0.nearlyFull;
18379 ** Deinitialize the memory allocation subsystem.
18381 SQLITE_PRIVATE void sqlite3MallocEnd(void){
18382 if( sqlite3GlobalConfig.m.xShutdown ){
18383 sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
18385 memset(&mem0, 0, sizeof(mem0));
18389 ** Return the amount of memory currently checked out.
18391 SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
18392 int n, mx;
18393 sqlite3_int64 res;
18394 sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
18395 res = (sqlite3_int64)n; /* Work around bug in Borland C. Ticket #3216 */
18396 return res;
18400 ** Return the maximum amount of memory that has ever been
18401 ** checked out since either the beginning of this process
18402 ** or since the most recent reset.
18404 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
18405 int n, mx;
18406 sqlite3_int64 res;
18407 sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
18408 res = (sqlite3_int64)mx; /* Work around bug in Borland C. Ticket #3216 */
18409 return res;
18413 ** Trigger the alarm
18415 static void sqlite3MallocAlarm(int nByte){
18416 void (*xCallback)(void*,sqlite3_int64,int);
18417 sqlite3_int64 nowUsed;
18418 void *pArg;
18419 if( mem0.alarmCallback==0 ) return;
18420 xCallback = mem0.alarmCallback;
18421 nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
18422 pArg = mem0.alarmArg;
18423 mem0.alarmCallback = 0;
18424 sqlite3_mutex_leave(mem0.mutex);
18425 xCallback(pArg, nowUsed, nByte);
18426 sqlite3_mutex_enter(mem0.mutex);
18427 mem0.alarmCallback = xCallback;
18428 mem0.alarmArg = pArg;
18432 ** Do a memory allocation with statistics and alarms. Assume the
18433 ** lock is already held.
18435 static int mallocWithAlarm(int n, void **pp){
18436 int nFull;
18437 void *p;
18438 assert( sqlite3_mutex_held(mem0.mutex) );
18439 nFull = sqlite3GlobalConfig.m.xRoundup(n);
18440 sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
18441 if( mem0.alarmCallback!=0 ){
18442 int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
18443 if( nUsed >= mem0.alarmThreshold - nFull ){
18444 mem0.nearlyFull = 1;
18445 sqlite3MallocAlarm(nFull);
18446 }else{
18447 mem0.nearlyFull = 0;
18450 p = sqlite3GlobalConfig.m.xMalloc(nFull);
18451 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
18452 if( p==0 && mem0.alarmCallback ){
18453 sqlite3MallocAlarm(nFull);
18454 p = sqlite3GlobalConfig.m.xMalloc(nFull);
18456 #endif
18457 if( p ){
18458 nFull = sqlite3MallocSize(p);
18459 sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
18460 sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, 1);
18462 *pp = p;
18463 return nFull;
18467 ** Allocate memory. This routine is like sqlite3_malloc() except that it
18468 ** assumes the memory subsystem has already been initialized.
18470 SQLITE_PRIVATE void *sqlite3Malloc(int n){
18471 void *p;
18472 if( n<=0 /* IMP: R-65312-04917 */
18473 || n>=0x7fffff00
18475 /* A memory allocation of a number of bytes which is near the maximum
18476 ** signed integer value might cause an integer overflow inside of the
18477 ** xMalloc(). Hence we limit the maximum size to 0x7fffff00, giving
18478 ** 255 bytes of overhead. SQLite itself will never use anything near
18479 ** this amount. The only way to reach the limit is with sqlite3_malloc() */
18480 p = 0;
18481 }else if( sqlite3GlobalConfig.bMemstat ){
18482 sqlite3_mutex_enter(mem0.mutex);
18483 mallocWithAlarm(n, &p);
18484 sqlite3_mutex_leave(mem0.mutex);
18485 }else{
18486 p = sqlite3GlobalConfig.m.xMalloc(n);
18488 assert( EIGHT_BYTE_ALIGNMENT(p) ); /* IMP: R-04675-44850 */
18489 return p;
18493 ** This version of the memory allocation is for use by the application.
18494 ** First make sure the memory subsystem is initialized, then do the
18495 ** allocation.
18497 SQLITE_API void *sqlite3_malloc(int n){
18498 #ifndef SQLITE_OMIT_AUTOINIT
18499 if( sqlite3_initialize() ) return 0;
18500 #endif
18501 return sqlite3Malloc(n);
18505 ** Each thread may only have a single outstanding allocation from
18506 ** xScratchMalloc(). We verify this constraint in the single-threaded
18507 ** case by setting scratchAllocOut to 1 when an allocation
18508 ** is outstanding clearing it when the allocation is freed.
18510 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
18511 static int scratchAllocOut = 0;
18512 #endif
18516 ** Allocate memory that is to be used and released right away.
18517 ** This routine is similar to alloca() in that it is not intended
18518 ** for situations where the memory might be held long-term. This
18519 ** routine is intended to get memory to old large transient data
18520 ** structures that would not normally fit on the stack of an
18521 ** embedded processor.
18523 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
18524 void *p;
18525 assert( n>0 );
18527 sqlite3_mutex_enter(mem0.mutex);
18528 if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
18529 p = mem0.pScratchFree;
18530 mem0.pScratchFree = mem0.pScratchFree->pNext;
18531 mem0.nScratchFree--;
18532 sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
18533 sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
18534 sqlite3_mutex_leave(mem0.mutex);
18535 }else{
18536 if( sqlite3GlobalConfig.bMemstat ){
18537 sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
18538 n = mallocWithAlarm(n, &p);
18539 if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
18540 sqlite3_mutex_leave(mem0.mutex);
18541 }else{
18542 sqlite3_mutex_leave(mem0.mutex);
18543 p = sqlite3GlobalConfig.m.xMalloc(n);
18545 sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
18547 assert( sqlite3_mutex_notheld(mem0.mutex) );
18550 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
18551 /* Verify that no more than two scratch allocations per thread
18552 ** are outstanding at one time. (This is only checked in the
18553 ** single-threaded case since checking in the multi-threaded case
18554 ** would be much more complicated.) */
18555 assert( scratchAllocOut<=1 );
18556 if( p ) scratchAllocOut++;
18557 #endif
18559 return p;
18561 SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
18562 if( p ){
18564 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
18565 /* Verify that no more than two scratch allocation per thread
18566 ** is outstanding at one time. (This is only checked in the
18567 ** single-threaded case since checking in the multi-threaded case
18568 ** would be much more complicated.) */
18569 assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
18570 scratchAllocOut--;
18571 #endif
18573 if( p>=sqlite3GlobalConfig.pScratch && p<mem0.pScratchEnd ){
18574 /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
18575 ScratchFreeslot *pSlot;
18576 pSlot = (ScratchFreeslot*)p;
18577 sqlite3_mutex_enter(mem0.mutex);
18578 pSlot->pNext = mem0.pScratchFree;
18579 mem0.pScratchFree = pSlot;
18580 mem0.nScratchFree++;
18581 assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
18582 sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
18583 sqlite3_mutex_leave(mem0.mutex);
18584 }else{
18585 /* Release memory back to the heap */
18586 assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
18587 assert( sqlite3MemdebugNoType(p, ~MEMTYPE_SCRATCH) );
18588 sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
18589 if( sqlite3GlobalConfig.bMemstat ){
18590 int iSize = sqlite3MallocSize(p);
18591 sqlite3_mutex_enter(mem0.mutex);
18592 sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
18593 sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
18594 sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
18595 sqlite3GlobalConfig.m.xFree(p);
18596 sqlite3_mutex_leave(mem0.mutex);
18597 }else{
18598 sqlite3GlobalConfig.m.xFree(p);
18605 ** TRUE if p is a lookaside memory allocation from db
18607 #ifndef SQLITE_OMIT_LOOKASIDE
18608 static int isLookaside(sqlite3 *db, void *p){
18609 return p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;
18611 #else
18612 #define isLookaside(A,B) 0
18613 #endif
18616 ** Return the size of a memory allocation previously obtained from
18617 ** sqlite3Malloc() or sqlite3_malloc().
18619 SQLITE_PRIVATE int sqlite3MallocSize(void *p){
18620 assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
18621 assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
18622 return sqlite3GlobalConfig.m.xSize(p);
18624 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
18625 assert( db==0 || sqlite3_mutex_held(db->mutex) );
18626 if( db && isLookaside(db, p) ){
18627 return db->lookaside.sz;
18628 }else{
18629 assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
18630 assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
18631 assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
18632 return sqlite3GlobalConfig.m.xSize(p);
18637 ** Free memory previously obtained from sqlite3Malloc().
18639 SQLITE_API void sqlite3_free(void *p){
18640 if( p==0 ) return; /* IMP: R-49053-54554 */
18641 assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
18642 assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
18643 if( sqlite3GlobalConfig.bMemstat ){
18644 sqlite3_mutex_enter(mem0.mutex);
18645 sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
18646 sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
18647 sqlite3GlobalConfig.m.xFree(p);
18648 sqlite3_mutex_leave(mem0.mutex);
18649 }else{
18650 sqlite3GlobalConfig.m.xFree(p);
18655 ** Free memory that might be associated with a particular database
18656 ** connection.
18658 SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
18659 assert( db==0 || sqlite3_mutex_held(db->mutex) );
18660 if( db ){
18661 if( db->pnBytesFreed ){
18662 *db->pnBytesFreed += sqlite3DbMallocSize(db, p);
18663 return;
18665 if( isLookaside(db, p) ){
18666 LookasideSlot *pBuf = (LookasideSlot*)p;
18667 pBuf->pNext = db->lookaside.pFree;
18668 db->lookaside.pFree = pBuf;
18669 db->lookaside.nOut--;
18670 return;
18673 assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
18674 assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
18675 assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
18676 sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
18677 sqlite3_free(p);
18681 ** Change the size of an existing memory allocation
18683 SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
18684 int nOld, nNew, nDiff;
18685 void *pNew;
18686 if( pOld==0 ){
18687 return sqlite3Malloc(nBytes); /* IMP: R-28354-25769 */
18689 if( nBytes<=0 ){
18690 sqlite3_free(pOld); /* IMP: R-31593-10574 */
18691 return 0;
18693 if( nBytes>=0x7fffff00 ){
18694 /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
18695 return 0;
18697 nOld = sqlite3MallocSize(pOld);
18698 /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
18699 ** argument to xRealloc is always a value returned by a prior call to
18700 ** xRoundup. */
18701 nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
18702 if( nOld==nNew ){
18703 pNew = pOld;
18704 }else if( sqlite3GlobalConfig.bMemstat ){
18705 sqlite3_mutex_enter(mem0.mutex);
18706 sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
18707 nDiff = nNew - nOld;
18708 if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >=
18709 mem0.alarmThreshold-nDiff ){
18710 sqlite3MallocAlarm(nDiff);
18712 assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
18713 assert( sqlite3MemdebugNoType(pOld, ~MEMTYPE_HEAP) );
18714 pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
18715 if( pNew==0 && mem0.alarmCallback ){
18716 sqlite3MallocAlarm(nBytes);
18717 pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
18719 if( pNew ){
18720 nNew = sqlite3MallocSize(pNew);
18721 sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
18723 sqlite3_mutex_leave(mem0.mutex);
18724 }else{
18725 pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
18727 assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-04675-44850 */
18728 return pNew;
18732 ** The public interface to sqlite3Realloc. Make sure that the memory
18733 ** subsystem is initialized prior to invoking sqliteRealloc.
18735 SQLITE_API void *sqlite3_realloc(void *pOld, int n){
18736 #ifndef SQLITE_OMIT_AUTOINIT
18737 if( sqlite3_initialize() ) return 0;
18738 #endif
18739 return sqlite3Realloc(pOld, n);
18744 ** Allocate and zero memory.
18746 SQLITE_PRIVATE void *sqlite3MallocZero(int n){
18747 void *p = sqlite3Malloc(n);
18748 if( p ){
18749 memset(p, 0, n);
18751 return p;
18755 ** Allocate and zero memory. If the allocation fails, make
18756 ** the mallocFailed flag in the connection pointer.
18758 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, int n){
18759 void *p = sqlite3DbMallocRaw(db, n);
18760 if( p ){
18761 memset(p, 0, n);
18763 return p;
18767 ** Allocate and zero memory. If the allocation fails, make
18768 ** the mallocFailed flag in the connection pointer.
18770 ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
18771 ** failure on the same database connection) then always return 0.
18772 ** Hence for a particular database connection, once malloc starts
18773 ** failing, it fails consistently until mallocFailed is reset.
18774 ** This is an important assumption. There are many places in the
18775 ** code that do things like this:
18777 ** int *a = (int*)sqlite3DbMallocRaw(db, 100);
18778 ** int *b = (int*)sqlite3DbMallocRaw(db, 200);
18779 ** if( b ) a[10] = 9;
18781 ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
18782 ** that all prior mallocs (ex: "a") worked too.
18784 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, int n){
18785 void *p;
18786 assert( db==0 || sqlite3_mutex_held(db->mutex) );
18787 assert( db==0 || db->pnBytesFreed==0 );
18788 #ifndef SQLITE_OMIT_LOOKASIDE
18789 if( db ){
18790 LookasideSlot *pBuf;
18791 if( db->mallocFailed ){
18792 return 0;
18794 if( db->lookaside.bEnabled ){
18795 if( n>db->lookaside.sz ){
18796 db->lookaside.anStat[1]++;
18797 }else if( (pBuf = db->lookaside.pFree)==0 ){
18798 db->lookaside.anStat[2]++;
18799 }else{
18800 db->lookaside.pFree = pBuf->pNext;
18801 db->lookaside.nOut++;
18802 db->lookaside.anStat[0]++;
18803 if( db->lookaside.nOut>db->lookaside.mxOut ){
18804 db->lookaside.mxOut = db->lookaside.nOut;
18806 return (void*)pBuf;
18810 #else
18811 if( db && db->mallocFailed ){
18812 return 0;
18814 #endif
18815 p = sqlite3Malloc(n);
18816 if( !p && db ){
18817 db->mallocFailed = 1;
18819 sqlite3MemdebugSetType(p, MEMTYPE_DB |
18820 ((db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
18821 return p;
18825 ** Resize the block of memory pointed to by p to n bytes. If the
18826 ** resize fails, set the mallocFailed flag in the connection object.
18828 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
18829 void *pNew = 0;
18830 assert( db!=0 );
18831 assert( sqlite3_mutex_held(db->mutex) );
18832 if( db->mallocFailed==0 ){
18833 if( p==0 ){
18834 return sqlite3DbMallocRaw(db, n);
18836 if( isLookaside(db, p) ){
18837 if( n<=db->lookaside.sz ){
18838 return p;
18840 pNew = sqlite3DbMallocRaw(db, n);
18841 if( pNew ){
18842 memcpy(pNew, p, db->lookaside.sz);
18843 sqlite3DbFree(db, p);
18845 }else{
18846 assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
18847 assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
18848 sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
18849 pNew = sqlite3_realloc(p, n);
18850 if( !pNew ){
18851 sqlite3MemdebugSetType(p, MEMTYPE_DB|MEMTYPE_HEAP);
18852 db->mallocFailed = 1;
18854 sqlite3MemdebugSetType(pNew, MEMTYPE_DB |
18855 (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
18858 return pNew;
18862 ** Attempt to reallocate p. If the reallocation fails, then free p
18863 ** and set the mallocFailed flag in the database connection.
18865 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
18866 void *pNew;
18867 pNew = sqlite3DbRealloc(db, p, n);
18868 if( !pNew ){
18869 sqlite3DbFree(db, p);
18871 return pNew;
18875 ** Make a copy of a string in memory obtained from sqliteMalloc(). These
18876 ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
18877 ** is because when memory debugging is turned on, these two functions are
18878 ** called via macros that record the current file and line number in the
18879 ** ThreadData structure.
18881 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
18882 char *zNew;
18883 size_t n;
18884 if( z==0 ){
18885 return 0;
18887 n = sqlite3Strlen30(z) + 1;
18888 assert( (n&0x7fffffff)==n );
18889 zNew = sqlite3DbMallocRaw(db, (int)n);
18890 if( zNew ){
18891 memcpy(zNew, z, n);
18893 return zNew;
18895 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
18896 char *zNew;
18897 if( z==0 ){
18898 return 0;
18900 assert( (n&0x7fffffff)==n );
18901 zNew = sqlite3DbMallocRaw(db, n+1);
18902 if( zNew ){
18903 memcpy(zNew, z, n);
18904 zNew[n] = 0;
18906 return zNew;
18910 ** Create a string from the zFromat argument and the va_list that follows.
18911 ** Store the string in memory obtained from sqliteMalloc() and make *pz
18912 ** point to that string.
18914 SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
18915 va_list ap;
18916 char *z;
18918 va_start(ap, zFormat);
18919 z = sqlite3VMPrintf(db, zFormat, ap);
18920 va_end(ap);
18921 sqlite3DbFree(db, *pz);
18922 *pz = z;
18927 ** This function must be called before exiting any API function (i.e.
18928 ** returning control to the user) that has called sqlite3_malloc or
18929 ** sqlite3_realloc.
18931 ** The returned value is normally a copy of the second argument to this
18932 ** function. However, if a malloc() failure has occurred since the previous
18933 ** invocation SQLITE_NOMEM is returned instead.
18935 ** If the first argument, db, is not NULL and a malloc() error has occurred,
18936 ** then the connection error-code (the value returned by sqlite3_errcode())
18937 ** is set to SQLITE_NOMEM.
18939 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
18940 /* If the db handle is not NULL, then we must hold the connection handle
18941 ** mutex here. Otherwise the read (and possible write) of db->mallocFailed
18942 ** is unsafe, as is the call to sqlite3Error().
18944 assert( !db || sqlite3_mutex_held(db->mutex) );
18945 if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
18946 sqlite3Error(db, SQLITE_NOMEM, 0);
18947 db->mallocFailed = 0;
18948 rc = SQLITE_NOMEM;
18950 return rc & (db ? db->errMask : 0xff);
18953 /************** End of malloc.c **********************************************/
18954 /************** Begin file printf.c ******************************************/
18956 ** The "printf" code that follows dates from the 1980's. It is in
18957 ** the public domain. The original comments are included here for
18958 ** completeness. They are very out-of-date but might be useful as
18959 ** an historical reference. Most of the "enhancements" have been backed
18960 ** out so that the functionality is now the same as standard printf().
18962 **************************************************************************
18964 ** This file contains code for a set of "printf"-like routines. These
18965 ** routines format strings much like the printf() from the standard C
18966 ** library, though the implementation here has enhancements to support
18967 ** SQLlite.
18971 ** Conversion types fall into various categories as defined by the
18972 ** following enumeration.
18974 #define etRADIX 1 /* Integer types. %d, %x, %o, and so forth */
18975 #define etFLOAT 2 /* Floating point. %f */
18976 #define etEXP 3 /* Exponentional notation. %e and %E */
18977 #define etGENERIC 4 /* Floating or exponential, depending on exponent. %g */
18978 #define etSIZE 5 /* Return number of characters processed so far. %n */
18979 #define etSTRING 6 /* Strings. %s */
18980 #define etDYNSTRING 7 /* Dynamically allocated strings. %z */
18981 #define etPERCENT 8 /* Percent symbol. %% */
18982 #define etCHARX 9 /* Characters. %c */
18983 /* The rest are extensions, not normally found in printf() */
18984 #define etSQLESCAPE 10 /* Strings with '\'' doubled. %q */
18985 #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
18986 NULL pointers replaced by SQL NULL. %Q */
18987 #define etTOKEN 12 /* a pointer to a Token structure */
18988 #define etSRCLIST 13 /* a pointer to a SrcList */
18989 #define etPOINTER 14 /* The %p conversion */
18990 #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
18991 #define etORDINAL 16 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */
18993 #define etINVALID 0 /* Any unrecognized conversion type */
18997 ** An "etByte" is an 8-bit unsigned value.
18999 typedef unsigned char etByte;
19002 ** Each builtin conversion character (ex: the 'd' in "%d") is described
19003 ** by an instance of the following structure
19005 typedef struct et_info { /* Information about each format field */
19006 char fmttype; /* The format field code letter */
19007 etByte base; /* The base for radix conversion */
19008 etByte flags; /* One or more of FLAG_ constants below */
19009 etByte type; /* Conversion paradigm */
19010 etByte charset; /* Offset into aDigits[] of the digits string */
19011 etByte prefix; /* Offset into aPrefix[] of the prefix string */
19012 } et_info;
19015 ** Allowed values for et_info.flags
19017 #define FLAG_SIGNED 1 /* True if the value to convert is signed */
19018 #define FLAG_INTERN 2 /* True if for internal use only */
19019 #define FLAG_STRING 4 /* Allow infinity precision */
19023 ** The following table is searched linearly, so it is good to put the
19024 ** most frequently used conversion types first.
19026 static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
19027 static const char aPrefix[] = "-x0\000X0";
19028 static const et_info fmtinfo[] = {
19029 { 'd', 10, 1, etRADIX, 0, 0 },
19030 { 's', 0, 4, etSTRING, 0, 0 },
19031 { 'g', 0, 1, etGENERIC, 30, 0 },
19032 { 'z', 0, 4, etDYNSTRING, 0, 0 },
19033 { 'q', 0, 4, etSQLESCAPE, 0, 0 },
19034 { 'Q', 0, 4, etSQLESCAPE2, 0, 0 },
19035 { 'w', 0, 4, etSQLESCAPE3, 0, 0 },
19036 { 'c', 0, 0, etCHARX, 0, 0 },
19037 { 'o', 8, 0, etRADIX, 0, 2 },
19038 { 'u', 10, 0, etRADIX, 0, 0 },
19039 { 'x', 16, 0, etRADIX, 16, 1 },
19040 { 'X', 16, 0, etRADIX, 0, 4 },
19041 #ifndef SQLITE_OMIT_FLOATING_POINT
19042 { 'f', 0, 1, etFLOAT, 0, 0 },
19043 { 'e', 0, 1, etEXP, 30, 0 },
19044 { 'E', 0, 1, etEXP, 14, 0 },
19045 { 'G', 0, 1, etGENERIC, 14, 0 },
19046 #endif
19047 { 'i', 10, 1, etRADIX, 0, 0 },
19048 { 'n', 0, 0, etSIZE, 0, 0 },
19049 { '%', 0, 0, etPERCENT, 0, 0 },
19050 { 'p', 16, 0, etPOINTER, 0, 1 },
19052 /* All the rest have the FLAG_INTERN bit set and are thus for internal
19053 ** use only */
19054 { 'T', 0, 2, etTOKEN, 0, 0 },
19055 { 'S', 0, 2, etSRCLIST, 0, 0 },
19056 { 'r', 10, 3, etORDINAL, 0, 0 },
19060 ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
19061 ** conversions will work.
19063 #ifndef SQLITE_OMIT_FLOATING_POINT
19065 ** "*val" is a double such that 0.1 <= *val < 10.0
19066 ** Return the ascii code for the leading digit of *val, then
19067 ** multiply "*val" by 10.0 to renormalize.
19069 ** Example:
19070 ** input: *val = 3.14159
19071 ** output: *val = 1.4159 function return = '3'
19073 ** The counter *cnt is incremented each time. After counter exceeds
19074 ** 16 (the number of significant digits in a 64-bit float) '0' is
19075 ** always returned.
19077 static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
19078 int digit;
19079 LONGDOUBLE_TYPE d;
19080 if( (*cnt)++ >= 16 ) return '0';
19081 digit = (int)*val;
19082 d = digit;
19083 digit += '0';
19084 *val = (*val - d)*10.0;
19085 return (char)digit;
19087 #endif /* SQLITE_OMIT_FLOATING_POINT */
19090 ** Append N space characters to the given string buffer.
19092 static void appendSpace(StrAccum *pAccum, int N){
19093 static const char zSpaces[] = " ";
19094 while( N>=(int)sizeof(zSpaces)-1 ){
19095 sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
19096 N -= sizeof(zSpaces)-1;
19098 if( N>0 ){
19099 sqlite3StrAccumAppend(pAccum, zSpaces, N);
19104 ** On machines with a small stack size, you can redefine the
19105 ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
19107 #ifndef SQLITE_PRINT_BUF_SIZE
19108 # define SQLITE_PRINT_BUF_SIZE 70
19109 #endif
19110 #define etBUFSIZE SQLITE_PRINT_BUF_SIZE /* Size of the output buffer */
19113 ** Render a string given by "fmt" into the StrAccum object.
19115 SQLITE_PRIVATE void sqlite3VXPrintf(
19116 StrAccum *pAccum, /* Accumulate results here */
19117 int useExtended, /* Allow extended %-conversions */
19118 const char *fmt, /* Format string */
19119 va_list ap /* arguments */
19121 int c; /* Next character in the format string */
19122 char *bufpt; /* Pointer to the conversion buffer */
19123 int precision; /* Precision of the current field */
19124 int length; /* Length of the field */
19125 int idx; /* A general purpose loop counter */
19126 int width; /* Width of the current field */
19127 etByte flag_leftjustify; /* True if "-" flag is present */
19128 etByte flag_plussign; /* True if "+" flag is present */
19129 etByte flag_blanksign; /* True if " " flag is present */
19130 etByte flag_alternateform; /* True if "#" flag is present */
19131 etByte flag_altform2; /* True if "!" flag is present */
19132 etByte flag_zeropad; /* True if field width constant starts with zero */
19133 etByte flag_long; /* True if "l" flag is present */
19134 etByte flag_longlong; /* True if the "ll" flag is present */
19135 etByte done; /* Loop termination flag */
19136 etByte xtype = 0; /* Conversion paradigm */
19137 char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */
19138 sqlite_uint64 longvalue; /* Value for integer types */
19139 LONGDOUBLE_TYPE realvalue; /* Value for real types */
19140 const et_info *infop; /* Pointer to the appropriate info structure */
19141 char *zOut; /* Rendering buffer */
19142 int nOut; /* Size of the rendering buffer */
19143 char *zExtra; /* Malloced memory used by some conversion */
19144 #ifndef SQLITE_OMIT_FLOATING_POINT
19145 int exp, e2; /* exponent of real numbers */
19146 int nsd; /* Number of significant digits returned */
19147 double rounder; /* Used for rounding floating point values */
19148 etByte flag_dp; /* True if decimal point should be shown */
19149 etByte flag_rtz; /* True if trailing zeros should be removed */
19150 #endif
19151 char buf[etBUFSIZE]; /* Conversion buffer */
19153 bufpt = 0;
19154 for(; (c=(*fmt))!=0; ++fmt){
19155 if( c!='%' ){
19156 int amt;
19157 bufpt = (char *)fmt;
19158 amt = 1;
19159 while( (c=(*++fmt))!='%' && c!=0 ) amt++;
19160 sqlite3StrAccumAppend(pAccum, bufpt, amt);
19161 if( c==0 ) break;
19163 if( (c=(*++fmt))==0 ){
19164 sqlite3StrAccumAppend(pAccum, "%", 1);
19165 break;
19167 /* Find out what flags are present */
19168 flag_leftjustify = flag_plussign = flag_blanksign =
19169 flag_alternateform = flag_altform2 = flag_zeropad = 0;
19170 done = 0;
19172 switch( c ){
19173 case '-': flag_leftjustify = 1; break;
19174 case '+': flag_plussign = 1; break;
19175 case ' ': flag_blanksign = 1; break;
19176 case '#': flag_alternateform = 1; break;
19177 case '!': flag_altform2 = 1; break;
19178 case '0': flag_zeropad = 1; break;
19179 default: done = 1; break;
19181 }while( !done && (c=(*++fmt))!=0 );
19182 /* Get the field width */
19183 width = 0;
19184 if( c=='*' ){
19185 width = va_arg(ap,int);
19186 if( width<0 ){
19187 flag_leftjustify = 1;
19188 width = -width;
19190 c = *++fmt;
19191 }else{
19192 while( c>='0' && c<='9' ){
19193 width = width*10 + c - '0';
19194 c = *++fmt;
19197 /* Get the precision */
19198 if( c=='.' ){
19199 precision = 0;
19200 c = *++fmt;
19201 if( c=='*' ){
19202 precision = va_arg(ap,int);
19203 if( precision<0 ) precision = -precision;
19204 c = *++fmt;
19205 }else{
19206 while( c>='0' && c<='9' ){
19207 precision = precision*10 + c - '0';
19208 c = *++fmt;
19211 }else{
19212 precision = -1;
19214 /* Get the conversion type modifier */
19215 if( c=='l' ){
19216 flag_long = 1;
19217 c = *++fmt;
19218 if( c=='l' ){
19219 flag_longlong = 1;
19220 c = *++fmt;
19221 }else{
19222 flag_longlong = 0;
19224 }else{
19225 flag_long = flag_longlong = 0;
19227 /* Fetch the info entry for the field */
19228 infop = &fmtinfo[0];
19229 xtype = etINVALID;
19230 for(idx=0; idx<ArraySize(fmtinfo); idx++){
19231 if( c==fmtinfo[idx].fmttype ){
19232 infop = &fmtinfo[idx];
19233 if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
19234 xtype = infop->type;
19235 }else{
19236 return;
19238 break;
19241 zExtra = 0;
19244 ** At this point, variables are initialized as follows:
19246 ** flag_alternateform TRUE if a '#' is present.
19247 ** flag_altform2 TRUE if a '!' is present.
19248 ** flag_plussign TRUE if a '+' is present.
19249 ** flag_leftjustify TRUE if a '-' is present or if the
19250 ** field width was negative.
19251 ** flag_zeropad TRUE if the width began with 0.
19252 ** flag_long TRUE if the letter 'l' (ell) prefixed
19253 ** the conversion character.
19254 ** flag_longlong TRUE if the letter 'll' (ell ell) prefixed
19255 ** the conversion character.
19256 ** flag_blanksign TRUE if a ' ' is present.
19257 ** width The specified field width. This is
19258 ** always non-negative. Zero is the default.
19259 ** precision The specified precision. The default
19260 ** is -1.
19261 ** xtype The class of the conversion.
19262 ** infop Pointer to the appropriate info struct.
19264 switch( xtype ){
19265 case etPOINTER:
19266 flag_longlong = sizeof(char*)==sizeof(i64);
19267 flag_long = sizeof(char*)==sizeof(long int);
19268 /* Fall through into the next case */
19269 case etORDINAL:
19270 case etRADIX:
19271 if( infop->flags & FLAG_SIGNED ){
19272 i64 v;
19273 if( flag_longlong ){
19274 v = va_arg(ap,i64);
19275 }else if( flag_long ){
19276 v = va_arg(ap,long int);
19277 }else{
19278 v = va_arg(ap,int);
19280 if( v<0 ){
19281 if( v==SMALLEST_INT64 ){
19282 longvalue = ((u64)1)<<63;
19283 }else{
19284 longvalue = -v;
19286 prefix = '-';
19287 }else{
19288 longvalue = v;
19289 if( flag_plussign ) prefix = '+';
19290 else if( flag_blanksign ) prefix = ' ';
19291 else prefix = 0;
19293 }else{
19294 if( flag_longlong ){
19295 longvalue = va_arg(ap,u64);
19296 }else if( flag_long ){
19297 longvalue = va_arg(ap,unsigned long int);
19298 }else{
19299 longvalue = va_arg(ap,unsigned int);
19301 prefix = 0;
19303 if( longvalue==0 ) flag_alternateform = 0;
19304 if( flag_zeropad && precision<width-(prefix!=0) ){
19305 precision = width-(prefix!=0);
19307 if( precision<etBUFSIZE-10 ){
19308 nOut = etBUFSIZE;
19309 zOut = buf;
19310 }else{
19311 nOut = precision + 10;
19312 zOut = zExtra = sqlite3Malloc( nOut );
19313 if( zOut==0 ){
19314 pAccum->mallocFailed = 1;
19315 return;
19318 bufpt = &zOut[nOut-1];
19319 if( xtype==etORDINAL ){
19320 static const char zOrd[] = "thstndrd";
19321 int x = (int)(longvalue % 10);
19322 if( x>=4 || (longvalue/10)%10==1 ){
19323 x = 0;
19325 *(--bufpt) = zOrd[x*2+1];
19326 *(--bufpt) = zOrd[x*2];
19329 register const char *cset; /* Use registers for speed */
19330 register int base;
19331 cset = &aDigits[infop->charset];
19332 base = infop->base;
19333 do{ /* Convert to ascii */
19334 *(--bufpt) = cset[longvalue%base];
19335 longvalue = longvalue/base;
19336 }while( longvalue>0 );
19338 length = (int)(&zOut[nOut-1]-bufpt);
19339 for(idx=precision-length; idx>0; idx--){
19340 *(--bufpt) = '0'; /* Zero pad */
19342 if( prefix ) *(--bufpt) = prefix; /* Add sign */
19343 if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */
19344 const char *pre;
19345 char x;
19346 pre = &aPrefix[infop->prefix];
19347 for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
19349 length = (int)(&zOut[nOut-1]-bufpt);
19350 break;
19351 case etFLOAT:
19352 case etEXP:
19353 case etGENERIC:
19354 realvalue = va_arg(ap,double);
19355 #ifdef SQLITE_OMIT_FLOATING_POINT
19356 length = 0;
19357 #else
19358 if( precision<0 ) precision = 6; /* Set default precision */
19359 if( realvalue<0.0 ){
19360 realvalue = -realvalue;
19361 prefix = '-';
19362 }else{
19363 if( flag_plussign ) prefix = '+';
19364 else if( flag_blanksign ) prefix = ' ';
19365 else prefix = 0;
19367 if( xtype==etGENERIC && precision>0 ) precision--;
19368 #if 0
19369 /* Rounding works like BSD when the constant 0.4999 is used. Wierd! */
19370 for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
19371 #else
19372 /* It makes more sense to use 0.5 */
19373 for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
19374 #endif
19375 if( xtype==etFLOAT ) realvalue += rounder;
19376 /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
19377 exp = 0;
19378 if( sqlite3IsNaN((double)realvalue) ){
19379 bufpt = "NaN";
19380 length = 3;
19381 break;
19383 if( realvalue>0.0 ){
19384 while( realvalue>=1e32 && exp<=350 ){ realvalue *= 1e-32; exp+=32; }
19385 while( realvalue>=1e8 && exp<=350 ){ realvalue *= 1e-8; exp+=8; }
19386 while( realvalue>=10.0 && exp<=350 ){ realvalue *= 0.1; exp++; }
19387 while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
19388 while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
19389 if( exp>350 ){
19390 if( prefix=='-' ){
19391 bufpt = "-Inf";
19392 }else if( prefix=='+' ){
19393 bufpt = "+Inf";
19394 }else{
19395 bufpt = "Inf";
19397 length = sqlite3Strlen30(bufpt);
19398 break;
19401 bufpt = buf;
19403 ** If the field type is etGENERIC, then convert to either etEXP
19404 ** or etFLOAT, as appropriate.
19406 if( xtype!=etFLOAT ){
19407 realvalue += rounder;
19408 if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
19410 if( xtype==etGENERIC ){
19411 flag_rtz = !flag_alternateform;
19412 if( exp<-4 || exp>precision ){
19413 xtype = etEXP;
19414 }else{
19415 precision = precision - exp;
19416 xtype = etFLOAT;
19418 }else{
19419 flag_rtz = 0;
19421 if( xtype==etEXP ){
19422 e2 = 0;
19423 }else{
19424 e2 = exp;
19426 if( e2+precision+width > etBUFSIZE - 15 ){
19427 bufpt = zExtra = sqlite3Malloc( e2+precision+width+15 );
19428 if( bufpt==0 ){
19429 pAccum->mallocFailed = 1;
19430 return;
19433 zOut = bufpt;
19434 nsd = 0;
19435 flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
19436 /* The sign in front of the number */
19437 if( prefix ){
19438 *(bufpt++) = prefix;
19440 /* Digits prior to the decimal point */
19441 if( e2<0 ){
19442 *(bufpt++) = '0';
19443 }else{
19444 for(; e2>=0; e2--){
19445 *(bufpt++) = et_getdigit(&realvalue,&nsd);
19448 /* The decimal point */
19449 if( flag_dp ){
19450 *(bufpt++) = '.';
19452 /* "0" digits after the decimal point but before the first
19453 ** significant digit of the number */
19454 for(e2++; e2<0; precision--, e2++){
19455 assert( precision>0 );
19456 *(bufpt++) = '0';
19458 /* Significant digits after the decimal point */
19459 while( (precision--)>0 ){
19460 *(bufpt++) = et_getdigit(&realvalue,&nsd);
19462 /* Remove trailing zeros and the "." if no digits follow the "." */
19463 if( flag_rtz && flag_dp ){
19464 while( bufpt[-1]=='0' ) *(--bufpt) = 0;
19465 assert( bufpt>zOut );
19466 if( bufpt[-1]=='.' ){
19467 if( flag_altform2 ){
19468 *(bufpt++) = '0';
19469 }else{
19470 *(--bufpt) = 0;
19474 /* Add the "eNNN" suffix */
19475 if( xtype==etEXP ){
19476 *(bufpt++) = aDigits[infop->charset];
19477 if( exp<0 ){
19478 *(bufpt++) = '-'; exp = -exp;
19479 }else{
19480 *(bufpt++) = '+';
19482 if( exp>=100 ){
19483 *(bufpt++) = (char)((exp/100)+'0'); /* 100's digit */
19484 exp %= 100;
19486 *(bufpt++) = (char)(exp/10+'0'); /* 10's digit */
19487 *(bufpt++) = (char)(exp%10+'0'); /* 1's digit */
19489 *bufpt = 0;
19491 /* The converted number is in buf[] and zero terminated. Output it.
19492 ** Note that the number is in the usual order, not reversed as with
19493 ** integer conversions. */
19494 length = (int)(bufpt-zOut);
19495 bufpt = zOut;
19497 /* Special case: Add leading zeros if the flag_zeropad flag is
19498 ** set and we are not left justified */
19499 if( flag_zeropad && !flag_leftjustify && length < width){
19500 int i;
19501 int nPad = width - length;
19502 for(i=width; i>=nPad; i--){
19503 bufpt[i] = bufpt[i-nPad];
19505 i = prefix!=0;
19506 while( nPad-- ) bufpt[i++] = '0';
19507 length = width;
19509 #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
19510 break;
19511 case etSIZE:
19512 *(va_arg(ap,int*)) = pAccum->nChar;
19513 length = width = 0;
19514 break;
19515 case etPERCENT:
19516 buf[0] = '%';
19517 bufpt = buf;
19518 length = 1;
19519 break;
19520 case etCHARX:
19521 c = va_arg(ap,int);
19522 buf[0] = (char)c;
19523 if( precision>=0 ){
19524 for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
19525 length = precision;
19526 }else{
19527 length =1;
19529 bufpt = buf;
19530 break;
19531 case etSTRING:
19532 case etDYNSTRING:
19533 bufpt = va_arg(ap,char*);
19534 if( bufpt==0 ){
19535 bufpt = "";
19536 }else if( xtype==etDYNSTRING ){
19537 zExtra = bufpt;
19539 if( precision>=0 ){
19540 for(length=0; length<precision && bufpt[length]; length++){}
19541 }else{
19542 length = sqlite3Strlen30(bufpt);
19544 break;
19545 case etSQLESCAPE:
19546 case etSQLESCAPE2:
19547 case etSQLESCAPE3: {
19548 int i, j, k, n, isnull;
19549 int needQuote;
19550 char ch;
19551 char q = ((xtype==etSQLESCAPE3)?'"':'\''); /* Quote character */
19552 char *escarg = va_arg(ap,char*);
19553 isnull = escarg==0;
19554 if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
19555 k = precision;
19556 for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
19557 if( ch==q ) n++;
19559 needQuote = !isnull && xtype==etSQLESCAPE2;
19560 n += i + 1 + needQuote*2;
19561 if( n>etBUFSIZE ){
19562 bufpt = zExtra = sqlite3Malloc( n );
19563 if( bufpt==0 ){
19564 pAccum->mallocFailed = 1;
19565 return;
19567 }else{
19568 bufpt = buf;
19570 j = 0;
19571 if( needQuote ) bufpt[j++] = q;
19572 k = i;
19573 for(i=0; i<k; i++){
19574 bufpt[j++] = ch = escarg[i];
19575 if( ch==q ) bufpt[j++] = ch;
19577 if( needQuote ) bufpt[j++] = q;
19578 bufpt[j] = 0;
19579 length = j;
19580 /* The precision in %q and %Q means how many input characters to
19581 ** consume, not the length of the output...
19582 ** if( precision>=0 && precision<length ) length = precision; */
19583 break;
19585 case etTOKEN: {
19586 Token *pToken = va_arg(ap, Token*);
19587 if( pToken ){
19588 sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
19590 length = width = 0;
19591 break;
19593 case etSRCLIST: {
19594 SrcList *pSrc = va_arg(ap, SrcList*);
19595 int k = va_arg(ap, int);
19596 struct SrcList_item *pItem = &pSrc->a[k];
19597 assert( k>=0 && k<pSrc->nSrc );
19598 if( pItem->zDatabase ){
19599 sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);
19600 sqlite3StrAccumAppend(pAccum, ".", 1);
19602 sqlite3StrAccumAppend(pAccum, pItem->zName, -1);
19603 length = width = 0;
19604 break;
19606 default: {
19607 assert( xtype==etINVALID );
19608 return;
19610 }/* End switch over the format type */
19612 ** The text of the conversion is pointed to by "bufpt" and is
19613 ** "length" characters long. The field width is "width". Do
19614 ** the output.
19616 if( !flag_leftjustify ){
19617 register int nspace;
19618 nspace = width-length;
19619 if( nspace>0 ){
19620 appendSpace(pAccum, nspace);
19623 if( length>0 ){
19624 sqlite3StrAccumAppend(pAccum, bufpt, length);
19626 if( flag_leftjustify ){
19627 register int nspace;
19628 nspace = width-length;
19629 if( nspace>0 ){
19630 appendSpace(pAccum, nspace);
19633 sqlite3_free(zExtra);
19634 }/* End for loop over the format string */
19635 } /* End of function */
19638 ** Append N bytes of text from z to the StrAccum object.
19640 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
19641 assert( z!=0 || N==0 );
19642 if( p->tooBig | p->mallocFailed ){
19643 testcase(p->tooBig);
19644 testcase(p->mallocFailed);
19645 return;
19647 assert( p->zText!=0 || p->nChar==0 );
19648 if( N<0 ){
19649 N = sqlite3Strlen30(z);
19651 if( N==0 || NEVER(z==0) ){
19652 return;
19654 if( p->nChar+N >= p->nAlloc ){
19655 char *zNew;
19656 if( !p->useMalloc ){
19657 p->tooBig = 1;
19658 N = p->nAlloc - p->nChar - 1;
19659 if( N<=0 ){
19660 return;
19662 }else{
19663 char *zOld = (p->zText==p->zBase ? 0 : p->zText);
19664 i64 szNew = p->nChar;
19665 szNew += N + 1;
19666 if( szNew > p->mxAlloc ){
19667 sqlite3StrAccumReset(p);
19668 p->tooBig = 1;
19669 return;
19670 }else{
19671 p->nAlloc = (int)szNew;
19673 if( p->useMalloc==1 ){
19674 zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
19675 }else{
19676 zNew = sqlite3_realloc(zOld, p->nAlloc);
19678 if( zNew ){
19679 if( zOld==0 && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
19680 p->zText = zNew;
19681 }else{
19682 p->mallocFailed = 1;
19683 sqlite3StrAccumReset(p);
19684 return;
19688 assert( p->zText );
19689 memcpy(&p->zText[p->nChar], z, N);
19690 p->nChar += N;
19694 ** Finish off a string by making sure it is zero-terminated.
19695 ** Return a pointer to the resulting string. Return a NULL
19696 ** pointer if any kind of error was encountered.
19698 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
19699 if( p->zText ){
19700 p->zText[p->nChar] = 0;
19701 if( p->useMalloc && p->zText==p->zBase ){
19702 if( p->useMalloc==1 ){
19703 p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
19704 }else{
19705 p->zText = sqlite3_malloc(p->nChar+1);
19707 if( p->zText ){
19708 memcpy(p->zText, p->zBase, p->nChar+1);
19709 }else{
19710 p->mallocFailed = 1;
19714 return p->zText;
19718 ** Reset an StrAccum string. Reclaim all malloced memory.
19720 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
19721 if( p->zText!=p->zBase ){
19722 if( p->useMalloc==1 ){
19723 sqlite3DbFree(p->db, p->zText);
19724 }else{
19725 sqlite3_free(p->zText);
19728 p->zText = 0;
19732 ** Initialize a string accumulator
19734 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
19735 p->zText = p->zBase = zBase;
19736 p->db = 0;
19737 p->nChar = 0;
19738 p->nAlloc = n;
19739 p->mxAlloc = mx;
19740 p->useMalloc = 1;
19741 p->tooBig = 0;
19742 p->mallocFailed = 0;
19746 ** Print into memory obtained from sqliteMalloc(). Use the internal
19747 ** %-conversion extensions.
19749 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
19750 char *z;
19751 char zBase[SQLITE_PRINT_BUF_SIZE];
19752 StrAccum acc;
19753 assert( db!=0 );
19754 sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
19755 db->aLimit[SQLITE_LIMIT_LENGTH]);
19756 acc.db = db;
19757 sqlite3VXPrintf(&acc, 1, zFormat, ap);
19758 z = sqlite3StrAccumFinish(&acc);
19759 if( acc.mallocFailed ){
19760 db->mallocFailed = 1;
19762 return z;
19766 ** Print into memory obtained from sqliteMalloc(). Use the internal
19767 ** %-conversion extensions.
19769 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
19770 va_list ap;
19771 char *z;
19772 va_start(ap, zFormat);
19773 z = sqlite3VMPrintf(db, zFormat, ap);
19774 va_end(ap);
19775 return z;
19779 ** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
19780 ** the string and before returnning. This routine is intended to be used
19781 ** to modify an existing string. For example:
19783 ** x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
19786 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
19787 va_list ap;
19788 char *z;
19789 va_start(ap, zFormat);
19790 z = sqlite3VMPrintf(db, zFormat, ap);
19791 va_end(ap);
19792 sqlite3DbFree(db, zStr);
19793 return z;
19797 ** Print into memory obtained from sqlite3_malloc(). Omit the internal
19798 ** %-conversion extensions.
19800 SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
19801 char *z;
19802 char zBase[SQLITE_PRINT_BUF_SIZE];
19803 StrAccum acc;
19804 #ifndef SQLITE_OMIT_AUTOINIT
19805 if( sqlite3_initialize() ) return 0;
19806 #endif
19807 sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
19808 acc.useMalloc = 2;
19809 sqlite3VXPrintf(&acc, 0, zFormat, ap);
19810 z = sqlite3StrAccumFinish(&acc);
19811 return z;
19815 ** Print into memory obtained from sqlite3_malloc()(). Omit the internal
19816 ** %-conversion extensions.
19818 SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
19819 va_list ap;
19820 char *z;
19821 #ifndef SQLITE_OMIT_AUTOINIT
19822 if( sqlite3_initialize() ) return 0;
19823 #endif
19824 va_start(ap, zFormat);
19825 z = sqlite3_vmprintf(zFormat, ap);
19826 va_end(ap);
19827 return z;
19831 ** sqlite3_snprintf() works like snprintf() except that it ignores the
19832 ** current locale settings. This is important for SQLite because we
19833 ** are not able to use a "," as the decimal point in place of "." as
19834 ** specified by some locales.
19836 ** Oops: The first two arguments of sqlite3_snprintf() are backwards
19837 ** from the snprintf() standard. Unfortunately, it is too late to change
19838 ** this without breaking compatibility, so we just have to live with the
19839 ** mistake.
19841 ** sqlite3_vsnprintf() is the varargs version.
19843 SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
19844 StrAccum acc;
19845 if( n<=0 ) return zBuf;
19846 sqlite3StrAccumInit(&acc, zBuf, n, 0);
19847 acc.useMalloc = 0;
19848 sqlite3VXPrintf(&acc, 0, zFormat, ap);
19849 return sqlite3StrAccumFinish(&acc);
19851 SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
19852 char *z;
19853 va_list ap;
19854 va_start(ap,zFormat);
19855 z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
19856 va_end(ap);
19857 return z;
19861 ** This is the routine that actually formats the sqlite3_log() message.
19862 ** We house it in a separate routine from sqlite3_log() to avoid using
19863 ** stack space on small-stack systems when logging is disabled.
19865 ** sqlite3_log() must render into a static buffer. It cannot dynamically
19866 ** allocate memory because it might be called while the memory allocator
19867 ** mutex is held.
19869 static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
19870 StrAccum acc; /* String accumulator */
19871 char zMsg[SQLITE_PRINT_BUF_SIZE*3]; /* Complete log message */
19873 sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
19874 acc.useMalloc = 0;
19875 sqlite3VXPrintf(&acc, 0, zFormat, ap);
19876 sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
19877 sqlite3StrAccumFinish(&acc));
19881 ** Format and write a message to the log if logging is enabled.
19883 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
19884 va_list ap; /* Vararg list */
19885 if( sqlite3GlobalConfig.xLog ){
19886 va_start(ap, zFormat);
19887 renderLogMsg(iErrCode, zFormat, ap);
19888 va_end(ap);
19892 #if defined(SQLITE_DEBUG)
19894 ** A version of printf() that understands %lld. Used for debugging.
19895 ** The printf() built into some versions of windows does not understand %lld
19896 ** and segfaults if you give it a long long int.
19898 SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
19899 va_list ap;
19900 StrAccum acc;
19901 char zBuf[500];
19902 sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
19903 acc.useMalloc = 0;
19904 va_start(ap,zFormat);
19905 sqlite3VXPrintf(&acc, 0, zFormat, ap);
19906 va_end(ap);
19907 sqlite3StrAccumFinish(&acc);
19908 fprintf(stdout,"%s", zBuf);
19909 fflush(stdout);
19911 #endif
19913 #ifndef SQLITE_OMIT_TRACE
19915 ** variable-argument wrapper around sqlite3VXPrintf().
19917 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
19918 va_list ap;
19919 va_start(ap,zFormat);
19920 sqlite3VXPrintf(p, 1, zFormat, ap);
19921 va_end(ap);
19923 #endif
19925 /************** End of printf.c **********************************************/
19926 /************** Begin file random.c ******************************************/
19928 ** 2001 September 15
19930 ** The author disclaims copyright to this source code. In place of
19931 ** a legal notice, here is a blessing:
19933 ** May you do good and not evil.
19934 ** May you find forgiveness for yourself and forgive others.
19935 ** May you share freely, never taking more than you give.
19937 *************************************************************************
19938 ** This file contains code to implement a pseudo-random number
19939 ** generator (PRNG) for SQLite.
19941 ** Random numbers are used by some of the database backends in order
19942 ** to generate random integer keys for tables or random filenames.
19946 /* All threads share a single random number generator.
19947 ** This structure is the current state of the generator.
19949 static SQLITE_WSD struct sqlite3PrngType {
19950 unsigned char isInit; /* True if initialized */
19951 unsigned char i, j; /* State variables */
19952 unsigned char s[256]; /* State variables */
19953 } sqlite3Prng;
19956 ** Get a single 8-bit random value from the RC4 PRNG. The Mutex
19957 ** must be held while executing this routine.
19959 ** Why not just use a library random generator like lrand48() for this?
19960 ** Because the OP_NewRowid opcode in the VDBE depends on having a very
19961 ** good source of random numbers. The lrand48() library function may
19962 ** well be good enough. But maybe not. Or maybe lrand48() has some
19963 ** subtle problems on some systems that could cause problems. It is hard
19964 ** to know. To minimize the risk of problems due to bad lrand48()
19965 ** implementations, SQLite uses this random number generator based
19966 ** on RC4, which we know works very well.
19968 ** (Later): Actually, OP_NewRowid does not depend on a good source of
19969 ** randomness any more. But we will leave this code in all the same.
19971 static u8 randomByte(void){
19972 unsigned char t;
19975 /* The "wsdPrng" macro will resolve to the pseudo-random number generator
19976 ** state vector. If writable static data is unsupported on the target,
19977 ** we have to locate the state vector at run-time. In the more common
19978 ** case where writable static data is supported, wsdPrng can refer directly
19979 ** to the "sqlite3Prng" state vector declared above.
19981 #ifdef SQLITE_OMIT_WSD
19982 struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
19983 # define wsdPrng p[0]
19984 #else
19985 # define wsdPrng sqlite3Prng
19986 #endif
19989 /* Initialize the state of the random number generator once,
19990 ** the first time this routine is called. The seed value does
19991 ** not need to contain a lot of randomness since we are not
19992 ** trying to do secure encryption or anything like that...
19994 ** Nothing in this file or anywhere else in SQLite does any kind of
19995 ** encryption. The RC4 algorithm is being used as a PRNG (pseudo-random
19996 ** number generator) not as an encryption device.
19998 if( !wsdPrng.isInit ){
19999 int i;
20000 char k[256];
20001 wsdPrng.j = 0;
20002 wsdPrng.i = 0;
20003 sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
20004 for(i=0; i<256; i++){
20005 wsdPrng.s[i] = (u8)i;
20007 for(i=0; i<256; i++){
20008 wsdPrng.j += wsdPrng.s[i] + k[i];
20009 t = wsdPrng.s[wsdPrng.j];
20010 wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
20011 wsdPrng.s[i] = t;
20013 wsdPrng.isInit = 1;
20016 /* Generate and return single random byte
20018 wsdPrng.i++;
20019 t = wsdPrng.s[wsdPrng.i];
20020 wsdPrng.j += t;
20021 wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
20022 wsdPrng.s[wsdPrng.j] = t;
20023 t += wsdPrng.s[wsdPrng.i];
20024 return wsdPrng.s[t];
20028 ** Return N random bytes.
20030 SQLITE_API void sqlite3_randomness(int N, void *pBuf){
20031 unsigned char *zBuf = pBuf;
20032 #if SQLITE_THREADSAFE
20033 sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
20034 #endif
20035 sqlite3_mutex_enter(mutex);
20036 while( N-- ){
20037 *(zBuf++) = randomByte();
20039 sqlite3_mutex_leave(mutex);
20042 #ifndef SQLITE_OMIT_BUILTIN_TEST
20044 ** For testing purposes, we sometimes want to preserve the state of
20045 ** PRNG and restore the PRNG to its saved state at a later time, or
20046 ** to reset the PRNG to its initial state. These routines accomplish
20047 ** those tasks.
20049 ** The sqlite3_test_control() interface calls these routines to
20050 ** control the PRNG.
20052 static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
20053 SQLITE_PRIVATE void sqlite3PrngSaveState(void){
20054 memcpy(
20055 &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
20056 &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
20057 sizeof(sqlite3Prng)
20060 SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
20061 memcpy(
20062 &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
20063 &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
20064 sizeof(sqlite3Prng)
20067 SQLITE_PRIVATE void sqlite3PrngResetState(void){
20068 GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0;
20070 #endif /* SQLITE_OMIT_BUILTIN_TEST */
20072 /************** End of random.c **********************************************/
20073 /************** Begin file utf.c *********************************************/
20075 ** 2004 April 13
20077 ** The author disclaims copyright to this source code. In place of
20078 ** a legal notice, here is a blessing:
20080 ** May you do good and not evil.
20081 ** May you find forgiveness for yourself and forgive others.
20082 ** May you share freely, never taking more than you give.
20084 *************************************************************************
20085 ** This file contains routines used to translate between UTF-8,
20086 ** UTF-16, UTF-16BE, and UTF-16LE.
20088 ** Notes on UTF-8:
20090 ** Byte-0 Byte-1 Byte-2 Byte-3 Value
20091 ** 0xxxxxxx 00000000 00000000 0xxxxxxx
20092 ** 110yyyyy 10xxxxxx 00000000 00000yyy yyxxxxxx
20093 ** 1110zzzz 10yyyyyy 10xxxxxx 00000000 zzzzyyyy yyxxxxxx
20094 ** 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx 000uuuuu zzzzyyyy yyxxxxxx
20097 ** Notes on UTF-16: (with wwww+1==uuuuu)
20099 ** Word-0 Word-1 Value
20100 ** 110110ww wwzzzzyy 110111yy yyxxxxxx 000uuuuu zzzzyyyy yyxxxxxx
20101 ** zzzzyyyy yyxxxxxx 00000000 zzzzyyyy yyxxxxxx
20104 ** BOM or Byte Order Mark:
20105 ** 0xff 0xfe little-endian utf-16 follows
20106 ** 0xfe 0xff big-endian utf-16 follows
20109 /* #include <assert.h> */
20111 #ifndef SQLITE_AMALGAMATION
20113 ** The following constant value is used by the SQLITE_BIGENDIAN and
20114 ** SQLITE_LITTLEENDIAN macros.
20116 SQLITE_PRIVATE const int sqlite3one = 1;
20117 #endif /* SQLITE_AMALGAMATION */
20120 ** This lookup table is used to help decode the first byte of
20121 ** a multi-byte UTF8 character.
20123 static const unsigned char sqlite3Utf8Trans1[] = {
20124 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
20125 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
20126 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
20127 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
20128 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
20129 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
20130 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
20131 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
20135 #define WRITE_UTF8(zOut, c) { \
20136 if( c<0x00080 ){ \
20137 *zOut++ = (u8)(c&0xFF); \
20139 else if( c<0x00800 ){ \
20140 *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
20141 *zOut++ = 0x80 + (u8)(c & 0x3F); \
20143 else if( c<0x10000 ){ \
20144 *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
20145 *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
20146 *zOut++ = 0x80 + (u8)(c & 0x3F); \
20147 }else{ \
20148 *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
20149 *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
20150 *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
20151 *zOut++ = 0x80 + (u8)(c & 0x3F); \
20155 #define WRITE_UTF16LE(zOut, c) { \
20156 if( c<=0xFFFF ){ \
20157 *zOut++ = (u8)(c&0x00FF); \
20158 *zOut++ = (u8)((c>>8)&0x00FF); \
20159 }else{ \
20160 *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
20161 *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
20162 *zOut++ = (u8)(c&0x00FF); \
20163 *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
20167 #define WRITE_UTF16BE(zOut, c) { \
20168 if( c<=0xFFFF ){ \
20169 *zOut++ = (u8)((c>>8)&0x00FF); \
20170 *zOut++ = (u8)(c&0x00FF); \
20171 }else{ \
20172 *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
20173 *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
20174 *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
20175 *zOut++ = (u8)(c&0x00FF); \
20179 #define READ_UTF16LE(zIn, TERM, c){ \
20180 c = (*zIn++); \
20181 c += ((*zIn++)<<8); \
20182 if( c>=0xD800 && c<0xE000 && TERM ){ \
20183 int c2 = (*zIn++); \
20184 c2 += ((*zIn++)<<8); \
20185 c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
20189 #define READ_UTF16BE(zIn, TERM, c){ \
20190 c = ((*zIn++)<<8); \
20191 c += (*zIn++); \
20192 if( c>=0xD800 && c<0xE000 && TERM ){ \
20193 int c2 = ((*zIn++)<<8); \
20194 c2 += (*zIn++); \
20195 c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
20200 ** Translate a single UTF-8 character. Return the unicode value.
20202 ** During translation, assume that the byte that zTerm points
20203 ** is a 0x00.
20205 ** Write a pointer to the next unread byte back into *pzNext.
20207 ** Notes On Invalid UTF-8:
20209 ** * This routine never allows a 7-bit character (0x00 through 0x7f) to
20210 ** be encoded as a multi-byte character. Any multi-byte character that
20211 ** attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
20213 ** * This routine never allows a UTF16 surrogate value to be encoded.
20214 ** If a multi-byte character attempts to encode a value between
20215 ** 0xd800 and 0xe000 then it is rendered as 0xfffd.
20217 ** * Bytes in the range of 0x80 through 0xbf which occur as the first
20218 ** byte of a character are interpreted as single-byte characters
20219 ** and rendered as themselves even though they are technically
20220 ** invalid characters.
20222 ** * This routine accepts an infinite number of different UTF8 encodings
20223 ** for unicode values 0x80 and greater. It do not change over-length
20224 ** encodings to 0xfffd as some systems recommend.
20226 #define READ_UTF8(zIn, zTerm, c) \
20227 c = *(zIn++); \
20228 if( c>=0xc0 ){ \
20229 c = sqlite3Utf8Trans1[c-0xc0]; \
20230 while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
20231 c = (c<<6) + (0x3f & *(zIn++)); \
20233 if( c<0x80 \
20234 || (c&0xFFFFF800)==0xD800 \
20235 || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
20237 SQLITE_PRIVATE u32 sqlite3Utf8Read(
20238 const unsigned char *zIn, /* First byte of UTF-8 character */
20239 const unsigned char **pzNext /* Write first byte past UTF-8 char here */
20241 unsigned int c;
20243 /* Same as READ_UTF8() above but without the zTerm parameter.
20244 ** For this routine, we assume the UTF8 string is always zero-terminated.
20246 c = *(zIn++);
20247 if( c>=0xc0 ){
20248 c = sqlite3Utf8Trans1[c-0xc0];
20249 while( (*zIn & 0xc0)==0x80 ){
20250 c = (c<<6) + (0x3f & *(zIn++));
20252 if( c<0x80
20253 || (c&0xFFFFF800)==0xD800
20254 || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; }
20256 *pzNext = zIn;
20257 return c;
20264 ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
20265 ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
20267 /* #define TRANSLATE_TRACE 1 */
20269 #ifndef SQLITE_OMIT_UTF16
20271 ** This routine transforms the internal text encoding used by pMem to
20272 ** desiredEnc. It is an error if the string is already of the desired
20273 ** encoding, or if *pMem does not contain a string value.
20275 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
20276 int len; /* Maximum length of output string in bytes */
20277 unsigned char *zOut; /* Output buffer */
20278 unsigned char *zIn; /* Input iterator */
20279 unsigned char *zTerm; /* End of input */
20280 unsigned char *z; /* Output iterator */
20281 unsigned int c;
20283 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
20284 assert( pMem->flags&MEM_Str );
20285 assert( pMem->enc!=desiredEnc );
20286 assert( pMem->enc!=0 );
20287 assert( pMem->n>=0 );
20289 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
20291 char zBuf[100];
20292 sqlite3VdbeMemPrettyPrint(pMem, zBuf);
20293 fprintf(stderr, "INPUT: %s\n", zBuf);
20295 #endif
20297 /* If the translation is between UTF-16 little and big endian, then
20298 ** all that is required is to swap the byte order. This case is handled
20299 ** differently from the others.
20301 if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
20302 u8 temp;
20303 int rc;
20304 rc = sqlite3VdbeMemMakeWriteable(pMem);
20305 if( rc!=SQLITE_OK ){
20306 assert( rc==SQLITE_NOMEM );
20307 return SQLITE_NOMEM;
20309 zIn = (u8*)pMem->z;
20310 zTerm = &zIn[pMem->n&~1];
20311 while( zIn<zTerm ){
20312 temp = *zIn;
20313 *zIn = *(zIn+1);
20314 zIn++;
20315 *zIn++ = temp;
20317 pMem->enc = desiredEnc;
20318 goto translate_out;
20321 /* Set len to the maximum number of bytes required in the output buffer. */
20322 if( desiredEnc==SQLITE_UTF8 ){
20323 /* When converting from UTF-16, the maximum growth results from
20324 ** translating a 2-byte character to a 4-byte UTF-8 character.
20325 ** A single byte is required for the output string
20326 ** nul-terminator.
20328 pMem->n &= ~1;
20329 len = pMem->n * 2 + 1;
20330 }else{
20331 /* When converting from UTF-8 to UTF-16 the maximum growth is caused
20332 ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
20333 ** character. Two bytes are required in the output buffer for the
20334 ** nul-terminator.
20336 len = pMem->n * 2 + 2;
20339 /* Set zIn to point at the start of the input buffer and zTerm to point 1
20340 ** byte past the end.
20342 ** Variable zOut is set to point at the output buffer, space obtained
20343 ** from sqlite3_malloc().
20345 zIn = (u8*)pMem->z;
20346 zTerm = &zIn[pMem->n];
20347 zOut = sqlite3DbMallocRaw(pMem->db, len);
20348 if( !zOut ){
20349 return SQLITE_NOMEM;
20351 z = zOut;
20353 if( pMem->enc==SQLITE_UTF8 ){
20354 if( desiredEnc==SQLITE_UTF16LE ){
20355 /* UTF-8 -> UTF-16 Little-endian */
20356 while( zIn<zTerm ){
20357 /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
20358 READ_UTF8(zIn, zTerm, c);
20359 WRITE_UTF16LE(z, c);
20361 }else{
20362 assert( desiredEnc==SQLITE_UTF16BE );
20363 /* UTF-8 -> UTF-16 Big-endian */
20364 while( zIn<zTerm ){
20365 /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
20366 READ_UTF8(zIn, zTerm, c);
20367 WRITE_UTF16BE(z, c);
20370 pMem->n = (int)(z - zOut);
20371 *z++ = 0;
20372 }else{
20373 assert( desiredEnc==SQLITE_UTF8 );
20374 if( pMem->enc==SQLITE_UTF16LE ){
20375 /* UTF-16 Little-endian -> UTF-8 */
20376 while( zIn<zTerm ){
20377 READ_UTF16LE(zIn, zIn<zTerm, c);
20378 WRITE_UTF8(z, c);
20380 }else{
20381 /* UTF-16 Big-endian -> UTF-8 */
20382 while( zIn<zTerm ){
20383 READ_UTF16BE(zIn, zIn<zTerm, c);
20384 WRITE_UTF8(z, c);
20387 pMem->n = (int)(z - zOut);
20389 *z = 0;
20390 assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
20392 sqlite3VdbeMemRelease(pMem);
20393 pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
20394 pMem->enc = desiredEnc;
20395 pMem->flags |= (MEM_Term|MEM_Dyn);
20396 pMem->z = (char*)zOut;
20397 pMem->zMalloc = pMem->z;
20399 translate_out:
20400 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
20402 char zBuf[100];
20403 sqlite3VdbeMemPrettyPrint(pMem, zBuf);
20404 fprintf(stderr, "OUTPUT: %s\n", zBuf);
20406 #endif
20407 return SQLITE_OK;
20411 ** This routine checks for a byte-order mark at the beginning of the
20412 ** UTF-16 string stored in *pMem. If one is present, it is removed and
20413 ** the encoding of the Mem adjusted. This routine does not do any
20414 ** byte-swapping, it just sets Mem.enc appropriately.
20416 ** The allocation (static, dynamic etc.) and encoding of the Mem may be
20417 ** changed by this function.
20419 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
20420 int rc = SQLITE_OK;
20421 u8 bom = 0;
20423 assert( pMem->n>=0 );
20424 if( pMem->n>1 ){
20425 u8 b1 = *(u8 *)pMem->z;
20426 u8 b2 = *(((u8 *)pMem->z) + 1);
20427 if( b1==0xFE && b2==0xFF ){
20428 bom = SQLITE_UTF16BE;
20430 if( b1==0xFF && b2==0xFE ){
20431 bom = SQLITE_UTF16LE;
20435 if( bom ){
20436 rc = sqlite3VdbeMemMakeWriteable(pMem);
20437 if( rc==SQLITE_OK ){
20438 pMem->n -= 2;
20439 memmove(pMem->z, &pMem->z[2], pMem->n);
20440 pMem->z[pMem->n] = '\0';
20441 pMem->z[pMem->n+1] = '\0';
20442 pMem->flags |= MEM_Term;
20443 pMem->enc = bom;
20446 return rc;
20448 #endif /* SQLITE_OMIT_UTF16 */
20451 ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
20452 ** return the number of unicode characters in pZ up to (but not including)
20453 ** the first 0x00 byte. If nByte is not less than zero, return the
20454 ** number of unicode characters in the first nByte of pZ (or up to
20455 ** the first 0x00, whichever comes first).
20457 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
20458 int r = 0;
20459 const u8 *z = (const u8*)zIn;
20460 const u8 *zTerm;
20461 if( nByte>=0 ){
20462 zTerm = &z[nByte];
20463 }else{
20464 zTerm = (const u8*)(-1);
20466 assert( z<=zTerm );
20467 while( *z!=0 && z<zTerm ){
20468 SQLITE_SKIP_UTF8(z);
20469 r++;
20471 return r;
20474 /* This test function is not currently used by the automated test-suite.
20475 ** Hence it is only available in debug builds.
20477 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
20479 ** Translate UTF-8 to UTF-8.
20481 ** This has the effect of making sure that the string is well-formed
20482 ** UTF-8. Miscoded characters are removed.
20484 ** The translation is done in-place and aborted if the output
20485 ** overruns the input.
20487 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
20488 unsigned char *zOut = zIn;
20489 unsigned char *zStart = zIn;
20490 u32 c;
20492 while( zIn[0] && zOut<=zIn ){
20493 c = sqlite3Utf8Read(zIn, (const u8**)&zIn);
20494 if( c!=0xfffd ){
20495 WRITE_UTF8(zOut, c);
20498 *zOut = 0;
20499 return (int)(zOut - zStart);
20501 #endif
20503 #ifndef SQLITE_OMIT_UTF16
20505 ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
20506 ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
20507 ** be freed by the calling function.
20509 ** NULL is returned if there is an allocation error.
20511 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
20512 Mem m;
20513 memset(&m, 0, sizeof(m));
20514 m.db = db;
20515 sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
20516 sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
20517 if( db->mallocFailed ){
20518 sqlite3VdbeMemRelease(&m);
20519 m.z = 0;
20521 assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
20522 assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
20523 assert( (m.flags & MEM_Dyn)!=0 || db->mallocFailed );
20524 assert( m.z || db->mallocFailed );
20525 return m.z;
20529 ** Convert a UTF-8 string to the UTF-16 encoding specified by parameter
20530 ** enc. A pointer to the new string is returned, and the value of *pnOut
20531 ** is set to the length of the returned string in bytes. The call should
20532 ** arrange to call sqlite3DbFree() on the returned pointer when it is
20533 ** no longer required.
20535 ** If a malloc failure occurs, NULL is returned and the db.mallocFailed
20536 ** flag set.
20538 #ifdef SQLITE_ENABLE_STAT3
20539 SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *db, u8 enc, char *z, int n, int *pnOut){
20540 Mem m;
20541 memset(&m, 0, sizeof(m));
20542 m.db = db;
20543 sqlite3VdbeMemSetStr(&m, z, n, SQLITE_UTF8, SQLITE_STATIC);
20544 if( sqlite3VdbeMemTranslate(&m, enc) ){
20545 assert( db->mallocFailed );
20546 return 0;
20548 assert( m.z==m.zMalloc );
20549 *pnOut = m.n;
20550 return m.z;
20552 #endif
20555 ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
20556 ** Return the number of bytes in the first nChar unicode characters
20557 ** in pZ. nChar must be non-negative.
20559 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
20560 int c;
20561 unsigned char const *z = zIn;
20562 int n = 0;
20564 if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
20565 while( n<nChar ){
20566 READ_UTF16BE(z, 1, c);
20567 n++;
20569 }else{
20570 while( n<nChar ){
20571 READ_UTF16LE(z, 1, c);
20572 n++;
20575 return (int)(z-(unsigned char const *)zIn);
20578 #if defined(SQLITE_TEST)
20580 ** This routine is called from the TCL test function "translate_selftest".
20581 ** It checks that the primitives for serializing and deserializing
20582 ** characters in each encoding are inverses of each other.
20584 SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
20585 unsigned int i, t;
20586 unsigned char zBuf[20];
20587 unsigned char *z;
20588 int n;
20589 unsigned int c;
20591 for(i=0; i<0x00110000; i++){
20592 z = zBuf;
20593 WRITE_UTF8(z, i);
20594 n = (int)(z-zBuf);
20595 assert( n>0 && n<=4 );
20596 z[0] = 0;
20597 z = zBuf;
20598 c = sqlite3Utf8Read(z, (const u8**)&z);
20599 t = i;
20600 if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
20601 if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
20602 assert( c==t );
20603 assert( (z-zBuf)==n );
20605 for(i=0; i<0x00110000; i++){
20606 if( i>=0xD800 && i<0xE000 ) continue;
20607 z = zBuf;
20608 WRITE_UTF16LE(z, i);
20609 n = (int)(z-zBuf);
20610 assert( n>0 && n<=4 );
20611 z[0] = 0;
20612 z = zBuf;
20613 READ_UTF16LE(z, 1, c);
20614 assert( c==i );
20615 assert( (z-zBuf)==n );
20617 for(i=0; i<0x00110000; i++){
20618 if( i>=0xD800 && i<0xE000 ) continue;
20619 z = zBuf;
20620 WRITE_UTF16BE(z, i);
20621 n = (int)(z-zBuf);
20622 assert( n>0 && n<=4 );
20623 z[0] = 0;
20624 z = zBuf;
20625 READ_UTF16BE(z, 1, c);
20626 assert( c==i );
20627 assert( (z-zBuf)==n );
20630 #endif /* SQLITE_TEST */
20631 #endif /* SQLITE_OMIT_UTF16 */
20633 /************** End of utf.c *************************************************/
20634 /************** Begin file util.c ********************************************/
20636 ** 2001 September 15
20638 ** The author disclaims copyright to this source code. In place of
20639 ** a legal notice, here is a blessing:
20641 ** May you do good and not evil.
20642 ** May you find forgiveness for yourself and forgive others.
20643 ** May you share freely, never taking more than you give.
20645 *************************************************************************
20646 ** Utility functions used throughout sqlite.
20648 ** This file contains functions for allocating memory, comparing
20649 ** strings, and stuff like that.
20652 /* #include <stdarg.h> */
20653 #ifdef SQLITE_HAVE_ISNAN
20654 # include <math.h>
20655 #endif
20658 ** Routine needed to support the testcase() macro.
20660 #ifdef SQLITE_COVERAGE_TEST
20661 SQLITE_PRIVATE void sqlite3Coverage(int x){
20662 static unsigned dummy = 0;
20663 dummy += (unsigned)x;
20665 #endif
20667 #ifndef SQLITE_OMIT_FLOATING_POINT
20669 ** Return true if the floating point value is Not a Number (NaN).
20671 ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
20672 ** Otherwise, we have our own implementation that works on most systems.
20674 SQLITE_PRIVATE int sqlite3IsNaN(double x){
20675 int rc; /* The value return */
20676 #if !defined(SQLITE_HAVE_ISNAN)
20678 ** Systems that support the isnan() library function should probably
20679 ** make use of it by compiling with -DSQLITE_HAVE_ISNAN. But we have
20680 ** found that many systems do not have a working isnan() function so
20681 ** this implementation is provided as an alternative.
20683 ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
20684 ** On the other hand, the use of -ffast-math comes with the following
20685 ** warning:
20687 ** This option [-ffast-math] should never be turned on by any
20688 ** -O option since it can result in incorrect output for programs
20689 ** which depend on an exact implementation of IEEE or ISO
20690 ** rules/specifications for math functions.
20692 ** Under MSVC, this NaN test may fail if compiled with a floating-
20693 ** point precision mode other than /fp:precise. From the MSDN
20694 ** documentation:
20696 ** The compiler [with /fp:precise] will properly handle comparisons
20697 ** involving NaN. For example, x != x evaluates to true if x is NaN
20698 ** ...
20700 #ifdef __FAST_MATH__
20701 # error SQLite will not work correctly with the -ffast-math option of GCC.
20702 #endif
20703 volatile double y = x;
20704 volatile double z = y;
20705 rc = (y!=z);
20706 #else /* if defined(SQLITE_HAVE_ISNAN) */
20707 rc = isnan(x);
20708 #endif /* SQLITE_HAVE_ISNAN */
20709 testcase( rc );
20710 return rc;
20712 #endif /* SQLITE_OMIT_FLOATING_POINT */
20715 ** Compute a string length that is limited to what can be stored in
20716 ** lower 30 bits of a 32-bit signed integer.
20718 ** The value returned will never be negative. Nor will it ever be greater
20719 ** than the actual length of the string. For very long strings (greater
20720 ** than 1GiB) the value returned might be less than the true string length.
20722 SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
20723 const char *z2 = z;
20724 if( z==0 ) return 0;
20725 while( *z2 ){ z2++; }
20726 return 0x3fffffff & (int)(z2 - z);
20730 ** Set the most recent error code and error string for the sqlite
20731 ** handle "db". The error code is set to "err_code".
20733 ** If it is not NULL, string zFormat specifies the format of the
20734 ** error string in the style of the printf functions: The following
20735 ** format characters are allowed:
20737 ** %s Insert a string
20738 ** %z A string that should be freed after use
20739 ** %d Insert an integer
20740 ** %T Insert a token
20741 ** %S Insert the first element of a SrcList
20743 ** zFormat and any string tokens that follow it are assumed to be
20744 ** encoded in UTF-8.
20746 ** To clear the most recent error for sqlite handle "db", sqlite3Error
20747 ** should be called with err_code set to SQLITE_OK and zFormat set
20748 ** to NULL.
20750 SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
20751 if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
20752 db->errCode = err_code;
20753 if( zFormat ){
20754 char *z;
20755 va_list ap;
20756 va_start(ap, zFormat);
20757 z = sqlite3VMPrintf(db, zFormat, ap);
20758 va_end(ap);
20759 sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
20760 }else{
20761 sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
20767 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
20768 ** The following formatting characters are allowed:
20770 ** %s Insert a string
20771 ** %z A string that should be freed after use
20772 ** %d Insert an integer
20773 ** %T Insert a token
20774 ** %S Insert the first element of a SrcList
20776 ** This function should be used to report any error that occurs whilst
20777 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
20778 ** last thing the sqlite3_prepare() function does is copy the error
20779 ** stored by this function into the database handle using sqlite3Error().
20780 ** Function sqlite3Error() should be used during statement execution
20781 ** (sqlite3_step() etc.).
20783 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
20784 char *zMsg;
20785 va_list ap;
20786 sqlite3 *db = pParse->db;
20787 va_start(ap, zFormat);
20788 zMsg = sqlite3VMPrintf(db, zFormat, ap);
20789 va_end(ap);
20790 if( db->suppressErr ){
20791 sqlite3DbFree(db, zMsg);
20792 }else{
20793 pParse->nErr++;
20794 sqlite3DbFree(db, pParse->zErrMsg);
20795 pParse->zErrMsg = zMsg;
20796 pParse->rc = SQLITE_ERROR;
20801 ** Convert an SQL-style quoted string into a normal string by removing
20802 ** the quote characters. The conversion is done in-place. If the
20803 ** input does not begin with a quote character, then this routine
20804 ** is a no-op.
20806 ** The input string must be zero-terminated. A new zero-terminator
20807 ** is added to the dequoted string.
20809 ** The return value is -1 if no dequoting occurs or the length of the
20810 ** dequoted string, exclusive of the zero terminator, if dequoting does
20811 ** occur.
20813 ** 2002-Feb-14: This routine is extended to remove MS-Access style
20814 ** brackets from around identifers. For example: "[a-b-c]" becomes
20815 ** "a-b-c".
20817 SQLITE_PRIVATE int sqlite3Dequote(char *z){
20818 char quote;
20819 int i, j;
20820 if( z==0 ) return -1;
20821 quote = z[0];
20822 switch( quote ){
20823 case '\'': break;
20824 case '"': break;
20825 case '`': break; /* For MySQL compatibility */
20826 case '[': quote = ']'; break; /* For MS SqlServer compatibility */
20827 default: return -1;
20829 for(i=1, j=0; ALWAYS(z[i]); i++){
20830 if( z[i]==quote ){
20831 if( z[i+1]==quote ){
20832 z[j++] = quote;
20833 i++;
20834 }else{
20835 break;
20837 }else{
20838 z[j++] = z[i];
20841 z[j] = 0;
20842 return j;
20845 /* Convenient short-hand */
20846 #define UpperToLower sqlite3UpperToLower
20849 ** Some systems have stricmp(). Others have strcasecmp(). Because
20850 ** there is no consistency, we will define our own.
20852 ** IMPLEMENTATION-OF: R-20522-24639 The sqlite3_strnicmp() API allows
20853 ** applications and extensions to compare the contents of two buffers
20854 ** containing UTF-8 strings in a case-independent fashion, using the same
20855 ** definition of case independence that SQLite uses internally when
20856 ** comparing identifiers.
20858 SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
20859 register unsigned char *a, *b;
20860 a = (unsigned char *)zLeft;
20861 b = (unsigned char *)zRight;
20862 while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
20863 return UpperToLower[*a] - UpperToLower[*b];
20865 SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
20866 register unsigned char *a, *b;
20867 a = (unsigned char *)zLeft;
20868 b = (unsigned char *)zRight;
20869 while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
20870 return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
20874 ** The string z[] is an text representation of a real number.
20875 ** Convert this string to a double and write it into *pResult.
20877 ** The string z[] is length bytes in length (bytes, not characters) and
20878 ** uses the encoding enc. The string is not necessarily zero-terminated.
20880 ** Return TRUE if the result is a valid real number (or integer) and FALSE
20881 ** if the string is empty or contains extraneous text. Valid numbers
20882 ** are in one of these formats:
20884 ** [+-]digits[E[+-]digits]
20885 ** [+-]digits.[digits][E[+-]digits]
20886 ** [+-].digits[E[+-]digits]
20888 ** Leading and trailing whitespace is ignored for the purpose of determining
20889 ** validity.
20891 ** If some prefix of the input string is a valid number, this routine
20892 ** returns FALSE but it still converts the prefix and writes the result
20893 ** into *pResult.
20895 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
20896 #ifndef SQLITE_OMIT_FLOATING_POINT
20897 int incr = (enc==SQLITE_UTF8?1:2);
20898 const char *zEnd = z + length;
20899 /* sign * significand * (10 ^ (esign * exponent)) */
20900 int sign = 1; /* sign of significand */
20901 i64 s = 0; /* significand */
20902 int d = 0; /* adjust exponent for shifting decimal point */
20903 int esign = 1; /* sign of exponent */
20904 int e = 0; /* exponent */
20905 int eValid = 1; /* True exponent is either not used or is well-formed */
20906 double result;
20907 int nDigits = 0;
20909 *pResult = 0.0; /* Default return value, in case of an error */
20911 if( enc==SQLITE_UTF16BE ) z++;
20913 /* skip leading spaces */
20914 while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
20915 if( z>=zEnd ) return 0;
20917 /* get sign of significand */
20918 if( *z=='-' ){
20919 sign = -1;
20920 z+=incr;
20921 }else if( *z=='+' ){
20922 z+=incr;
20925 /* skip leading zeroes */
20926 while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
20928 /* copy max significant digits to significand */
20929 while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
20930 s = s*10 + (*z - '0');
20931 z+=incr, nDigits++;
20934 /* skip non-significant significand digits
20935 ** (increase exponent by d to shift decimal left) */
20936 while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
20937 if( z>=zEnd ) goto do_atof_calc;
20939 /* if decimal point is present */
20940 if( *z=='.' ){
20941 z+=incr;
20942 /* copy digits from after decimal to significand
20943 ** (decrease exponent by d to shift decimal right) */
20944 while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
20945 s = s*10 + (*z - '0');
20946 z+=incr, nDigits++, d--;
20948 /* skip non-significant digits */
20949 while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++;
20951 if( z>=zEnd ) goto do_atof_calc;
20953 /* if exponent is present */
20954 if( *z=='e' || *z=='E' ){
20955 z+=incr;
20956 eValid = 0;
20957 if( z>=zEnd ) goto do_atof_calc;
20958 /* get sign of exponent */
20959 if( *z=='-' ){
20960 esign = -1;
20961 z+=incr;
20962 }else if( *z=='+' ){
20963 z+=incr;
20965 /* copy digits to exponent */
20966 while( z<zEnd && sqlite3Isdigit(*z) ){
20967 e = e<10000 ? (e*10 + (*z - '0')) : 10000;
20968 z+=incr;
20969 eValid = 1;
20973 /* skip trailing spaces */
20974 if( nDigits && eValid ){
20975 while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
20978 do_atof_calc:
20979 /* adjust exponent by d, and update sign */
20980 e = (e*esign) + d;
20981 if( e<0 ) {
20982 esign = -1;
20983 e *= -1;
20984 } else {
20985 esign = 1;
20988 /* if 0 significand */
20989 if( !s ) {
20990 /* In the IEEE 754 standard, zero is signed.
20991 ** Add the sign if we've seen at least one digit */
20992 result = (sign<0 && nDigits) ? -(double)0 : (double)0;
20993 } else {
20994 /* attempt to reduce exponent */
20995 if( esign>0 ){
20996 while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
20997 }else{
20998 while( !(s%10) && e>0 ) e--,s/=10;
21001 /* adjust the sign of significand */
21002 s = sign<0 ? -s : s;
21004 /* if exponent, scale significand as appropriate
21005 ** and store in result. */
21006 if( e ){
21007 double scale = 1.0;
21008 /* attempt to handle extremely small/large numbers better */
21009 if( e>307 && e<342 ){
21010 while( e%308 ) { scale *= 1.0e+1; e -= 1; }
21011 if( esign<0 ){
21012 result = s / scale;
21013 result /= 1.0e+308;
21014 }else{
21015 result = s * scale;
21016 result *= 1.0e+308;
21018 }else if( e>=342 ){
21019 if( esign<0 ){
21020 result = 0.0*s;
21021 }else{
21022 result = 1e308*1e308*s; /* Infinity */
21024 }else{
21025 /* 1.0e+22 is the largest power of 10 than can be
21026 ** represented exactly. */
21027 while( e%22 ) { scale *= 1.0e+1; e -= 1; }
21028 while( e>0 ) { scale *= 1.0e+22; e -= 22; }
21029 if( esign<0 ){
21030 result = s / scale;
21031 }else{
21032 result = s * scale;
21035 } else {
21036 result = (double)s;
21040 /* store the result */
21041 *pResult = result;
21043 /* return true if number and no extra non-whitespace chracters after */
21044 return z>=zEnd && nDigits>0 && eValid;
21045 #else
21046 return !sqlite3Atoi64(z, pResult, length, enc);
21047 #endif /* SQLITE_OMIT_FLOATING_POINT */
21051 ** Compare the 19-character string zNum against the text representation
21052 ** value 2^63: 9223372036854775808. Return negative, zero, or positive
21053 ** if zNum is less than, equal to, or greater than the string.
21054 ** Note that zNum must contain exactly 19 characters.
21056 ** Unlike memcmp() this routine is guaranteed to return the difference
21057 ** in the values of the last digit if the only difference is in the
21058 ** last digit. So, for example,
21060 ** compare2pow63("9223372036854775800", 1)
21062 ** will return -8.
21064 static int compare2pow63(const char *zNum, int incr){
21065 int c = 0;
21066 int i;
21067 /* 012345678901234567 */
21068 const char *pow63 = "922337203685477580";
21069 for(i=0; c==0 && i<18; i++){
21070 c = (zNum[i*incr]-pow63[i])*10;
21072 if( c==0 ){
21073 c = zNum[18*incr] - '8';
21074 testcase( c==(-1) );
21075 testcase( c==0 );
21076 testcase( c==(+1) );
21078 return c;
21083 ** Convert zNum to a 64-bit signed integer.
21085 ** If the zNum value is representable as a 64-bit twos-complement
21086 ** integer, then write that value into *pNum and return 0.
21088 ** If zNum is exactly 9223372036854665808, return 2. This special
21089 ** case is broken out because while 9223372036854665808 cannot be a
21090 ** signed 64-bit integer, its negative -9223372036854665808 can be.
21092 ** If zNum is too big for a 64-bit integer and is not
21093 ** 9223372036854665808 then return 1.
21095 ** length is the number of bytes in the string (bytes, not characters).
21096 ** The string is not necessarily zero-terminated. The encoding is
21097 ** given by enc.
21099 SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
21100 int incr = (enc==SQLITE_UTF8?1:2);
21101 u64 u = 0;
21102 int neg = 0; /* assume positive */
21103 int i;
21104 int c = 0;
21105 const char *zStart;
21106 const char *zEnd = zNum + length;
21107 if( enc==SQLITE_UTF16BE ) zNum++;
21108 while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
21109 if( zNum<zEnd ){
21110 if( *zNum=='-' ){
21111 neg = 1;
21112 zNum+=incr;
21113 }else if( *zNum=='+' ){
21114 zNum+=incr;
21117 zStart = zNum;
21118 while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
21119 for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
21120 u = u*10 + c - '0';
21122 if( u>LARGEST_INT64 ){
21123 *pNum = SMALLEST_INT64;
21124 }else if( neg ){
21125 *pNum = -(i64)u;
21126 }else{
21127 *pNum = (i64)u;
21129 testcase( i==18 );
21130 testcase( i==19 );
21131 testcase( i==20 );
21132 if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum) || i>19*incr ){
21133 /* zNum is empty or contains non-numeric text or is longer
21134 ** than 19 digits (thus guaranteeing that it is too large) */
21135 return 1;
21136 }else if( i<19*incr ){
21137 /* Less than 19 digits, so we know that it fits in 64 bits */
21138 assert( u<=LARGEST_INT64 );
21139 return 0;
21140 }else{
21141 /* zNum is a 19-digit numbers. Compare it against 9223372036854775808. */
21142 c = compare2pow63(zNum, incr);
21143 if( c<0 ){
21144 /* zNum is less than 9223372036854775808 so it fits */
21145 assert( u<=LARGEST_INT64 );
21146 return 0;
21147 }else if( c>0 ){
21148 /* zNum is greater than 9223372036854775808 so it overflows */
21149 return 1;
21150 }else{
21151 /* zNum is exactly 9223372036854775808. Fits if negative. The
21152 ** special case 2 overflow if positive */
21153 assert( u-1==LARGEST_INT64 );
21154 assert( (*pNum)==SMALLEST_INT64 );
21155 return neg ? 0 : 2;
21161 ** If zNum represents an integer that will fit in 32-bits, then set
21162 ** *pValue to that integer and return true. Otherwise return false.
21164 ** Any non-numeric characters that following zNum are ignored.
21165 ** This is different from sqlite3Atoi64() which requires the
21166 ** input number to be zero-terminated.
21168 SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
21169 sqlite_int64 v = 0;
21170 int i, c;
21171 int neg = 0;
21172 if( zNum[0]=='-' ){
21173 neg = 1;
21174 zNum++;
21175 }else if( zNum[0]=='+' ){
21176 zNum++;
21178 while( zNum[0]=='0' ) zNum++;
21179 for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
21180 v = v*10 + c;
21183 /* The longest decimal representation of a 32 bit integer is 10 digits:
21185 ** 1234567890
21186 ** 2^31 -> 2147483648
21188 testcase( i==10 );
21189 if( i>10 ){
21190 return 0;
21192 testcase( v-neg==2147483647 );
21193 if( v-neg>2147483647 ){
21194 return 0;
21196 if( neg ){
21197 v = -v;
21199 *pValue = (int)v;
21200 return 1;
21204 ** Return a 32-bit integer value extracted from a string. If the
21205 ** string is not an integer, just return 0.
21207 SQLITE_PRIVATE int sqlite3Atoi(const char *z){
21208 int x = 0;
21209 if( z ) sqlite3GetInt32(z, &x);
21210 return x;
21214 ** The variable-length integer encoding is as follows:
21216 ** KEY:
21217 ** A = 0xxxxxxx 7 bits of data and one flag bit
21218 ** B = 1xxxxxxx 7 bits of data and one flag bit
21219 ** C = xxxxxxxx 8 bits of data
21221 ** 7 bits - A
21222 ** 14 bits - BA
21223 ** 21 bits - BBA
21224 ** 28 bits - BBBA
21225 ** 35 bits - BBBBA
21226 ** 42 bits - BBBBBA
21227 ** 49 bits - BBBBBBA
21228 ** 56 bits - BBBBBBBA
21229 ** 64 bits - BBBBBBBBC
21233 ** Write a 64-bit variable-length integer to memory starting at p[0].
21234 ** The length of data write will be between 1 and 9 bytes. The number
21235 ** of bytes written is returned.
21237 ** A variable-length integer consists of the lower 7 bits of each byte
21238 ** for all bytes that have the 8th bit set and one byte with the 8th
21239 ** bit clear. Except, if we get to the 9th byte, it stores the full
21240 ** 8 bits and is the last byte.
21242 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
21243 int i, j, n;
21244 u8 buf[10];
21245 if( v & (((u64)0xff000000)<<32) ){
21246 p[8] = (u8)v;
21247 v >>= 8;
21248 for(i=7; i>=0; i--){
21249 p[i] = (u8)((v & 0x7f) | 0x80);
21250 v >>= 7;
21252 return 9;
21254 n = 0;
21256 buf[n++] = (u8)((v & 0x7f) | 0x80);
21257 v >>= 7;
21258 }while( v!=0 );
21259 buf[0] &= 0x7f;
21260 assert( n<=9 );
21261 for(i=0, j=n-1; j>=0; j--, i++){
21262 p[i] = buf[j];
21264 return n;
21268 ** This routine is a faster version of sqlite3PutVarint() that only
21269 ** works for 32-bit positive integers and which is optimized for
21270 ** the common case of small integers. A MACRO version, putVarint32,
21271 ** is provided which inlines the single-byte case. All code should use
21272 ** the MACRO version as this function assumes the single-byte case has
21273 ** already been handled.
21275 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char *p, u32 v){
21276 #ifndef putVarint32
21277 if( (v & ~0x7f)==0 ){
21278 p[0] = v;
21279 return 1;
21281 #endif
21282 if( (v & ~0x3fff)==0 ){
21283 p[0] = (u8)((v>>7) | 0x80);
21284 p[1] = (u8)(v & 0x7f);
21285 return 2;
21287 return sqlite3PutVarint(p, v);
21291 ** Bitmasks used by sqlite3GetVarint(). These precomputed constants
21292 ** are defined here rather than simply putting the constant expressions
21293 ** inline in order to work around bugs in the RVT compiler.
21295 ** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
21297 ** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
21299 #define SLOT_2_0 0x001fc07f
21300 #define SLOT_4_2_0 0xf01fc07f
21304 ** Read a 64-bit variable-length integer from memory starting at p[0].
21305 ** Return the number of bytes read. The value is stored in *v.
21307 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
21308 u32 a,b,s;
21310 a = *p;
21311 /* a: p0 (unmasked) */
21312 if (!(a&0x80))
21314 *v = a;
21315 return 1;
21318 p++;
21319 b = *p;
21320 /* b: p1 (unmasked) */
21321 if (!(b&0x80))
21323 a &= 0x7f;
21324 a = a<<7;
21325 a |= b;
21326 *v = a;
21327 return 2;
21330 /* Verify that constants are precomputed correctly */
21331 assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
21332 assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
21334 p++;
21335 a = a<<14;
21336 a |= *p;
21337 /* a: p0<<14 | p2 (unmasked) */
21338 if (!(a&0x80))
21340 a &= SLOT_2_0;
21341 b &= 0x7f;
21342 b = b<<7;
21343 a |= b;
21344 *v = a;
21345 return 3;
21348 /* CSE1 from below */
21349 a &= SLOT_2_0;
21350 p++;
21351 b = b<<14;
21352 b |= *p;
21353 /* b: p1<<14 | p3 (unmasked) */
21354 if (!(b&0x80))
21356 b &= SLOT_2_0;
21357 /* moved CSE1 up */
21358 /* a &= (0x7f<<14)|(0x7f); */
21359 a = a<<7;
21360 a |= b;
21361 *v = a;
21362 return 4;
21365 /* a: p0<<14 | p2 (masked) */
21366 /* b: p1<<14 | p3 (unmasked) */
21367 /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
21368 /* moved CSE1 up */
21369 /* a &= (0x7f<<14)|(0x7f); */
21370 b &= SLOT_2_0;
21371 s = a;
21372 /* s: p0<<14 | p2 (masked) */
21374 p++;
21375 a = a<<14;
21376 a |= *p;
21377 /* a: p0<<28 | p2<<14 | p4 (unmasked) */
21378 if (!(a&0x80))
21380 /* we can skip these cause they were (effectively) done above in calc'ing s */
21381 /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
21382 /* b &= (0x7f<<14)|(0x7f); */
21383 b = b<<7;
21384 a |= b;
21385 s = s>>18;
21386 *v = ((u64)s)<<32 | a;
21387 return 5;
21390 /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
21391 s = s<<7;
21392 s |= b;
21393 /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
21395 p++;
21396 b = b<<14;
21397 b |= *p;
21398 /* b: p1<<28 | p3<<14 | p5 (unmasked) */
21399 if (!(b&0x80))
21401 /* we can skip this cause it was (effectively) done above in calc'ing s */
21402 /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
21403 a &= SLOT_2_0;
21404 a = a<<7;
21405 a |= b;
21406 s = s>>18;
21407 *v = ((u64)s)<<32 | a;
21408 return 6;
21411 p++;
21412 a = a<<14;
21413 a |= *p;
21414 /* a: p2<<28 | p4<<14 | p6 (unmasked) */
21415 if (!(a&0x80))
21417 a &= SLOT_4_2_0;
21418 b &= SLOT_2_0;
21419 b = b<<7;
21420 a |= b;
21421 s = s>>11;
21422 *v = ((u64)s)<<32 | a;
21423 return 7;
21426 /* CSE2 from below */
21427 a &= SLOT_2_0;
21428 p++;
21429 b = b<<14;
21430 b |= *p;
21431 /* b: p3<<28 | p5<<14 | p7 (unmasked) */
21432 if (!(b&0x80))
21434 b &= SLOT_4_2_0;
21435 /* moved CSE2 up */
21436 /* a &= (0x7f<<14)|(0x7f); */
21437 a = a<<7;
21438 a |= b;
21439 s = s>>4;
21440 *v = ((u64)s)<<32 | a;
21441 return 8;
21444 p++;
21445 a = a<<15;
21446 a |= *p;
21447 /* a: p4<<29 | p6<<15 | p8 (unmasked) */
21449 /* moved CSE2 up */
21450 /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
21451 b &= SLOT_2_0;
21452 b = b<<8;
21453 a |= b;
21455 s = s<<4;
21456 b = p[-4];
21457 b &= 0x7f;
21458 b = b>>3;
21459 s |= b;
21461 *v = ((u64)s)<<32 | a;
21463 return 9;
21467 ** Read a 32-bit variable-length integer from memory starting at p[0].
21468 ** Return the number of bytes read. The value is stored in *v.
21470 ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
21471 ** integer, then set *v to 0xffffffff.
21473 ** A MACRO version, getVarint32, is provided which inlines the
21474 ** single-byte case. All code should use the MACRO version as
21475 ** this function assumes the single-byte case has already been handled.
21477 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
21478 u32 a,b;
21480 /* The 1-byte case. Overwhelmingly the most common. Handled inline
21481 ** by the getVarin32() macro */
21482 a = *p;
21483 /* a: p0 (unmasked) */
21484 #ifndef getVarint32
21485 if (!(a&0x80))
21487 /* Values between 0 and 127 */
21488 *v = a;
21489 return 1;
21491 #endif
21493 /* The 2-byte case */
21494 p++;
21495 b = *p;
21496 /* b: p1 (unmasked) */
21497 if (!(b&0x80))
21499 /* Values between 128 and 16383 */
21500 a &= 0x7f;
21501 a = a<<7;
21502 *v = a | b;
21503 return 2;
21506 /* The 3-byte case */
21507 p++;
21508 a = a<<14;
21509 a |= *p;
21510 /* a: p0<<14 | p2 (unmasked) */
21511 if (!(a&0x80))
21513 /* Values between 16384 and 2097151 */
21514 a &= (0x7f<<14)|(0x7f);
21515 b &= 0x7f;
21516 b = b<<7;
21517 *v = a | b;
21518 return 3;
21521 /* A 32-bit varint is used to store size information in btrees.
21522 ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
21523 ** A 3-byte varint is sufficient, for example, to record the size
21524 ** of a 1048569-byte BLOB or string.
21526 ** We only unroll the first 1-, 2-, and 3- byte cases. The very
21527 ** rare larger cases can be handled by the slower 64-bit varint
21528 ** routine.
21530 #if 1
21532 u64 v64;
21533 u8 n;
21535 p -= 2;
21536 n = sqlite3GetVarint(p, &v64);
21537 assert( n>3 && n<=9 );
21538 if( (v64 & SQLITE_MAX_U32)!=v64 ){
21539 *v = 0xffffffff;
21540 }else{
21541 *v = (u32)v64;
21543 return n;
21546 #else
21547 /* For following code (kept for historical record only) shows an
21548 ** unrolling for the 3- and 4-byte varint cases. This code is
21549 ** slightly faster, but it is also larger and much harder to test.
21551 p++;
21552 b = b<<14;
21553 b |= *p;
21554 /* b: p1<<14 | p3 (unmasked) */
21555 if (!(b&0x80))
21557 /* Values between 2097152 and 268435455 */
21558 b &= (0x7f<<14)|(0x7f);
21559 a &= (0x7f<<14)|(0x7f);
21560 a = a<<7;
21561 *v = a | b;
21562 return 4;
21565 p++;
21566 a = a<<14;
21567 a |= *p;
21568 /* a: p0<<28 | p2<<14 | p4 (unmasked) */
21569 if (!(a&0x80))
21571 /* Values between 268435456 and 34359738367 */
21572 a &= SLOT_4_2_0;
21573 b &= SLOT_4_2_0;
21574 b = b<<7;
21575 *v = a | b;
21576 return 5;
21579 /* We can only reach this point when reading a corrupt database
21580 ** file. In that case we are not in any hurry. Use the (relatively
21581 ** slow) general-purpose sqlite3GetVarint() routine to extract the
21582 ** value. */
21584 u64 v64;
21585 u8 n;
21587 p -= 4;
21588 n = sqlite3GetVarint(p, &v64);
21589 assert( n>5 && n<=9 );
21590 *v = (u32)v64;
21591 return n;
21593 #endif
21597 ** Return the number of bytes that will be needed to store the given
21598 ** 64-bit integer.
21600 SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
21601 int i = 0;
21603 i++;
21604 v >>= 7;
21605 }while( v!=0 && ALWAYS(i<9) );
21606 return i;
21611 ** Read or write a four-byte big-endian integer value.
21613 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
21614 return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
21616 SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
21617 p[0] = (u8)(v>>24);
21618 p[1] = (u8)(v>>16);
21619 p[2] = (u8)(v>>8);
21620 p[3] = (u8)v;
21626 ** Translate a single byte of Hex into an integer.
21627 ** This routine only works if h really is a valid hexadecimal
21628 ** character: 0..9a..fA..F
21630 SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
21631 assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') );
21632 #ifdef SQLITE_ASCII
21633 h += 9*(1&(h>>6));
21634 #endif
21635 #ifdef SQLITE_EBCDIC
21636 h += 9*(1&~(h>>4));
21637 #endif
21638 return (u8)(h & 0xf);
21641 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
21643 ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
21644 ** value. Return a pointer to its binary value. Space to hold the
21645 ** binary value has been obtained from malloc and must be freed by
21646 ** the calling routine.
21648 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
21649 char *zBlob;
21650 int i;
21652 zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
21653 n--;
21654 if( zBlob ){
21655 for(i=0; i<n; i+=2){
21656 zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
21658 zBlob[i/2] = 0;
21660 return zBlob;
21662 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
21665 ** Log an error that is an API call on a connection pointer that should
21666 ** not have been used. The "type" of connection pointer is given as the
21667 ** argument. The zType is a word like "NULL" or "closed" or "invalid".
21669 static void logBadConnection(const char *zType){
21670 sqlite3_log(SQLITE_MISUSE,
21671 "API call with %s database connection pointer",
21672 zType
21677 ** Check to make sure we have a valid db pointer. This test is not
21678 ** foolproof but it does provide some measure of protection against
21679 ** misuse of the interface such as passing in db pointers that are
21680 ** NULL or which have been previously closed. If this routine returns
21681 ** 1 it means that the db pointer is valid and 0 if it should not be
21682 ** dereferenced for any reason. The calling function should invoke
21683 ** SQLITE_MISUSE immediately.
21685 ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
21686 ** use. sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
21687 ** open properly and is not fit for general use but which can be
21688 ** used as an argument to sqlite3_errmsg() or sqlite3_close().
21690 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
21691 u32 magic;
21692 if( db==0 ){
21693 logBadConnection("NULL");
21694 return 0;
21696 magic = db->magic;
21697 if( magic!=SQLITE_MAGIC_OPEN ){
21698 if( sqlite3SafetyCheckSickOrOk(db) ){
21699 testcase( sqlite3GlobalConfig.xLog!=0 );
21700 logBadConnection("unopened");
21702 return 0;
21703 }else{
21704 return 1;
21707 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
21708 u32 magic;
21709 magic = db->magic;
21710 if( magic!=SQLITE_MAGIC_SICK &&
21711 magic!=SQLITE_MAGIC_OPEN &&
21712 magic!=SQLITE_MAGIC_BUSY ){
21713 testcase( sqlite3GlobalConfig.xLog!=0 );
21714 logBadConnection("invalid");
21715 return 0;
21716 }else{
21717 return 1;
21722 ** Attempt to add, substract, or multiply the 64-bit signed value iB against
21723 ** the other 64-bit signed integer at *pA and store the result in *pA.
21724 ** Return 0 on success. Or if the operation would have resulted in an
21725 ** overflow, leave *pA unchanged and return 1.
21727 SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
21728 i64 iA = *pA;
21729 testcase( iA==0 ); testcase( iA==1 );
21730 testcase( iB==-1 ); testcase( iB==0 );
21731 if( iB>=0 ){
21732 testcase( iA>0 && LARGEST_INT64 - iA == iB );
21733 testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
21734 if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
21735 *pA += iB;
21736 }else{
21737 testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
21738 testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
21739 if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
21740 *pA += iB;
21742 return 0;
21744 SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
21745 testcase( iB==SMALLEST_INT64+1 );
21746 if( iB==SMALLEST_INT64 ){
21747 testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
21748 if( (*pA)>=0 ) return 1;
21749 *pA -= iB;
21750 return 0;
21751 }else{
21752 return sqlite3AddInt64(pA, -iB);
21755 #define TWOPOWER32 (((i64)1)<<32)
21756 #define TWOPOWER31 (((i64)1)<<31)
21757 SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
21758 i64 iA = *pA;
21759 i64 iA1, iA0, iB1, iB0, r;
21761 iA1 = iA/TWOPOWER32;
21762 iA0 = iA % TWOPOWER32;
21763 iB1 = iB/TWOPOWER32;
21764 iB0 = iB % TWOPOWER32;
21765 if( iA1*iB1 != 0 ) return 1;
21766 assert( iA1*iB0==0 || iA0*iB1==0 );
21767 r = iA1*iB0 + iA0*iB1;
21768 testcase( r==(-TWOPOWER31)-1 );
21769 testcase( r==(-TWOPOWER31) );
21770 testcase( r==TWOPOWER31 );
21771 testcase( r==TWOPOWER31-1 );
21772 if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1;
21773 r *= TWOPOWER32;
21774 if( sqlite3AddInt64(&r, iA0*iB0) ) return 1;
21775 *pA = r;
21776 return 0;
21780 ** Compute the absolute value of a 32-bit signed integer, of possible. Or
21781 ** if the integer has a value of -2147483648, return +2147483647
21783 SQLITE_PRIVATE int sqlite3AbsInt32(int x){
21784 if( x>=0 ) return x;
21785 if( x==(int)0x80000000 ) return 0x7fffffff;
21786 return -x;
21789 #ifdef SQLITE_ENABLE_8_3_NAMES
21791 ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
21792 ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
21793 ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
21794 ** three characters, then shorten the suffix on z[] to be the last three
21795 ** characters of the original suffix.
21797 ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
21798 ** do the suffix shortening regardless of URI parameter.
21800 ** Examples:
21802 ** test.db-journal => test.nal
21803 ** test.db-wal => test.wal
21804 ** test.db-shm => test.shm
21806 SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
21807 #if SQLITE_ENABLE_8_3_NAMES<2
21808 const char *zOk;
21809 zOk = sqlite3_uri_parameter(zBaseFilename, "8_3_names");
21810 if( zOk && sqlite3GetBoolean(zOk) )
21811 #endif
21813 int i, sz;
21814 sz = sqlite3Strlen30(z);
21815 for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
21816 if( z[i]=='.' && ALWAYS(sz>i+4) ) memcpy(&z[i+1], &z[sz-3], 4);
21819 #endif
21821 /************** End of util.c ************************************************/
21822 /************** Begin file hash.c ********************************************/
21824 ** 2001 September 22
21826 ** The author disclaims copyright to this source code. In place of
21827 ** a legal notice, here is a blessing:
21829 ** May you do good and not evil.
21830 ** May you find forgiveness for yourself and forgive others.
21831 ** May you share freely, never taking more than you give.
21833 *************************************************************************
21834 ** This is the implementation of generic hash-tables
21835 ** used in SQLite.
21837 /* #include <assert.h> */
21839 /* Turn bulk memory into a hash table object by initializing the
21840 ** fields of the Hash structure.
21842 ** "pNew" is a pointer to the hash table that is to be initialized.
21844 SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
21845 assert( pNew!=0 );
21846 pNew->first = 0;
21847 pNew->count = 0;
21848 pNew->htsize = 0;
21849 pNew->ht = 0;
21852 /* Remove all entries from a hash table. Reclaim all memory.
21853 ** Call this routine to delete a hash table or to reset a hash table
21854 ** to the empty state.
21856 SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
21857 HashElem *elem; /* For looping over all elements of the table */
21859 assert( pH!=0 );
21860 elem = pH->first;
21861 pH->first = 0;
21862 sqlite3_free(pH->ht);
21863 pH->ht = 0;
21864 pH->htsize = 0;
21865 while( elem ){
21866 HashElem *next_elem = elem->next;
21867 sqlite3_free(elem);
21868 elem = next_elem;
21870 pH->count = 0;
21874 ** The hashing function.
21876 static unsigned int strHash(const char *z, int nKey){
21877 int h = 0;
21878 assert( nKey>=0 );
21879 while( nKey > 0 ){
21880 h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
21881 nKey--;
21883 return h;
21887 /* Link pNew element into the hash table pH. If pEntry!=0 then also
21888 ** insert pNew into the pEntry hash bucket.
21890 static void insertElement(
21891 Hash *pH, /* The complete hash table */
21892 struct _ht *pEntry, /* The entry into which pNew is inserted */
21893 HashElem *pNew /* The element to be inserted */
21895 HashElem *pHead; /* First element already in pEntry */
21896 if( pEntry ){
21897 pHead = pEntry->count ? pEntry->chain : 0;
21898 pEntry->count++;
21899 pEntry->chain = pNew;
21900 }else{
21901 pHead = 0;
21903 if( pHead ){
21904 pNew->next = pHead;
21905 pNew->prev = pHead->prev;
21906 if( pHead->prev ){ pHead->prev->next = pNew; }
21907 else { pH->first = pNew; }
21908 pHead->prev = pNew;
21909 }else{
21910 pNew->next = pH->first;
21911 if( pH->first ){ pH->first->prev = pNew; }
21912 pNew->prev = 0;
21913 pH->first = pNew;
21918 /* Resize the hash table so that it cantains "new_size" buckets.
21920 ** The hash table might fail to resize if sqlite3_malloc() fails or
21921 ** if the new size is the same as the prior size.
21922 ** Return TRUE if the resize occurs and false if not.
21924 static int rehash(Hash *pH, unsigned int new_size){
21925 struct _ht *new_ht; /* The new hash table */
21926 HashElem *elem, *next_elem; /* For looping over existing elements */
21928 #if SQLITE_MALLOC_SOFT_LIMIT>0
21929 if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
21930 new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
21932 if( new_size==pH->htsize ) return 0;
21933 #endif
21935 /* The inability to allocates space for a larger hash table is
21936 ** a performance hit but it is not a fatal error. So mark the
21937 ** allocation as a benign.
21939 sqlite3BeginBenignMalloc();
21940 new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
21941 sqlite3EndBenignMalloc();
21943 if( new_ht==0 ) return 0;
21944 sqlite3_free(pH->ht);
21945 pH->ht = new_ht;
21946 pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
21947 memset(new_ht, 0, new_size*sizeof(struct _ht));
21948 for(elem=pH->first, pH->first=0; elem; elem = next_elem){
21949 unsigned int h = strHash(elem->pKey, elem->nKey) % new_size;
21950 next_elem = elem->next;
21951 insertElement(pH, &new_ht[h], elem);
21953 return 1;
21956 /* This function (for internal use only) locates an element in an
21957 ** hash table that matches the given key. The hash for this key has
21958 ** already been computed and is passed as the 4th parameter.
21960 static HashElem *findElementGivenHash(
21961 const Hash *pH, /* The pH to be searched */
21962 const char *pKey, /* The key we are searching for */
21963 int nKey, /* Bytes in key (not counting zero terminator) */
21964 unsigned int h /* The hash for this key. */
21966 HashElem *elem; /* Used to loop thru the element list */
21967 int count; /* Number of elements left to test */
21969 if( pH->ht ){
21970 struct _ht *pEntry = &pH->ht[h];
21971 elem = pEntry->chain;
21972 count = pEntry->count;
21973 }else{
21974 elem = pH->first;
21975 count = pH->count;
21977 while( count-- && ALWAYS(elem) ){
21978 if( elem->nKey==nKey && sqlite3StrNICmp(elem->pKey,pKey,nKey)==0 ){
21979 return elem;
21981 elem = elem->next;
21983 return 0;
21986 /* Remove a single entry from the hash table given a pointer to that
21987 ** element and a hash on the element's key.
21989 static void removeElementGivenHash(
21990 Hash *pH, /* The pH containing "elem" */
21991 HashElem* elem, /* The element to be removed from the pH */
21992 unsigned int h /* Hash value for the element */
21994 struct _ht *pEntry;
21995 if( elem->prev ){
21996 elem->prev->next = elem->next;
21997 }else{
21998 pH->first = elem->next;
22000 if( elem->next ){
22001 elem->next->prev = elem->prev;
22003 if( pH->ht ){
22004 pEntry = &pH->ht[h];
22005 if( pEntry->chain==elem ){
22006 pEntry->chain = elem->next;
22008 pEntry->count--;
22009 assert( pEntry->count>=0 );
22011 sqlite3_free( elem );
22012 pH->count--;
22013 if( pH->count<=0 ){
22014 assert( pH->first==0 );
22015 assert( pH->count==0 );
22016 sqlite3HashClear(pH);
22020 /* Attempt to locate an element of the hash table pH with a key
22021 ** that matches pKey,nKey. Return the data for this element if it is
22022 ** found, or NULL if there is no match.
22024 SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey, int nKey){
22025 HashElem *elem; /* The element that matches key */
22026 unsigned int h; /* A hash on key */
22028 assert( pH!=0 );
22029 assert( pKey!=0 );
22030 assert( nKey>=0 );
22031 if( pH->ht ){
22032 h = strHash(pKey, nKey) % pH->htsize;
22033 }else{
22034 h = 0;
22036 elem = findElementGivenHash(pH, pKey, nKey, h);
22037 return elem ? elem->data : 0;
22040 /* Insert an element into the hash table pH. The key is pKey,nKey
22041 ** and the data is "data".
22043 ** If no element exists with a matching key, then a new
22044 ** element is created and NULL is returned.
22046 ** If another element already exists with the same key, then the
22047 ** new data replaces the old data and the old data is returned.
22048 ** The key is not copied in this instance. If a malloc fails, then
22049 ** the new data is returned and the hash table is unchanged.
22051 ** If the "data" parameter to this function is NULL, then the
22052 ** element corresponding to "key" is removed from the hash table.
22054 SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, int nKey, void *data){
22055 unsigned int h; /* the hash of the key modulo hash table size */
22056 HashElem *elem; /* Used to loop thru the element list */
22057 HashElem *new_elem; /* New element added to the pH */
22059 assert( pH!=0 );
22060 assert( pKey!=0 );
22061 assert( nKey>=0 );
22062 if( pH->htsize ){
22063 h = strHash(pKey, nKey) % pH->htsize;
22064 }else{
22065 h = 0;
22067 elem = findElementGivenHash(pH,pKey,nKey,h);
22068 if( elem ){
22069 void *old_data = elem->data;
22070 if( data==0 ){
22071 removeElementGivenHash(pH,elem,h);
22072 }else{
22073 elem->data = data;
22074 elem->pKey = pKey;
22075 assert(nKey==elem->nKey);
22077 return old_data;
22079 if( data==0 ) return 0;
22080 new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
22081 if( new_elem==0 ) return data;
22082 new_elem->pKey = pKey;
22083 new_elem->nKey = nKey;
22084 new_elem->data = data;
22085 pH->count++;
22086 if( pH->count>=10 && pH->count > 2*pH->htsize ){
22087 if( rehash(pH, pH->count*2) ){
22088 assert( pH->htsize>0 );
22089 h = strHash(pKey, nKey) % pH->htsize;
22092 if( pH->ht ){
22093 insertElement(pH, &pH->ht[h], new_elem);
22094 }else{
22095 insertElement(pH, 0, new_elem);
22097 return 0;
22100 /************** End of hash.c ************************************************/
22101 /************** Begin file opcodes.c *****************************************/
22102 /* Automatically generated. Do not edit */
22103 /* See the mkopcodec.awk script for details. */
22104 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
22105 SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
22106 static const char *const azName[] = { "?",
22107 /* 1 */ "Goto",
22108 /* 2 */ "Gosub",
22109 /* 3 */ "Return",
22110 /* 4 */ "Yield",
22111 /* 5 */ "HaltIfNull",
22112 /* 6 */ "Halt",
22113 /* 7 */ "Integer",
22114 /* 8 */ "Int64",
22115 /* 9 */ "String",
22116 /* 10 */ "Null",
22117 /* 11 */ "Blob",
22118 /* 12 */ "Variable",
22119 /* 13 */ "Move",
22120 /* 14 */ "Copy",
22121 /* 15 */ "SCopy",
22122 /* 16 */ "ResultRow",
22123 /* 17 */ "CollSeq",
22124 /* 18 */ "Function",
22125 /* 19 */ "Not",
22126 /* 20 */ "AddImm",
22127 /* 21 */ "MustBeInt",
22128 /* 22 */ "RealAffinity",
22129 /* 23 */ "Permutation",
22130 /* 24 */ "Compare",
22131 /* 25 */ "Jump",
22132 /* 26 */ "Once",
22133 /* 27 */ "If",
22134 /* 28 */ "IfNot",
22135 /* 29 */ "Column",
22136 /* 30 */ "Affinity",
22137 /* 31 */ "MakeRecord",
22138 /* 32 */ "Count",
22139 /* 33 */ "Savepoint",
22140 /* 34 */ "AutoCommit",
22141 /* 35 */ "Transaction",
22142 /* 36 */ "ReadCookie",
22143 /* 37 */ "SetCookie",
22144 /* 38 */ "VerifyCookie",
22145 /* 39 */ "OpenRead",
22146 /* 40 */ "OpenWrite",
22147 /* 41 */ "OpenAutoindex",
22148 /* 42 */ "OpenEphemeral",
22149 /* 43 */ "SorterOpen",
22150 /* 44 */ "OpenPseudo",
22151 /* 45 */ "Close",
22152 /* 46 */ "SeekLt",
22153 /* 47 */ "SeekLe",
22154 /* 48 */ "SeekGe",
22155 /* 49 */ "SeekGt",
22156 /* 50 */ "Seek",
22157 /* 51 */ "NotFound",
22158 /* 52 */ "Found",
22159 /* 53 */ "IsUnique",
22160 /* 54 */ "NotExists",
22161 /* 55 */ "Sequence",
22162 /* 56 */ "NewRowid",
22163 /* 57 */ "Insert",
22164 /* 58 */ "InsertInt",
22165 /* 59 */ "Delete",
22166 /* 60 */ "ResetCount",
22167 /* 61 */ "SorterCompare",
22168 /* 62 */ "SorterData",
22169 /* 63 */ "RowKey",
22170 /* 64 */ "RowData",
22171 /* 65 */ "Rowid",
22172 /* 66 */ "NullRow",
22173 /* 67 */ "Last",
22174 /* 68 */ "Or",
22175 /* 69 */ "And",
22176 /* 70 */ "SorterSort",
22177 /* 71 */ "Sort",
22178 /* 72 */ "Rewind",
22179 /* 73 */ "IsNull",
22180 /* 74 */ "NotNull",
22181 /* 75 */ "Ne",
22182 /* 76 */ "Eq",
22183 /* 77 */ "Gt",
22184 /* 78 */ "Le",
22185 /* 79 */ "Lt",
22186 /* 80 */ "Ge",
22187 /* 81 */ "SorterNext",
22188 /* 82 */ "BitAnd",
22189 /* 83 */ "BitOr",
22190 /* 84 */ "ShiftLeft",
22191 /* 85 */ "ShiftRight",
22192 /* 86 */ "Add",
22193 /* 87 */ "Subtract",
22194 /* 88 */ "Multiply",
22195 /* 89 */ "Divide",
22196 /* 90 */ "Remainder",
22197 /* 91 */ "Concat",
22198 /* 92 */ "Prev",
22199 /* 93 */ "BitNot",
22200 /* 94 */ "String8",
22201 /* 95 */ "Next",
22202 /* 96 */ "SorterInsert",
22203 /* 97 */ "IdxInsert",
22204 /* 98 */ "IdxDelete",
22205 /* 99 */ "IdxRowid",
22206 /* 100 */ "IdxLT",
22207 /* 101 */ "IdxGE",
22208 /* 102 */ "Destroy",
22209 /* 103 */ "Clear",
22210 /* 104 */ "CreateIndex",
22211 /* 105 */ "CreateTable",
22212 /* 106 */ "ParseSchema",
22213 /* 107 */ "LoadAnalysis",
22214 /* 108 */ "DropTable",
22215 /* 109 */ "DropIndex",
22216 /* 110 */ "DropTrigger",
22217 /* 111 */ "IntegrityCk",
22218 /* 112 */ "RowSetAdd",
22219 /* 113 */ "RowSetRead",
22220 /* 114 */ "RowSetTest",
22221 /* 115 */ "Program",
22222 /* 116 */ "Param",
22223 /* 117 */ "FkCounter",
22224 /* 118 */ "FkIfZero",
22225 /* 119 */ "MemMax",
22226 /* 120 */ "IfPos",
22227 /* 121 */ "IfNeg",
22228 /* 122 */ "IfZero",
22229 /* 123 */ "AggStep",
22230 /* 124 */ "AggFinal",
22231 /* 125 */ "Checkpoint",
22232 /* 126 */ "JournalMode",
22233 /* 127 */ "Vacuum",
22234 /* 128 */ "IncrVacuum",
22235 /* 129 */ "Expire",
22236 /* 130 */ "Real",
22237 /* 131 */ "TableLock",
22238 /* 132 */ "VBegin",
22239 /* 133 */ "VCreate",
22240 /* 134 */ "VDestroy",
22241 /* 135 */ "VOpen",
22242 /* 136 */ "VFilter",
22243 /* 137 */ "VColumn",
22244 /* 138 */ "VNext",
22245 /* 139 */ "VRename",
22246 /* 140 */ "VUpdate",
22247 /* 141 */ "ToText",
22248 /* 142 */ "ToBlob",
22249 /* 143 */ "ToNumeric",
22250 /* 144 */ "ToInt",
22251 /* 145 */ "ToReal",
22252 /* 146 */ "Pagecount",
22253 /* 147 */ "MaxPgcnt",
22254 /* 148 */ "Trace",
22255 /* 149 */ "Noop",
22256 /* 150 */ "Explain",
22258 return azName[i];
22260 #endif
22262 /************** End of opcodes.c *********************************************/
22263 /************** Begin file os_os2.c ******************************************/
22265 ** 2006 Feb 14
22267 ** The author disclaims copyright to this source code. In place of
22268 ** a legal notice, here is a blessing:
22270 ** May you do good and not evil.
22271 ** May you find forgiveness for yourself and forgive others.
22272 ** May you share freely, never taking more than you give.
22274 ******************************************************************************
22276 ** This file contains code that is specific to OS/2.
22280 #if SQLITE_OS_OS2
22283 ** A Note About Memory Allocation:
22285 ** This driver uses malloc()/free() directly rather than going through
22286 ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free(). Those wrappers
22287 ** are designed for use on embedded systems where memory is scarce and
22288 ** malloc failures happen frequently. OS/2 does not typically run on
22289 ** embedded systems, and when it does the developers normally have bigger
22290 ** problems to worry about than running out of memory. So there is not
22291 ** a compelling need to use the wrappers.
22293 ** But there is a good reason to not use the wrappers. If we use the
22294 ** wrappers then we will get simulated malloc() failures within this
22295 ** driver. And that causes all kinds of problems for our tests. We
22296 ** could enhance SQLite to deal with simulated malloc failures within
22297 ** the OS driver, but the code to deal with those failure would not
22298 ** be exercised on Linux (which does not need to malloc() in the driver)
22299 ** and so we would have difficulty writing coverage tests for that
22300 ** code. Better to leave the code out, we think.
22302 ** The point of this discussion is as follows: When creating a new
22303 ** OS layer for an embedded system, if you use this file as an example,
22304 ** avoid the use of malloc()/free(). Those routines work ok on OS/2
22305 ** desktops but not so well in embedded systems.
22309 ** Macros used to determine whether or not to use threads.
22311 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE
22312 # define SQLITE_OS2_THREADS 1
22313 #endif
22316 ** Include code that is common to all os_*.c files
22318 /************** Include os_common.h in the middle of os_os2.c ****************/
22319 /************** Begin file os_common.h ***************************************/
22321 ** 2004 May 22
22323 ** The author disclaims copyright to this source code. In place of
22324 ** a legal notice, here is a blessing:
22326 ** May you do good and not evil.
22327 ** May you find forgiveness for yourself and forgive others.
22328 ** May you share freely, never taking more than you give.
22330 ******************************************************************************
22332 ** This file contains macros and a little bit of code that is common to
22333 ** all of the platform-specific files (os_*.c) and is #included into those
22334 ** files.
22336 ** This file should be #included by the os_*.c files only. It is not a
22337 ** general purpose header file.
22339 #ifndef _OS_COMMON_H_
22340 #define _OS_COMMON_H_
22343 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
22344 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
22345 ** switch. The following code should catch this problem at compile-time.
22347 #ifdef MEMORY_DEBUG
22348 # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
22349 #endif
22351 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
22352 # ifndef SQLITE_DEBUG_OS_TRACE
22353 # define SQLITE_DEBUG_OS_TRACE 0
22354 # endif
22355 int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
22356 # define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
22357 #else
22358 # define OSTRACE(X)
22359 #endif
22362 ** Macros for performance tracing. Normally turned off. Only works
22363 ** on i486 hardware.
22365 #ifdef SQLITE_PERFORMANCE_TRACE
22368 ** hwtime.h contains inline assembler code for implementing
22369 ** high-performance timing routines.
22371 /************** Include hwtime.h in the middle of os_common.h ****************/
22372 /************** Begin file hwtime.h ******************************************/
22374 ** 2008 May 27
22376 ** The author disclaims copyright to this source code. In place of
22377 ** a legal notice, here is a blessing:
22379 ** May you do good and not evil.
22380 ** May you find forgiveness for yourself and forgive others.
22381 ** May you share freely, never taking more than you give.
22383 ******************************************************************************
22385 ** This file contains inline asm code for retrieving "high-performance"
22386 ** counters for x86 class CPUs.
22388 #ifndef _HWTIME_H_
22389 #define _HWTIME_H_
22392 ** The following routine only works on pentium-class (or newer) processors.
22393 ** It uses the RDTSC opcode to read the cycle count value out of the
22394 ** processor and returns that value. This can be used for high-res
22395 ** profiling.
22397 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
22398 (defined(i386) || defined(__i386__) || defined(_M_IX86))
22400 #if defined(__GNUC__)
22402 __inline__ sqlite_uint64 sqlite3Hwtime(void){
22403 unsigned int lo, hi;
22404 __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
22405 return (sqlite_uint64)hi << 32 | lo;
22408 #elif defined(_MSC_VER)
22410 __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
22411 __asm {
22412 rdtsc
22413 ret ; return value at EDX:EAX
22417 #endif
22419 #elif (defined(__GNUC__) && defined(__x86_64__))
22421 __inline__ sqlite_uint64 sqlite3Hwtime(void){
22422 unsigned long val;
22423 __asm__ __volatile__ ("rdtsc" : "=A" (val));
22424 return val;
22427 #elif (defined(__GNUC__) && defined(__ppc__))
22429 __inline__ sqlite_uint64 sqlite3Hwtime(void){
22430 unsigned long long retval;
22431 unsigned long junk;
22432 __asm__ __volatile__ ("\n\
22433 1: mftbu %1\n\
22434 mftb %L0\n\
22435 mftbu %0\n\
22436 cmpw %0,%1\n\
22437 bne 1b"
22438 : "=r" (retval), "=r" (junk));
22439 return retval;
22442 #else
22444 #error Need implementation of sqlite3Hwtime() for your platform.
22447 ** To compile without implementing sqlite3Hwtime() for your platform,
22448 ** you can remove the above #error and use the following
22449 ** stub function. You will lose timing support for many
22450 ** of the debugging and testing utilities, but it should at
22451 ** least compile and run.
22453 SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
22455 #endif
22457 #endif /* !defined(_HWTIME_H_) */
22459 /************** End of hwtime.h **********************************************/
22460 /************** Continuing where we left off in os_common.h ******************/
22462 static sqlite_uint64 g_start;
22463 static sqlite_uint64 g_elapsed;
22464 #define TIMER_START g_start=sqlite3Hwtime()
22465 #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
22466 #define TIMER_ELAPSED g_elapsed
22467 #else
22468 #define TIMER_START
22469 #define TIMER_END
22470 #define TIMER_ELAPSED ((sqlite_uint64)0)
22471 #endif
22474 ** If we compile with the SQLITE_TEST macro set, then the following block
22475 ** of code will give us the ability to simulate a disk I/O error. This
22476 ** is used for testing the I/O recovery logic.
22478 #ifdef SQLITE_TEST
22479 SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
22480 SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
22481 SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
22482 SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
22483 SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
22484 SQLITE_API int sqlite3_diskfull_pending = 0;
22485 SQLITE_API int sqlite3_diskfull = 0;
22486 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
22487 #define SimulateIOError(CODE) \
22488 if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
22489 || sqlite3_io_error_pending-- == 1 ) \
22490 { local_ioerr(); CODE; }
22491 static void local_ioerr(){
22492 IOTRACE(("IOERR\n"));
22493 sqlite3_io_error_hit++;
22494 if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
22496 #define SimulateDiskfullError(CODE) \
22497 if( sqlite3_diskfull_pending ){ \
22498 if( sqlite3_diskfull_pending == 1 ){ \
22499 local_ioerr(); \
22500 sqlite3_diskfull = 1; \
22501 sqlite3_io_error_hit = 1; \
22502 CODE; \
22503 }else{ \
22504 sqlite3_diskfull_pending--; \
22507 #else
22508 #define SimulateIOErrorBenign(X)
22509 #define SimulateIOError(A)
22510 #define SimulateDiskfullError(A)
22511 #endif
22514 ** When testing, keep a count of the number of open files.
22516 #ifdef SQLITE_TEST
22517 SQLITE_API int sqlite3_open_file_count = 0;
22518 #define OpenCounter(X) sqlite3_open_file_count+=(X)
22519 #else
22520 #define OpenCounter(X)
22521 #endif
22523 #endif /* !defined(_OS_COMMON_H_) */
22525 /************** End of os_common.h *******************************************/
22526 /************** Continuing where we left off in os_os2.c *********************/
22528 /* Forward references */
22529 typedef struct os2File os2File; /* The file structure */
22530 typedef struct os2ShmNode os2ShmNode; /* A shared descritive memory node */
22531 typedef struct os2ShmLink os2ShmLink; /* A connection to shared-memory */
22534 ** The os2File structure is subclass of sqlite3_file specific for the OS/2
22535 ** protability layer.
22537 struct os2File {
22538 const sqlite3_io_methods *pMethod; /* Always the first entry */
22539 HFILE h; /* Handle for accessing the file */
22540 int flags; /* Flags provided to os2Open() */
22541 int locktype; /* Type of lock currently held on this file */
22542 int szChunk; /* Chunk size configured by FCNTL_CHUNK_SIZE */
22543 char *zFullPathCp; /* Full path name of this file */
22544 os2ShmLink *pShmLink; /* Instance of shared memory on this file */
22547 #define LOCK_TIMEOUT 10L /* the default locking timeout */
22550 ** Missing from some versions of the OS/2 toolkit -
22551 ** used to allocate from high memory if possible
22553 #ifndef OBJ_ANY
22554 # define OBJ_ANY 0x00000400
22555 #endif
22557 /*****************************************************************************
22558 ** The next group of routines implement the I/O methods specified
22559 ** by the sqlite3_io_methods object.
22560 ******************************************************************************/
22563 ** Close a file.
22565 static int os2Close( sqlite3_file *id ){
22566 APIRET rc;
22567 os2File *pFile = (os2File*)id;
22569 assert( id!=0 );
22570 OSTRACE(( "CLOSE %d (%s)\n", pFile->h, pFile->zFullPathCp ));
22572 rc = DosClose( pFile->h );
22574 if( pFile->flags & SQLITE_OPEN_DELETEONCLOSE )
22575 DosForceDelete( (PSZ)pFile->zFullPathCp );
22577 free( pFile->zFullPathCp );
22578 pFile->zFullPathCp = NULL;
22579 pFile->locktype = NO_LOCK;
22580 pFile->h = (HFILE)-1;
22581 pFile->flags = 0;
22583 OpenCounter( -1 );
22584 return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
22588 ** Read data from a file into a buffer. Return SQLITE_OK if all
22589 ** bytes were read successfully and SQLITE_IOERR if anything goes
22590 ** wrong.
22592 static int os2Read(
22593 sqlite3_file *id, /* File to read from */
22594 void *pBuf, /* Write content into this buffer */
22595 int amt, /* Number of bytes to read */
22596 sqlite3_int64 offset /* Begin reading at this offset */
22598 ULONG fileLocation = 0L;
22599 ULONG got;
22600 os2File *pFile = (os2File*)id;
22601 assert( id!=0 );
22602 SimulateIOError( return SQLITE_IOERR_READ );
22603 OSTRACE(( "READ %d lock=%d\n", pFile->h, pFile->locktype ));
22604 if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
22605 return SQLITE_IOERR;
22607 if( DosRead( pFile->h, pBuf, amt, &got ) != NO_ERROR ){
22608 return SQLITE_IOERR_READ;
22610 if( got == (ULONG)amt )
22611 return SQLITE_OK;
22612 else {
22613 /* Unread portions of the input buffer must be zero-filled */
22614 memset(&((char*)pBuf)[got], 0, amt-got);
22615 return SQLITE_IOERR_SHORT_READ;
22620 ** Write data from a buffer into a file. Return SQLITE_OK on success
22621 ** or some other error code on failure.
22623 static int os2Write(
22624 sqlite3_file *id, /* File to write into */
22625 const void *pBuf, /* The bytes to be written */
22626 int amt, /* Number of bytes to write */
22627 sqlite3_int64 offset /* Offset into the file to begin writing at */
22629 ULONG fileLocation = 0L;
22630 APIRET rc = NO_ERROR;
22631 ULONG wrote;
22632 os2File *pFile = (os2File*)id;
22633 assert( id!=0 );
22634 SimulateIOError( return SQLITE_IOERR_WRITE );
22635 SimulateDiskfullError( return SQLITE_FULL );
22636 OSTRACE(( "WRITE %d lock=%d\n", pFile->h, pFile->locktype ));
22637 if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
22638 return SQLITE_IOERR;
22640 assert( amt>0 );
22641 while( amt > 0 &&
22642 ( rc = DosWrite( pFile->h, (PVOID)pBuf, amt, &wrote ) ) == NO_ERROR &&
22643 wrote > 0
22645 amt -= wrote;
22646 pBuf = &((char*)pBuf)[wrote];
22649 return ( rc != NO_ERROR || amt > (int)wrote ) ? SQLITE_FULL : SQLITE_OK;
22653 ** Truncate an open file to a specified size
22655 static int os2Truncate( sqlite3_file *id, i64 nByte ){
22656 APIRET rc;
22657 os2File *pFile = (os2File*)id;
22658 assert( id!=0 );
22659 OSTRACE(( "TRUNCATE %d %lld\n", pFile->h, nByte ));
22660 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
22662 /* If the user has configured a chunk-size for this file, truncate the
22663 ** file so that it consists of an integer number of chunks (i.e. the
22664 ** actual file size after the operation may be larger than the requested
22665 ** size).
22667 if( pFile->szChunk ){
22668 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
22671 rc = DosSetFileSize( pFile->h, nByte );
22672 return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_TRUNCATE;
22675 #ifdef SQLITE_TEST
22677 ** Count the number of fullsyncs and normal syncs. This is used to test
22678 ** that syncs and fullsyncs are occuring at the right times.
22680 SQLITE_API int sqlite3_sync_count = 0;
22681 SQLITE_API int sqlite3_fullsync_count = 0;
22682 #endif
22685 ** Make sure all writes to a particular file are committed to disk.
22687 static int os2Sync( sqlite3_file *id, int flags ){
22688 os2File *pFile = (os2File*)id;
22689 OSTRACE(( "SYNC %d lock=%d\n", pFile->h, pFile->locktype ));
22690 #ifdef SQLITE_TEST
22691 if( flags & SQLITE_SYNC_FULL){
22692 sqlite3_fullsync_count++;
22694 sqlite3_sync_count++;
22695 #endif
22696 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
22697 ** no-op
22699 #ifdef SQLITE_NO_SYNC
22700 UNUSED_PARAMETER(pFile);
22701 return SQLITE_OK;
22702 #else
22703 return DosResetBuffer( pFile->h ) == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
22704 #endif
22708 ** Determine the current size of a file in bytes
22710 static int os2FileSize( sqlite3_file *id, sqlite3_int64 *pSize ){
22711 APIRET rc = NO_ERROR;
22712 FILESTATUS3 fsts3FileInfo;
22713 memset(&fsts3FileInfo, 0, sizeof(fsts3FileInfo));
22714 assert( id!=0 );
22715 SimulateIOError( return SQLITE_IOERR_FSTAT );
22716 rc = DosQueryFileInfo( ((os2File*)id)->h, FIL_STANDARD, &fsts3FileInfo, sizeof(FILESTATUS3) );
22717 if( rc == NO_ERROR ){
22718 *pSize = fsts3FileInfo.cbFile;
22719 return SQLITE_OK;
22720 }else{
22721 return SQLITE_IOERR_FSTAT;
22726 ** Acquire a reader lock.
22728 static int getReadLock( os2File *pFile ){
22729 FILELOCK LockArea,
22730 UnlockArea;
22731 APIRET res;
22732 memset(&LockArea, 0, sizeof(LockArea));
22733 memset(&UnlockArea, 0, sizeof(UnlockArea));
22734 LockArea.lOffset = SHARED_FIRST;
22735 LockArea.lRange = SHARED_SIZE;
22736 UnlockArea.lOffset = 0L;
22737 UnlockArea.lRange = 0L;
22738 res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
22739 OSTRACE(( "GETREADLOCK %d res=%d\n", pFile->h, res ));
22740 return res;
22744 ** Undo a readlock
22746 static int unlockReadLock( os2File *id ){
22747 FILELOCK LockArea,
22748 UnlockArea;
22749 APIRET res;
22750 memset(&LockArea, 0, sizeof(LockArea));
22751 memset(&UnlockArea, 0, sizeof(UnlockArea));
22752 LockArea.lOffset = 0L;
22753 LockArea.lRange = 0L;
22754 UnlockArea.lOffset = SHARED_FIRST;
22755 UnlockArea.lRange = SHARED_SIZE;
22756 res = DosSetFileLocks( id->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
22757 OSTRACE(( "UNLOCK-READLOCK file handle=%d res=%d?\n", id->h, res ));
22758 return res;
22762 ** Lock the file with the lock specified by parameter locktype - one
22763 ** of the following:
22765 ** (1) SHARED_LOCK
22766 ** (2) RESERVED_LOCK
22767 ** (3) PENDING_LOCK
22768 ** (4) EXCLUSIVE_LOCK
22770 ** Sometimes when requesting one lock state, additional lock states
22771 ** are inserted in between. The locking might fail on one of the later
22772 ** transitions leaving the lock state different from what it started but
22773 ** still short of its goal. The following chart shows the allowed
22774 ** transitions and the inserted intermediate states:
22776 ** UNLOCKED -> SHARED
22777 ** SHARED -> RESERVED
22778 ** SHARED -> (PENDING) -> EXCLUSIVE
22779 ** RESERVED -> (PENDING) -> EXCLUSIVE
22780 ** PENDING -> EXCLUSIVE
22782 ** This routine will only increase a lock. The os2Unlock() routine
22783 ** erases all locks at once and returns us immediately to locking level 0.
22784 ** It is not possible to lower the locking level one step at a time. You
22785 ** must go straight to locking level 0.
22787 static int os2Lock( sqlite3_file *id, int locktype ){
22788 int rc = SQLITE_OK; /* Return code from subroutines */
22789 APIRET res = NO_ERROR; /* Result of an OS/2 lock call */
22790 int newLocktype; /* Set pFile->locktype to this value before exiting */
22791 int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
22792 FILELOCK LockArea,
22793 UnlockArea;
22794 os2File *pFile = (os2File*)id;
22795 memset(&LockArea, 0, sizeof(LockArea));
22796 memset(&UnlockArea, 0, sizeof(UnlockArea));
22797 assert( pFile!=0 );
22798 OSTRACE(( "LOCK %d %d was %d\n", pFile->h, locktype, pFile->locktype ));
22800 /* If there is already a lock of this type or more restrictive on the
22801 ** os2File, do nothing. Don't use the end_lock: exit path, as
22802 ** sqlite3_mutex_enter() hasn't been called yet.
22804 if( pFile->locktype>=locktype ){
22805 OSTRACE(( "LOCK %d %d ok (already held)\n", pFile->h, locktype ));
22806 return SQLITE_OK;
22809 /* Make sure the locking sequence is correct
22811 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
22812 assert( locktype!=PENDING_LOCK );
22813 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
22815 /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
22816 ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of
22817 ** the PENDING_LOCK byte is temporary.
22819 newLocktype = pFile->locktype;
22820 if( pFile->locktype==NO_LOCK
22821 || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)
22823 LockArea.lOffset = PENDING_BYTE;
22824 LockArea.lRange = 1L;
22825 UnlockArea.lOffset = 0L;
22826 UnlockArea.lRange = 0L;
22828 /* wait longer than LOCK_TIMEOUT here not to have to try multiple times */
22829 res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 100L, 0L );
22830 if( res == NO_ERROR ){
22831 gotPendingLock = 1;
22832 OSTRACE(( "LOCK %d pending lock boolean set. res=%d\n", pFile->h, res ));
22836 /* Acquire a shared lock
22838 if( locktype==SHARED_LOCK && res == NO_ERROR ){
22839 assert( pFile->locktype==NO_LOCK );
22840 res = getReadLock(pFile);
22841 if( res == NO_ERROR ){
22842 newLocktype = SHARED_LOCK;
22844 OSTRACE(( "LOCK %d acquire shared lock. res=%d\n", pFile->h, res ));
22847 /* Acquire a RESERVED lock
22849 if( locktype==RESERVED_LOCK && res == NO_ERROR ){
22850 assert( pFile->locktype==SHARED_LOCK );
22851 LockArea.lOffset = RESERVED_BYTE;
22852 LockArea.lRange = 1L;
22853 UnlockArea.lOffset = 0L;
22854 UnlockArea.lRange = 0L;
22855 res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22856 if( res == NO_ERROR ){
22857 newLocktype = RESERVED_LOCK;
22859 OSTRACE(( "LOCK %d acquire reserved lock. res=%d\n", pFile->h, res ));
22862 /* Acquire a PENDING lock
22864 if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
22865 newLocktype = PENDING_LOCK;
22866 gotPendingLock = 0;
22867 OSTRACE(( "LOCK %d acquire pending lock. pending lock boolean unset.\n",
22868 pFile->h ));
22871 /* Acquire an EXCLUSIVE lock
22873 if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
22874 assert( pFile->locktype>=SHARED_LOCK );
22875 res = unlockReadLock(pFile);
22876 OSTRACE(( "unreadlock = %d\n", res ));
22877 LockArea.lOffset = SHARED_FIRST;
22878 LockArea.lRange = SHARED_SIZE;
22879 UnlockArea.lOffset = 0L;
22880 UnlockArea.lRange = 0L;
22881 res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22882 if( res == NO_ERROR ){
22883 newLocktype = EXCLUSIVE_LOCK;
22884 }else{
22885 OSTRACE(( "OS/2 error-code = %d\n", res ));
22886 getReadLock(pFile);
22888 OSTRACE(( "LOCK %d acquire exclusive lock. res=%d\n", pFile->h, res ));
22891 /* If we are holding a PENDING lock that ought to be released, then
22892 ** release it now.
22894 if( gotPendingLock && locktype==SHARED_LOCK ){
22895 int r;
22896 LockArea.lOffset = 0L;
22897 LockArea.lRange = 0L;
22898 UnlockArea.lOffset = PENDING_BYTE;
22899 UnlockArea.lRange = 1L;
22900 r = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22901 OSTRACE(( "LOCK %d unlocking pending/is shared. r=%d\n", pFile->h, r ));
22904 /* Update the state of the lock has held in the file descriptor then
22905 ** return the appropriate result code.
22907 if( res == NO_ERROR ){
22908 rc = SQLITE_OK;
22909 }else{
22910 OSTRACE(( "LOCK FAILED %d trying for %d but got %d\n", pFile->h,
22911 locktype, newLocktype ));
22912 rc = SQLITE_BUSY;
22914 pFile->locktype = newLocktype;
22915 OSTRACE(( "LOCK %d now %d\n", pFile->h, pFile->locktype ));
22916 return rc;
22920 ** This routine checks if there is a RESERVED lock held on the specified
22921 ** file by this or any other process. If such a lock is held, return
22922 ** non-zero, otherwise zero.
22924 static int os2CheckReservedLock( sqlite3_file *id, int *pOut ){
22925 int r = 0;
22926 os2File *pFile = (os2File*)id;
22927 assert( pFile!=0 );
22928 if( pFile->locktype>=RESERVED_LOCK ){
22929 r = 1;
22930 OSTRACE(( "TEST WR-LOCK %d %d (local)\n", pFile->h, r ));
22931 }else{
22932 FILELOCK LockArea,
22933 UnlockArea;
22934 APIRET rc = NO_ERROR;
22935 memset(&LockArea, 0, sizeof(LockArea));
22936 memset(&UnlockArea, 0, sizeof(UnlockArea));
22937 LockArea.lOffset = RESERVED_BYTE;
22938 LockArea.lRange = 1L;
22939 UnlockArea.lOffset = 0L;
22940 UnlockArea.lRange = 0L;
22941 rc = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22942 OSTRACE(( "TEST WR-LOCK %d lock reserved byte rc=%d\n", pFile->h, rc ));
22943 if( rc == NO_ERROR ){
22944 APIRET rcu = NO_ERROR; /* return code for unlocking */
22945 LockArea.lOffset = 0L;
22946 LockArea.lRange = 0L;
22947 UnlockArea.lOffset = RESERVED_BYTE;
22948 UnlockArea.lRange = 1L;
22949 rcu = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22950 OSTRACE(( "TEST WR-LOCK %d unlock reserved byte r=%d\n", pFile->h, rcu ));
22952 r = !(rc == NO_ERROR);
22953 OSTRACE(( "TEST WR-LOCK %d %d (remote)\n", pFile->h, r ));
22955 *pOut = r;
22956 return SQLITE_OK;
22960 ** Lower the locking level on file descriptor id to locktype. locktype
22961 ** must be either NO_LOCK or SHARED_LOCK.
22963 ** If the locking level of the file descriptor is already at or below
22964 ** the requested locking level, this routine is a no-op.
22966 ** It is not possible for this routine to fail if the second argument
22967 ** is NO_LOCK. If the second argument is SHARED_LOCK then this routine
22968 ** might return SQLITE_IOERR;
22970 static int os2Unlock( sqlite3_file *id, int locktype ){
22971 int type;
22972 os2File *pFile = (os2File*)id;
22973 APIRET rc = SQLITE_OK;
22974 APIRET res = NO_ERROR;
22975 FILELOCK LockArea,
22976 UnlockArea;
22977 memset(&LockArea, 0, sizeof(LockArea));
22978 memset(&UnlockArea, 0, sizeof(UnlockArea));
22979 assert( pFile!=0 );
22980 assert( locktype<=SHARED_LOCK );
22981 OSTRACE(( "UNLOCK %d to %d was %d\n", pFile->h, locktype, pFile->locktype ));
22982 type = pFile->locktype;
22983 if( type>=EXCLUSIVE_LOCK ){
22984 LockArea.lOffset = 0L;
22985 LockArea.lRange = 0L;
22986 UnlockArea.lOffset = SHARED_FIRST;
22987 UnlockArea.lRange = SHARED_SIZE;
22988 res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22989 OSTRACE(( "UNLOCK %d exclusive lock res=%d\n", pFile->h, res ));
22990 if( locktype==SHARED_LOCK && getReadLock(pFile) != NO_ERROR ){
22991 /* This should never happen. We should always be able to
22992 ** reacquire the read lock */
22993 OSTRACE(( "UNLOCK %d to %d getReadLock() failed\n", pFile->h, locktype ));
22994 rc = SQLITE_IOERR_UNLOCK;
22997 if( type>=RESERVED_LOCK ){
22998 LockArea.lOffset = 0L;
22999 LockArea.lRange = 0L;
23000 UnlockArea.lOffset = RESERVED_BYTE;
23001 UnlockArea.lRange = 1L;
23002 res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
23003 OSTRACE(( "UNLOCK %d reserved res=%d\n", pFile->h, res ));
23005 if( locktype==NO_LOCK && type>=SHARED_LOCK ){
23006 res = unlockReadLock(pFile);
23007 OSTRACE(( "UNLOCK %d is %d want %d res=%d\n",
23008 pFile->h, type, locktype, res ));
23010 if( type>=PENDING_LOCK ){
23011 LockArea.lOffset = 0L;
23012 LockArea.lRange = 0L;
23013 UnlockArea.lOffset = PENDING_BYTE;
23014 UnlockArea.lRange = 1L;
23015 res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
23016 OSTRACE(( "UNLOCK %d pending res=%d\n", pFile->h, res ));
23018 pFile->locktype = locktype;
23019 OSTRACE(( "UNLOCK %d now %d\n", pFile->h, pFile->locktype ));
23020 return rc;
23024 ** Control and query of the open file handle.
23026 static int os2FileControl(sqlite3_file *id, int op, void *pArg){
23027 switch( op ){
23028 case SQLITE_FCNTL_LOCKSTATE: {
23029 *(int*)pArg = ((os2File*)id)->locktype;
23030 OSTRACE(( "FCNTL_LOCKSTATE %d lock=%d\n",
23031 ((os2File*)id)->h, ((os2File*)id)->locktype ));
23032 return SQLITE_OK;
23034 case SQLITE_FCNTL_CHUNK_SIZE: {
23035 ((os2File*)id)->szChunk = *(int*)pArg;
23036 return SQLITE_OK;
23038 case SQLITE_FCNTL_SIZE_HINT: {
23039 sqlite3_int64 sz = *(sqlite3_int64*)pArg;
23040 SimulateIOErrorBenign(1);
23041 os2Truncate(id, sz);
23042 SimulateIOErrorBenign(0);
23043 return SQLITE_OK;
23045 case SQLITE_FCNTL_SYNC_OMITTED: {
23046 return SQLITE_OK;
23049 return SQLITE_NOTFOUND;
23053 ** Return the sector size in bytes of the underlying block device for
23054 ** the specified file. This is almost always 512 bytes, but may be
23055 ** larger for some devices.
23057 ** SQLite code assumes this function cannot fail. It also assumes that
23058 ** if two files are created in the same file-system directory (i.e.
23059 ** a database and its journal file) that the sector size will be the
23060 ** same for both.
23062 static int os2SectorSize(sqlite3_file *id){
23063 UNUSED_PARAMETER(id);
23064 return SQLITE_DEFAULT_SECTOR_SIZE;
23068 ** Return a vector of device characteristics.
23070 static int os2DeviceCharacteristics(sqlite3_file *id){
23071 UNUSED_PARAMETER(id);
23072 return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN;
23077 ** Character set conversion objects used by conversion routines.
23079 static UconvObject ucUtf8 = NULL; /* convert between UTF-8 and UCS-2 */
23080 static UconvObject uclCp = NULL; /* convert between local codepage and UCS-2 */
23083 ** Helper function to initialize the conversion objects from and to UTF-8.
23085 static void initUconvObjects( void ){
23086 if( UniCreateUconvObject( UTF_8, &ucUtf8 ) != ULS_SUCCESS )
23087 ucUtf8 = NULL;
23088 if ( UniCreateUconvObject( (UniChar *)L"@path=yes", &uclCp ) != ULS_SUCCESS )
23089 uclCp = NULL;
23093 ** Helper function to free the conversion objects from and to UTF-8.
23095 static void freeUconvObjects( void ){
23096 if ( ucUtf8 )
23097 UniFreeUconvObject( ucUtf8 );
23098 if ( uclCp )
23099 UniFreeUconvObject( uclCp );
23100 ucUtf8 = NULL;
23101 uclCp = NULL;
23105 ** Helper function to convert UTF-8 filenames to local OS/2 codepage.
23106 ** The two-step process: first convert the incoming UTF-8 string
23107 ** into UCS-2 and then from UCS-2 to the current codepage.
23108 ** The returned char pointer has to be freed.
23110 static char *convertUtf8PathToCp( const char *in ){
23111 UniChar tempPath[CCHMAXPATH];
23112 char *out = (char *)calloc( CCHMAXPATH, 1 );
23114 if( !out )
23115 return NULL;
23117 if( !ucUtf8 || !uclCp )
23118 initUconvObjects();
23120 /* determine string for the conversion of UTF-8 which is CP1208 */
23121 if( UniStrToUcs( ucUtf8, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
23122 return out; /* if conversion fails, return the empty string */
23124 /* conversion for current codepage which can be used for paths */
23125 UniStrFromUcs( uclCp, out, tempPath, CCHMAXPATH );
23127 return out;
23131 ** Helper function to convert filenames from local codepage to UTF-8.
23132 ** The two-step process: first convert the incoming codepage-specific
23133 ** string into UCS-2 and then from UCS-2 to the codepage of UTF-8.
23134 ** The returned char pointer has to be freed.
23136 ** This function is non-static to be able to use this in shell.c and
23137 ** similar applications that take command line arguments.
23139 char *convertCpPathToUtf8( const char *in ){
23140 UniChar tempPath[CCHMAXPATH];
23141 char *out = (char *)calloc( CCHMAXPATH, 1 );
23143 if( !out )
23144 return NULL;
23146 if( !ucUtf8 || !uclCp )
23147 initUconvObjects();
23149 /* conversion for current codepage which can be used for paths */
23150 if( UniStrToUcs( uclCp, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
23151 return out; /* if conversion fails, return the empty string */
23153 /* determine string for the conversion of UTF-8 which is CP1208 */
23154 UniStrFromUcs( ucUtf8, out, tempPath, CCHMAXPATH );
23156 return out;
23160 #ifndef SQLITE_OMIT_WAL
23163 ** Use main database file for interprocess locking. If un-defined
23164 ** a separate file is created for this purpose. The file will be
23165 ** used only to set file locks. There will be no data written to it.
23167 #define SQLITE_OS2_NO_WAL_LOCK_FILE
23169 #if 0
23170 static void _ERR_TRACE( const char *fmt, ... ) {
23171 va_list ap;
23172 va_start(ap, fmt);
23173 vfprintf(stderr, fmt, ap);
23174 fflush(stderr);
23176 #define ERR_TRACE(rc, msg) \
23177 if( (rc) != SQLITE_OK ) _ERR_TRACE msg;
23178 #else
23179 #define ERR_TRACE(rc, msg)
23180 #endif
23183 ** Helper functions to obtain and relinquish the global mutex. The
23184 ** global mutex is used to protect os2ShmNodeList.
23186 ** Function os2ShmMutexHeld() is used to assert() that the global mutex
23187 ** is held when required. This function is only used as part of assert()
23188 ** statements. e.g.
23190 ** os2ShmEnterMutex()
23191 ** assert( os2ShmMutexHeld() );
23192 ** os2ShmLeaveMutex()
23194 static void os2ShmEnterMutex(void){
23195 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
23197 static void os2ShmLeaveMutex(void){
23198 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
23200 #ifdef SQLITE_DEBUG
23201 static int os2ShmMutexHeld(void) {
23202 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
23204 int GetCurrentProcessId(void) {
23205 PPIB pib;
23206 DosGetInfoBlocks(NULL, &pib);
23207 return (int)pib->pib_ulpid;
23209 #endif
23212 ** Object used to represent a the shared memory area for a single log file.
23213 ** When multiple threads all reference the same log-summary, each thread has
23214 ** its own os2File object, but they all point to a single instance of this
23215 ** object. In other words, each log-summary is opened only once per process.
23217 ** os2ShmMutexHeld() must be true when creating or destroying
23218 ** this object or while reading or writing the following fields:
23220 ** nRef
23221 ** pNext
23223 ** The following fields are read-only after the object is created:
23225 ** szRegion
23226 ** hLockFile
23227 ** shmBaseName
23229 ** Either os2ShmNode.mutex must be held or os2ShmNode.nRef==0 and
23230 ** os2ShmMutexHeld() is true when reading or writing any other field
23231 ** in this structure.
23234 struct os2ShmNode {
23235 sqlite3_mutex *mutex; /* Mutex to access this object */
23236 os2ShmNode *pNext; /* Next in list of all os2ShmNode objects */
23238 int szRegion; /* Size of shared-memory regions */
23240 int nRegion; /* Size of array apRegion */
23241 void **apRegion; /* Array of pointers to shared-memory regions */
23243 int nRef; /* Number of os2ShmLink objects pointing to this */
23244 os2ShmLink *pFirst; /* First os2ShmLink object pointing to this */
23246 HFILE hLockFile; /* File used for inter-process memory locking */
23247 char shmBaseName[1]; /* Name of the memory object !!! must last !!! */
23252 ** Structure used internally by this VFS to record the state of an
23253 ** open shared memory connection.
23255 ** The following fields are initialized when this object is created and
23256 ** are read-only thereafter:
23258 ** os2Shm.pShmNode
23259 ** os2Shm.id
23261 ** All other fields are read/write. The os2Shm.pShmNode->mutex must be held
23262 ** while accessing any read/write fields.
23264 struct os2ShmLink {
23265 os2ShmNode *pShmNode; /* The underlying os2ShmNode object */
23266 os2ShmLink *pNext; /* Next os2Shm with the same os2ShmNode */
23267 u32 sharedMask; /* Mask of shared locks held */
23268 u32 exclMask; /* Mask of exclusive locks held */
23269 #ifdef SQLITE_DEBUG
23270 u8 id; /* Id of this connection with its os2ShmNode */
23271 #endif
23276 ** A global list of all os2ShmNode objects.
23278 ** The os2ShmMutexHeld() must be true while reading or writing this list.
23280 static os2ShmNode *os2ShmNodeList = NULL;
23283 ** Constants used for locking
23285 #ifdef SQLITE_OS2_NO_WAL_LOCK_FILE
23286 #define OS2_SHM_BASE (PENDING_BYTE + 0x10000) /* first lock byte */
23287 #else
23288 #define OS2_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
23289 #endif
23291 #define OS2_SHM_DMS (OS2_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
23294 ** Apply advisory locks for all n bytes beginning at ofst.
23296 #define _SHM_UNLCK 1 /* no lock */
23297 #define _SHM_RDLCK 2 /* shared lock, no wait */
23298 #define _SHM_WRLCK 3 /* exlusive lock, no wait */
23299 #define _SHM_WRLCK_WAIT 4 /* exclusive lock, wait */
23300 static int os2ShmSystemLock(
23301 os2ShmNode *pNode, /* Apply locks to this open shared-memory segment */
23302 int lockType, /* _SHM_UNLCK, _SHM_RDLCK, _SHM_WRLCK or _SHM_WRLCK_WAIT */
23303 int ofst, /* Offset to first byte to be locked/unlocked */
23304 int nByte /* Number of bytes to lock or unlock */
23306 APIRET rc;
23307 FILELOCK area;
23308 ULONG mode, timeout;
23310 /* Access to the os2ShmNode object is serialized by the caller */
23311 assert( sqlite3_mutex_held(pNode->mutex) || pNode->nRef==0 );
23313 mode = 1; /* shared lock */
23314 timeout = 0; /* no wait */
23315 area.lOffset = ofst;
23316 area.lRange = nByte;
23318 switch( lockType ) {
23319 case _SHM_WRLCK_WAIT:
23320 timeout = (ULONG)-1; /* wait forever */
23321 case _SHM_WRLCK:
23322 mode = 0; /* exclusive lock */
23323 case _SHM_RDLCK:
23324 rc = DosSetFileLocks(pNode->hLockFile,
23325 NULL, &area, timeout, mode);
23326 break;
23327 /* case _SHM_UNLCK: */
23328 default:
23329 rc = DosSetFileLocks(pNode->hLockFile,
23330 &area, NULL, 0, 0);
23331 break;
23334 OSTRACE(("SHM-LOCK %d %s %s 0x%08lx\n",
23335 pNode->hLockFile,
23336 rc==SQLITE_OK ? "ok" : "failed",
23337 lockType==_SHM_UNLCK ? "Unlock" : "Lock",
23338 rc));
23340 ERR_TRACE(rc, ("os2ShmSystemLock: %d %s\n", rc, pNode->shmBaseName))
23342 return ( rc == 0 ) ? SQLITE_OK : SQLITE_BUSY;
23346 ** Find an os2ShmNode in global list or allocate a new one, if not found.
23348 ** This is not a VFS shared-memory method; it is a utility function called
23349 ** by VFS shared-memory methods.
23351 static int os2OpenSharedMemory( os2File *fd, int szRegion ) {
23352 os2ShmLink *pLink;
23353 os2ShmNode *pNode;
23354 int cbShmName, rc = SQLITE_OK;
23355 char shmName[CCHMAXPATH + 30];
23356 #ifndef SQLITE_OS2_NO_WAL_LOCK_FILE
23357 ULONG action;
23358 #endif
23360 /* We need some additional space at the end to append the region number */
23361 cbShmName = sprintf(shmName, "\\SHAREMEM\\%s", fd->zFullPathCp );
23362 if( cbShmName >= CCHMAXPATH-8 )
23363 return SQLITE_IOERR_SHMOPEN;
23365 /* Replace colon in file name to form a valid shared memory name */
23366 shmName[10+1] = '!';
23368 /* Allocate link object (we free it later in case of failure) */
23369 pLink = sqlite3_malloc( sizeof(*pLink) );
23370 if( !pLink )
23371 return SQLITE_NOMEM;
23373 /* Access node list */
23374 os2ShmEnterMutex();
23376 /* Find node by it's shared memory base name */
23377 for( pNode = os2ShmNodeList;
23378 pNode && stricmp(shmName, pNode->shmBaseName) != 0;
23379 pNode = pNode->pNext ) ;
23381 /* Not found: allocate a new node */
23382 if( !pNode ) {
23383 pNode = sqlite3_malloc( sizeof(*pNode) + cbShmName );
23384 if( pNode ) {
23385 memset(pNode, 0, sizeof(*pNode) );
23386 pNode->szRegion = szRegion;
23387 pNode->hLockFile = (HFILE)-1;
23388 strcpy(pNode->shmBaseName, shmName);
23390 #ifdef SQLITE_OS2_NO_WAL_LOCK_FILE
23391 if( DosDupHandle(fd->h, &pNode->hLockFile) != 0 ) {
23392 #else
23393 sprintf(shmName, "%s-lck", fd->zFullPathCp);
23394 if( DosOpen((PSZ)shmName, &pNode->hLockFile, &action, 0, FILE_NORMAL,
23395 OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_CREATE_IF_NEW,
23396 OPEN_ACCESS_READWRITE | OPEN_SHARE_DENYNONE |
23397 OPEN_FLAGS_NOINHERIT | OPEN_FLAGS_FAIL_ON_ERROR,
23398 NULL) != 0 ) {
23399 #endif
23400 sqlite3_free(pNode);
23401 rc = SQLITE_IOERR;
23402 } else {
23403 pNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
23404 if( !pNode->mutex ) {
23405 sqlite3_free(pNode);
23406 rc = SQLITE_NOMEM;
23409 } else {
23410 rc = SQLITE_NOMEM;
23413 if( rc == SQLITE_OK ) {
23414 pNode->pNext = os2ShmNodeList;
23415 os2ShmNodeList = pNode;
23416 } else {
23417 pNode = NULL;
23419 } else if( pNode->szRegion != szRegion ) {
23420 rc = SQLITE_IOERR_SHMSIZE;
23421 pNode = NULL;
23424 if( pNode ) {
23425 sqlite3_mutex_enter(pNode->mutex);
23427 memset(pLink, 0, sizeof(*pLink));
23429 pLink->pShmNode = pNode;
23430 pLink->pNext = pNode->pFirst;
23431 pNode->pFirst = pLink;
23432 pNode->nRef++;
23434 fd->pShmLink = pLink;
23436 sqlite3_mutex_leave(pNode->mutex);
23438 } else {
23439 /* Error occured. Free our link object. */
23440 sqlite3_free(pLink);
23443 os2ShmLeaveMutex();
23445 ERR_TRACE(rc, ("os2OpenSharedMemory: %d %s\n", rc, fd->zFullPathCp))
23447 return rc;
23451 ** Purge the os2ShmNodeList list of all entries with nRef==0.
23453 ** This is not a VFS shared-memory method; it is a utility function called
23454 ** by VFS shared-memory methods.
23456 static void os2PurgeShmNodes( int deleteFlag ) {
23457 os2ShmNode *pNode;
23458 os2ShmNode **ppNode;
23460 os2ShmEnterMutex();
23462 ppNode = &os2ShmNodeList;
23464 while( *ppNode ) {
23465 pNode = *ppNode;
23467 if( pNode->nRef == 0 ) {
23468 *ppNode = pNode->pNext;
23470 if( pNode->apRegion ) {
23471 /* Prevent other processes from resizing the shared memory */
23472 os2ShmSystemLock(pNode, _SHM_WRLCK_WAIT, OS2_SHM_DMS, 1);
23474 while( pNode->nRegion-- ) {
23475 #ifdef SQLITE_DEBUG
23476 int rc =
23477 #endif
23478 DosFreeMem(pNode->apRegion[pNode->nRegion]);
23480 OSTRACE(("SHM-PURGE pid-%d unmap region=%d %s\n",
23481 (int)GetCurrentProcessId(), pNode->nRegion,
23482 rc == 0 ? "ok" : "failed"));
23485 /* Allow other processes to resize the shared memory */
23486 os2ShmSystemLock(pNode, _SHM_UNLCK, OS2_SHM_DMS, 1);
23488 sqlite3_free(pNode->apRegion);
23491 DosClose(pNode->hLockFile);
23493 #ifndef SQLITE_OS2_NO_WAL_LOCK_FILE
23494 if( deleteFlag ) {
23495 char fileName[CCHMAXPATH];
23496 /* Skip "\\SHAREMEM\\" */
23497 sprintf(fileName, "%s-lck", pNode->shmBaseName + 10);
23498 /* restore colon */
23499 fileName[1] = ':';
23501 DosForceDelete(fileName);
23503 #endif
23505 sqlite3_mutex_free(pNode->mutex);
23507 sqlite3_free(pNode);
23509 } else {
23510 ppNode = &pNode->pNext;
23514 os2ShmLeaveMutex();
23518 ** This function is called to obtain a pointer to region iRegion of the
23519 ** shared-memory associated with the database file id. Shared-memory regions
23520 ** are numbered starting from zero. Each shared-memory region is szRegion
23521 ** bytes in size.
23523 ** If an error occurs, an error code is returned and *pp is set to NULL.
23525 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
23526 ** region has not been allocated (by any client, including one running in a
23527 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
23528 ** bExtend is non-zero and the requested shared-memory region has not yet
23529 ** been allocated, it is allocated by this function.
23531 ** If the shared-memory region has already been allocated or is allocated by
23532 ** this call as described above, then it is mapped into this processes
23533 ** address space (if it is not already), *pp is set to point to the mapped
23534 ** memory and SQLITE_OK returned.
23536 static int os2ShmMap(
23537 sqlite3_file *id, /* Handle open on database file */
23538 int iRegion, /* Region to retrieve */
23539 int szRegion, /* Size of regions */
23540 int bExtend, /* True to extend block if necessary */
23541 void volatile **pp /* OUT: Mapped memory */
23543 PVOID pvTemp;
23544 void **apRegion;
23545 os2ShmNode *pNode;
23546 int n, rc = SQLITE_OK;
23547 char shmName[CCHMAXPATH];
23548 os2File *pFile = (os2File*)id;
23550 *pp = NULL;
23552 if( !pFile->pShmLink )
23553 rc = os2OpenSharedMemory( pFile, szRegion );
23555 if( rc == SQLITE_OK ) {
23556 pNode = pFile->pShmLink->pShmNode ;
23558 sqlite3_mutex_enter(pNode->mutex);
23560 assert( szRegion==pNode->szRegion );
23562 /* Unmapped region ? */
23563 if( iRegion >= pNode->nRegion ) {
23564 /* Prevent other processes from resizing the shared memory */
23565 os2ShmSystemLock(pNode, _SHM_WRLCK_WAIT, OS2_SHM_DMS, 1);
23567 apRegion = sqlite3_realloc(
23568 pNode->apRegion, (iRegion + 1) * sizeof(apRegion[0]));
23570 if( apRegion ) {
23571 pNode->apRegion = apRegion;
23573 while( pNode->nRegion <= iRegion ) {
23574 sprintf(shmName, "%s-%u",
23575 pNode->shmBaseName, pNode->nRegion);
23577 if( DosGetNamedSharedMem(&pvTemp, (PSZ)shmName,
23578 PAG_READ | PAG_WRITE) != NO_ERROR ) {
23579 if( !bExtend )
23580 break;
23582 if( DosAllocSharedMem(&pvTemp, (PSZ)shmName, szRegion,
23583 PAG_READ | PAG_WRITE | PAG_COMMIT | OBJ_ANY) != NO_ERROR &&
23584 DosAllocSharedMem(&pvTemp, (PSZ)shmName, szRegion,
23585 PAG_READ | PAG_WRITE | PAG_COMMIT) != NO_ERROR ) {
23586 rc = SQLITE_NOMEM;
23587 break;
23591 apRegion[pNode->nRegion++] = pvTemp;
23594 /* zero out remaining entries */
23595 for( n = pNode->nRegion; n <= iRegion; n++ )
23596 pNode->apRegion[n] = NULL;
23598 /* Return this region (maybe zero) */
23599 *pp = pNode->apRegion[iRegion];
23600 } else {
23601 rc = SQLITE_NOMEM;
23604 /* Allow other processes to resize the shared memory */
23605 os2ShmSystemLock(pNode, _SHM_UNLCK, OS2_SHM_DMS, 1);
23607 } else {
23608 /* Region has been mapped previously */
23609 *pp = pNode->apRegion[iRegion];
23612 sqlite3_mutex_leave(pNode->mutex);
23615 ERR_TRACE(rc, ("os2ShmMap: %s iRgn = %d, szRgn = %d, bExt = %d : %d\n",
23616 pFile->zFullPathCp, iRegion, szRegion, bExtend, rc))
23618 return rc;
23622 ** Close a connection to shared-memory. Delete the underlying
23623 ** storage if deleteFlag is true.
23625 ** If there is no shared memory associated with the connection then this
23626 ** routine is a harmless no-op.
23628 static int os2ShmUnmap(
23629 sqlite3_file *id, /* The underlying database file */
23630 int deleteFlag /* Delete shared-memory if true */
23632 os2File *pFile = (os2File*)id;
23633 os2ShmLink *pLink = pFile->pShmLink;
23635 if( pLink ) {
23636 int nRef = -1;
23637 os2ShmLink **ppLink;
23638 os2ShmNode *pNode = pLink->pShmNode;
23640 sqlite3_mutex_enter(pNode->mutex);
23642 for( ppLink = &pNode->pFirst;
23643 *ppLink && *ppLink != pLink;
23644 ppLink = &(*ppLink)->pNext ) ;
23646 assert(*ppLink);
23648 if( *ppLink ) {
23649 *ppLink = pLink->pNext;
23650 nRef = --pNode->nRef;
23651 } else {
23652 ERR_TRACE(1, ("os2ShmUnmap: link not found ! %s\n",
23653 pNode->shmBaseName))
23656 pFile->pShmLink = NULL;
23657 sqlite3_free(pLink);
23659 sqlite3_mutex_leave(pNode->mutex);
23661 if( nRef == 0 )
23662 os2PurgeShmNodes( deleteFlag );
23665 return SQLITE_OK;
23669 ** Change the lock state for a shared-memory segment.
23671 ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
23672 ** different here than in posix. In xShmLock(), one can go from unlocked
23673 ** to shared and back or from unlocked to exclusive and back. But one may
23674 ** not go from shared to exclusive or from exclusive to shared.
23676 static int os2ShmLock(
23677 sqlite3_file *id, /* Database file holding the shared memory */
23678 int ofst, /* First lock to acquire or release */
23679 int n, /* Number of locks to acquire or release */
23680 int flags /* What to do with the lock */
23682 u32 mask; /* Mask of locks to take or release */
23683 int rc = SQLITE_OK; /* Result code */
23684 os2File *pFile = (os2File*)id;
23685 os2ShmLink *p = pFile->pShmLink; /* The shared memory being locked */
23686 os2ShmLink *pX; /* For looping over all siblings */
23687 os2ShmNode *pShmNode = p->pShmNode; /* Our node */
23689 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
23690 assert( n>=1 );
23691 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
23692 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
23693 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
23694 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
23695 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
23697 mask = (u32)((1U<<(ofst+n)) - (1U<<ofst));
23698 assert( n>1 || mask==(1<<ofst) );
23701 sqlite3_mutex_enter(pShmNode->mutex);
23703 if( flags & SQLITE_SHM_UNLOCK ){
23704 u32 allMask = 0; /* Mask of locks held by siblings */
23706 /* See if any siblings hold this same lock */
23707 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
23708 if( pX==p ) continue;
23709 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
23710 allMask |= pX->sharedMask;
23713 /* Unlock the system-level locks */
23714 if( (mask & allMask)==0 ){
23715 rc = os2ShmSystemLock(pShmNode, _SHM_UNLCK, ofst+OS2_SHM_BASE, n);
23716 }else{
23717 rc = SQLITE_OK;
23720 /* Undo the local locks */
23721 if( rc==SQLITE_OK ){
23722 p->exclMask &= ~mask;
23723 p->sharedMask &= ~mask;
23725 }else if( flags & SQLITE_SHM_SHARED ){
23726 u32 allShared = 0; /* Union of locks held by connections other than "p" */
23728 /* Find out which shared locks are already held by sibling connections.
23729 ** If any sibling already holds an exclusive lock, go ahead and return
23730 ** SQLITE_BUSY.
23732 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
23733 if( (pX->exclMask & mask)!=0 ){
23734 rc = SQLITE_BUSY;
23735 break;
23737 allShared |= pX->sharedMask;
23740 /* Get shared locks at the system level, if necessary */
23741 if( rc==SQLITE_OK ){
23742 if( (allShared & mask)==0 ){
23743 rc = os2ShmSystemLock(pShmNode, _SHM_RDLCK, ofst+OS2_SHM_BASE, n);
23744 }else{
23745 rc = SQLITE_OK;
23749 /* Get the local shared locks */
23750 if( rc==SQLITE_OK ){
23751 p->sharedMask |= mask;
23753 }else{
23754 /* Make sure no sibling connections hold locks that will block this
23755 ** lock. If any do, return SQLITE_BUSY right away.
23757 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
23758 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
23759 rc = SQLITE_BUSY;
23760 break;
23764 /* Get the exclusive locks at the system level. Then if successful
23765 ** also mark the local connection as being locked.
23767 if( rc==SQLITE_OK ){
23768 rc = os2ShmSystemLock(pShmNode, _SHM_WRLCK, ofst+OS2_SHM_BASE, n);
23769 if( rc==SQLITE_OK ){
23770 assert( (p->sharedMask & mask)==0 );
23771 p->exclMask |= mask;
23776 sqlite3_mutex_leave(pShmNode->mutex);
23778 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x %s\n",
23779 p->id, (int)GetCurrentProcessId(), p->sharedMask, p->exclMask,
23780 rc ? "failed" : "ok"));
23782 ERR_TRACE(rc, ("os2ShmLock: ofst = %d, n = %d, flags = 0x%x -> %d \n",
23783 ofst, n, flags, rc))
23785 return rc;
23789 ** Implement a memory barrier or memory fence on shared memory.
23791 ** All loads and stores begun before the barrier must complete before
23792 ** any load or store begun after the barrier.
23794 static void os2ShmBarrier(
23795 sqlite3_file *id /* Database file holding the shared memory */
23797 UNUSED_PARAMETER(id);
23798 os2ShmEnterMutex();
23799 os2ShmLeaveMutex();
23802 #else
23803 # define os2ShmMap 0
23804 # define os2ShmLock 0
23805 # define os2ShmBarrier 0
23806 # define os2ShmUnmap 0
23807 #endif /* #ifndef SQLITE_OMIT_WAL */
23811 ** This vector defines all the methods that can operate on an
23812 ** sqlite3_file for os2.
23814 static const sqlite3_io_methods os2IoMethod = {
23815 2, /* iVersion */
23816 os2Close, /* xClose */
23817 os2Read, /* xRead */
23818 os2Write, /* xWrite */
23819 os2Truncate, /* xTruncate */
23820 os2Sync, /* xSync */
23821 os2FileSize, /* xFileSize */
23822 os2Lock, /* xLock */
23823 os2Unlock, /* xUnlock */
23824 os2CheckReservedLock, /* xCheckReservedLock */
23825 os2FileControl, /* xFileControl */
23826 os2SectorSize, /* xSectorSize */
23827 os2DeviceCharacteristics, /* xDeviceCharacteristics */
23828 os2ShmMap, /* xShmMap */
23829 os2ShmLock, /* xShmLock */
23830 os2ShmBarrier, /* xShmBarrier */
23831 os2ShmUnmap /* xShmUnmap */
23835 /***************************************************************************
23836 ** Here ends the I/O methods that form the sqlite3_io_methods object.
23838 ** The next block of code implements the VFS methods.
23839 ****************************************************************************/
23842 ** Create a temporary file name in zBuf. zBuf must be big enough to
23843 ** hold at pVfs->mxPathname characters.
23845 static int getTempname(int nBuf, char *zBuf ){
23846 static const char zChars[] =
23847 "abcdefghijklmnopqrstuvwxyz"
23848 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
23849 "0123456789";
23850 int i, j;
23851 PSZ zTempPathCp;
23852 char zTempPath[CCHMAXPATH];
23853 ULONG ulDriveNum, ulDriveMap;
23855 /* It's odd to simulate an io-error here, but really this is just
23856 ** using the io-error infrastructure to test that SQLite handles this
23857 ** function failing.
23859 SimulateIOError( return SQLITE_IOERR );
23861 if( sqlite3_temp_directory ) {
23862 sqlite3_snprintf(CCHMAXPATH-30, zTempPath, "%s", sqlite3_temp_directory);
23863 } else if( DosScanEnv( (PSZ)"TEMP", &zTempPathCp ) == NO_ERROR ||
23864 DosScanEnv( (PSZ)"TMP", &zTempPathCp ) == NO_ERROR ||
23865 DosScanEnv( (PSZ)"TMPDIR", &zTempPathCp ) == NO_ERROR ) {
23866 char *zTempPathUTF = convertCpPathToUtf8( (char *)zTempPathCp );
23867 sqlite3_snprintf(CCHMAXPATH-30, zTempPath, "%s", zTempPathUTF);
23868 free( zTempPathUTF );
23869 } else if( DosQueryCurrentDisk( &ulDriveNum, &ulDriveMap ) == NO_ERROR ) {
23870 zTempPath[0] = (char)('A' + ulDriveNum - 1);
23871 zTempPath[1] = ':';
23872 zTempPath[2] = '\0';
23873 } else {
23874 zTempPath[0] = '\0';
23877 /* Strip off a trailing slashes or backslashes, otherwise we would get *
23878 * multiple (back)slashes which causes DosOpen() to fail. *
23879 * Trailing spaces are not allowed, either. */
23880 j = sqlite3Strlen30(zTempPath);
23881 while( j > 0 && ( zTempPath[j-1] == '\\' || zTempPath[j-1] == '/' ||
23882 zTempPath[j-1] == ' ' ) ){
23883 j--;
23885 zTempPath[j] = '\0';
23887 /* We use 20 bytes to randomize the name */
23888 sqlite3_snprintf(nBuf-22, zBuf,
23889 "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
23890 j = sqlite3Strlen30(zBuf);
23891 sqlite3_randomness( 20, &zBuf[j] );
23892 for( i = 0; i < 20; i++, j++ ){
23893 zBuf[j] = zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
23895 zBuf[j] = 0;
23897 OSTRACE(( "TEMP FILENAME: %s\n", zBuf ));
23898 return SQLITE_OK;
23903 ** Turn a relative pathname into a full pathname. Write the full
23904 ** pathname into zFull[]. zFull[] will be at least pVfs->mxPathname
23905 ** bytes in size.
23907 static int os2FullPathname(
23908 sqlite3_vfs *pVfs, /* Pointer to vfs object */
23909 const char *zRelative, /* Possibly relative input path */
23910 int nFull, /* Size of output buffer in bytes */
23911 char *zFull /* Output buffer */
23913 char *zRelativeCp = convertUtf8PathToCp( zRelative );
23914 char zFullCp[CCHMAXPATH] = "\0";
23915 char *zFullUTF;
23916 APIRET rc = DosQueryPathInfo( (PSZ)zRelativeCp, FIL_QUERYFULLNAME,
23917 zFullCp, CCHMAXPATH );
23918 free( zRelativeCp );
23919 zFullUTF = convertCpPathToUtf8( zFullCp );
23920 sqlite3_snprintf( nFull, zFull, zFullUTF );
23921 free( zFullUTF );
23922 return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
23927 ** Open a file.
23929 static int os2Open(
23930 sqlite3_vfs *pVfs, /* Not used */
23931 const char *zName, /* Name of the file (UTF-8) */
23932 sqlite3_file *id, /* Write the SQLite file handle here */
23933 int flags, /* Open mode flags */
23934 int *pOutFlags /* Status return flags */
23936 HFILE h;
23937 ULONG ulOpenFlags = 0;
23938 ULONG ulOpenMode = 0;
23939 ULONG ulAction = 0;
23940 ULONG rc;
23941 os2File *pFile = (os2File*)id;
23942 const char *zUtf8Name = zName;
23943 char *zNameCp;
23944 char zTmpname[CCHMAXPATH];
23946 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
23947 int isCreate = (flags & SQLITE_OPEN_CREATE);
23948 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
23949 #ifndef NDEBUG
23950 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
23951 int isReadonly = (flags & SQLITE_OPEN_READONLY);
23952 int eType = (flags & 0xFFFFFF00);
23953 int isOpenJournal = (isCreate && (
23954 eType==SQLITE_OPEN_MASTER_JOURNAL
23955 || eType==SQLITE_OPEN_MAIN_JOURNAL
23956 || eType==SQLITE_OPEN_WAL
23958 #endif
23960 UNUSED_PARAMETER(pVfs);
23961 assert( id!=0 );
23963 /* Check the following statements are true:
23965 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
23966 ** (b) if CREATE is set, then READWRITE must also be set, and
23967 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
23968 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
23970 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
23971 assert(isCreate==0 || isReadWrite);
23972 assert(isExclusive==0 || isCreate);
23973 assert(isDelete==0 || isCreate);
23975 /* The main DB, main journal, WAL file and master journal are never
23976 ** automatically deleted. Nor are they ever temporary files. */
23977 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
23978 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
23979 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
23980 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
23982 /* Assert that the upper layer has set one of the "file-type" flags. */
23983 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
23984 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
23985 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
23986 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
23989 memset( pFile, 0, sizeof(*pFile) );
23990 pFile->h = (HFILE)-1;
23992 /* If the second argument to this function is NULL, generate a
23993 ** temporary file name to use
23995 if( !zUtf8Name ){
23996 assert(isDelete && !isOpenJournal);
23997 rc = getTempname(CCHMAXPATH, zTmpname);
23998 if( rc!=SQLITE_OK ){
23999 return rc;
24001 zUtf8Name = zTmpname;
24004 if( isReadWrite ){
24005 ulOpenMode |= OPEN_ACCESS_READWRITE;
24006 }else{
24007 ulOpenMode |= OPEN_ACCESS_READONLY;
24010 /* Open in random access mode for possibly better speed. Allow full
24011 ** sharing because file locks will provide exclusive access when needed.
24012 ** The handle should not be inherited by child processes and we don't
24013 ** want popups from the critical error handler.
24015 ulOpenMode |= OPEN_FLAGS_RANDOM | OPEN_SHARE_DENYNONE |
24016 OPEN_FLAGS_NOINHERIT | OPEN_FLAGS_FAIL_ON_ERROR;
24018 /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
24019 ** created. SQLite doesn't use it to indicate "exclusive access"
24020 ** as it is usually understood.
24022 if( isExclusive ){
24023 /* Creates a new file, only if it does not already exist. */
24024 /* If the file exists, it fails. */
24025 ulOpenFlags |= OPEN_ACTION_CREATE_IF_NEW | OPEN_ACTION_FAIL_IF_EXISTS;
24026 }else if( isCreate ){
24027 /* Open existing file, or create if it doesn't exist */
24028 ulOpenFlags |= OPEN_ACTION_CREATE_IF_NEW | OPEN_ACTION_OPEN_IF_EXISTS;
24029 }else{
24030 /* Opens a file, only if it exists. */
24031 ulOpenFlags |= OPEN_ACTION_FAIL_IF_NEW | OPEN_ACTION_OPEN_IF_EXISTS;
24034 zNameCp = convertUtf8PathToCp( zUtf8Name );
24035 rc = DosOpen( (PSZ)zNameCp,
24037 &ulAction,
24039 FILE_NORMAL,
24040 ulOpenFlags,
24041 ulOpenMode,
24042 (PEAOP2)NULL );
24043 free( zNameCp );
24045 if( rc != NO_ERROR ){
24046 OSTRACE(( "OPEN Invalid handle rc=%d: zName=%s, ulAction=%#lx, ulFlags=%#lx, ulMode=%#lx\n",
24047 rc, zUtf8Name, ulAction, ulOpenFlags, ulOpenMode ));
24049 if( isReadWrite ){
24050 return os2Open( pVfs, zName, id,
24051 ((flags|SQLITE_OPEN_READONLY)&~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
24052 pOutFlags );
24053 }else{
24054 return SQLITE_CANTOPEN;
24058 if( pOutFlags ){
24059 *pOutFlags = isReadWrite ? SQLITE_OPEN_READWRITE : SQLITE_OPEN_READONLY;
24062 os2FullPathname( pVfs, zUtf8Name, sizeof( zTmpname ), zTmpname );
24063 pFile->zFullPathCp = convertUtf8PathToCp( zTmpname );
24064 pFile->pMethod = &os2IoMethod;
24065 pFile->flags = flags;
24066 pFile->h = h;
24068 OpenCounter(+1);
24069 OSTRACE(( "OPEN %d pOutFlags=%d\n", pFile->h, pOutFlags ));
24070 return SQLITE_OK;
24074 ** Delete the named file.
24076 static int os2Delete(
24077 sqlite3_vfs *pVfs, /* Not used on os2 */
24078 const char *zFilename, /* Name of file to delete */
24079 int syncDir /* Not used on os2 */
24081 APIRET rc;
24082 char *zFilenameCp;
24083 SimulateIOError( return SQLITE_IOERR_DELETE );
24084 zFilenameCp = convertUtf8PathToCp( zFilename );
24085 rc = DosDelete( (PSZ)zFilenameCp );
24086 free( zFilenameCp );
24087 OSTRACE(( "DELETE \"%s\"\n", zFilename ));
24088 return (rc == NO_ERROR ||
24089 rc == ERROR_FILE_NOT_FOUND ||
24090 rc == ERROR_PATH_NOT_FOUND ) ? SQLITE_OK : SQLITE_IOERR_DELETE;
24094 ** Check the existance and status of a file.
24096 static int os2Access(
24097 sqlite3_vfs *pVfs, /* Not used on os2 */
24098 const char *zFilename, /* Name of file to check */
24099 int flags, /* Type of test to make on this file */
24100 int *pOut /* Write results here */
24102 APIRET rc;
24103 FILESTATUS3 fsts3ConfigInfo;
24104 char *zFilenameCp;
24106 UNUSED_PARAMETER(pVfs);
24107 SimulateIOError( return SQLITE_IOERR_ACCESS; );
24109 zFilenameCp = convertUtf8PathToCp( zFilename );
24110 rc = DosQueryPathInfo( (PSZ)zFilenameCp, FIL_STANDARD,
24111 &fsts3ConfigInfo, sizeof(FILESTATUS3) );
24112 free( zFilenameCp );
24113 OSTRACE(( "ACCESS fsts3ConfigInfo.attrFile=%d flags=%d rc=%d\n",
24114 fsts3ConfigInfo.attrFile, flags, rc ));
24116 switch( flags ){
24117 case SQLITE_ACCESS_EXISTS:
24118 /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
24119 ** as if it does not exist.
24121 if( fsts3ConfigInfo.cbFile == 0 )
24122 rc = ERROR_FILE_NOT_FOUND;
24123 break;
24124 case SQLITE_ACCESS_READ:
24125 break;
24126 case SQLITE_ACCESS_READWRITE:
24127 if( fsts3ConfigInfo.attrFile & FILE_READONLY )
24128 rc = ERROR_ACCESS_DENIED;
24129 break;
24130 default:
24131 rc = ERROR_FILE_NOT_FOUND;
24132 assert( !"Invalid flags argument" );
24135 *pOut = (rc == NO_ERROR);
24136 OSTRACE(( "ACCESS %s flags %d: rc=%d\n", zFilename, flags, *pOut ));
24138 return SQLITE_OK;
24142 #ifndef SQLITE_OMIT_LOAD_EXTENSION
24144 ** Interfaces for opening a shared library, finding entry points
24145 ** within the shared library, and closing the shared library.
24148 ** Interfaces for opening a shared library, finding entry points
24149 ** within the shared library, and closing the shared library.
24151 static void *os2DlOpen(sqlite3_vfs *pVfs, const char *zFilename){
24152 HMODULE hmod;
24153 APIRET rc;
24154 char *zFilenameCp = convertUtf8PathToCp(zFilename);
24155 rc = DosLoadModule(NULL, 0, (PSZ)zFilenameCp, &hmod);
24156 free(zFilenameCp);
24157 return rc != NO_ERROR ? 0 : (void*)hmod;
24160 ** A no-op since the error code is returned on the DosLoadModule call.
24161 ** os2Dlopen returns zero if DosLoadModule is not successful.
24163 static void os2DlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
24164 /* no-op */
24166 static void (*os2DlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
24167 PFN pfn;
24168 APIRET rc;
24169 rc = DosQueryProcAddr((HMODULE)pHandle, 0L, (PSZ)zSymbol, &pfn);
24170 if( rc != NO_ERROR ){
24171 /* if the symbol itself was not found, search again for the same
24172 * symbol with an extra underscore, that might be needed depending
24173 * on the calling convention */
24174 char _zSymbol[256] = "_";
24175 strncat(_zSymbol, zSymbol, 254);
24176 rc = DosQueryProcAddr((HMODULE)pHandle, 0L, (PSZ)_zSymbol, &pfn);
24178 return rc != NO_ERROR ? 0 : (void(*)(void))pfn;
24180 static void os2DlClose(sqlite3_vfs *pVfs, void *pHandle){
24181 DosFreeModule((HMODULE)pHandle);
24183 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
24184 #define os2DlOpen 0
24185 #define os2DlError 0
24186 #define os2DlSym 0
24187 #define os2DlClose 0
24188 #endif
24192 ** Write up to nBuf bytes of randomness into zBuf.
24194 static int os2Randomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf ){
24195 int n = 0;
24196 #if defined(SQLITE_TEST)
24197 n = nBuf;
24198 memset(zBuf, 0, nBuf);
24199 #else
24200 int i;
24201 PPIB ppib;
24202 PTIB ptib;
24203 DATETIME dt;
24204 static unsigned c = 0;
24205 /* Ordered by variation probability */
24206 static ULONG svIdx[6] = { QSV_MS_COUNT, QSV_TIME_LOW,
24207 QSV_MAXPRMEM, QSV_MAXSHMEM,
24208 QSV_TOTAVAILMEM, QSV_TOTRESMEM };
24210 /* 8 bytes; timezone and weekday don't increase the randomness much */
24211 if( (int)sizeof(dt)-3 <= nBuf - n ){
24212 c += 0x0100;
24213 DosGetDateTime(&dt);
24214 dt.year = (USHORT)((dt.year - 1900) | c);
24215 memcpy(&zBuf[n], &dt, sizeof(dt)-3);
24216 n += sizeof(dt)-3;
24219 /* 4 bytes; PIDs and TIDs are 16 bit internally, so combine them */
24220 if( (int)sizeof(ULONG) <= nBuf - n ){
24221 DosGetInfoBlocks(&ptib, &ppib);
24222 *(PULONG)&zBuf[n] = MAKELONG(ppib->pib_ulpid,
24223 ptib->tib_ptib2->tib2_ultid);
24224 n += sizeof(ULONG);
24227 /* Up to 6 * 4 bytes; variables depend on the system state */
24228 for( i = 0; i < 6 && (int)sizeof(ULONG) <= nBuf - n; i++ ){
24229 DosQuerySysInfo(svIdx[i], svIdx[i],
24230 (PULONG)&zBuf[n], sizeof(ULONG));
24231 n += sizeof(ULONG);
24233 #endif
24235 return n;
24239 ** Sleep for a little while. Return the amount of time slept.
24240 ** The argument is the number of microseconds we want to sleep.
24241 ** The return value is the number of microseconds of sleep actually
24242 ** requested from the underlying operating system, a number which
24243 ** might be greater than or equal to the argument, but not less
24244 ** than the argument.
24246 static int os2Sleep( sqlite3_vfs *pVfs, int microsec ){
24247 DosSleep( (microsec/1000) );
24248 return microsec;
24252 ** The following variable, if set to a non-zero value, becomes the result
24253 ** returned from sqlite3OsCurrentTime(). This is used for testing.
24255 #ifdef SQLITE_TEST
24256 SQLITE_API int sqlite3_current_time = 0;
24257 #endif
24260 ** Find the current time (in Universal Coordinated Time). Write into *piNow
24261 ** the current time and date as a Julian Day number times 86_400_000. In
24262 ** other words, write into *piNow the number of milliseconds since the Julian
24263 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
24264 ** proleptic Gregorian calendar.
24266 ** On success, return 0. Return 1 if the time and date cannot be found.
24268 static int os2CurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
24269 #ifdef SQLITE_TEST
24270 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
24271 #endif
24272 int year, month, datepart, timepart;
24274 DATETIME dt;
24275 DosGetDateTime( &dt );
24277 year = dt.year;
24278 month = dt.month;
24280 /* Calculations from http://www.astro.keele.ac.uk/~rno/Astronomy/hjd.html
24281 ** http://www.astro.keele.ac.uk/~rno/Astronomy/hjd-0.1.c
24282 ** Calculate the Julian days
24284 datepart = (int)dt.day - 32076 +
24285 1461*(year + 4800 + (month - 14)/12)/4 +
24286 367*(month - 2 - (month - 14)/12*12)/12 -
24287 3*((year + 4900 + (month - 14)/12)/100)/4;
24289 /* Time in milliseconds, hours to noon added */
24290 timepart = 12*3600*1000 + dt.hundredths*10 + dt.seconds*1000 +
24291 ((int)dt.minutes + dt.timezone)*60*1000 + dt.hours*3600*1000;
24293 *piNow = (sqlite3_int64)datepart*86400*1000 + timepart;
24295 #ifdef SQLITE_TEST
24296 if( sqlite3_current_time ){
24297 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
24299 #endif
24301 UNUSED_PARAMETER(pVfs);
24302 return 0;
24306 ** Find the current time (in Universal Coordinated Time). Write the
24307 ** current time and date as a Julian Day number into *prNow and
24308 ** return 0. Return 1 if the time and date cannot be found.
24310 static int os2CurrentTime( sqlite3_vfs *pVfs, double *prNow ){
24311 int rc;
24312 sqlite3_int64 i;
24313 rc = os2CurrentTimeInt64(pVfs, &i);
24314 if( !rc ){
24315 *prNow = i/86400000.0;
24317 return rc;
24321 ** The idea is that this function works like a combination of
24322 ** GetLastError() and FormatMessage() on windows (or errno and
24323 ** strerror_r() on unix). After an error is returned by an OS
24324 ** function, SQLite calls this function with zBuf pointing to
24325 ** a buffer of nBuf bytes. The OS layer should populate the
24326 ** buffer with a nul-terminated UTF-8 encoded error message
24327 ** describing the last IO error to have occurred within the calling
24328 ** thread.
24330 ** If the error message is too large for the supplied buffer,
24331 ** it should be truncated. The return value of xGetLastError
24332 ** is zero if the error message fits in the buffer, or non-zero
24333 ** otherwise (if the message was truncated). If non-zero is returned,
24334 ** then it is not necessary to include the nul-terminator character
24335 ** in the output buffer.
24337 ** Not supplying an error message will have no adverse effect
24338 ** on SQLite. It is fine to have an implementation that never
24339 ** returns an error message:
24341 ** int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
24342 ** assert(zBuf[0]=='\0');
24343 ** return 0;
24344 ** }
24346 ** However if an error message is supplied, it will be incorporated
24347 ** by sqlite into the error message available to the user using
24348 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
24350 static int os2GetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
24351 assert(zBuf[0]=='\0');
24352 return 0;
24356 ** Initialize and deinitialize the operating system interface.
24358 SQLITE_API int sqlite3_os_init(void){
24359 static sqlite3_vfs os2Vfs = {
24360 3, /* iVersion */
24361 sizeof(os2File), /* szOsFile */
24362 CCHMAXPATH, /* mxPathname */
24363 0, /* pNext */
24364 "os2", /* zName */
24365 0, /* pAppData */
24367 os2Open, /* xOpen */
24368 os2Delete, /* xDelete */
24369 os2Access, /* xAccess */
24370 os2FullPathname, /* xFullPathname */
24371 os2DlOpen, /* xDlOpen */
24372 os2DlError, /* xDlError */
24373 os2DlSym, /* xDlSym */
24374 os2DlClose, /* xDlClose */
24375 os2Randomness, /* xRandomness */
24376 os2Sleep, /* xSleep */
24377 os2CurrentTime, /* xCurrentTime */
24378 os2GetLastError, /* xGetLastError */
24379 os2CurrentTimeInt64, /* xCurrentTimeInt64 */
24380 0, /* xSetSystemCall */
24381 0, /* xGetSystemCall */
24382 0 /* xNextSystemCall */
24384 sqlite3_vfs_register(&os2Vfs, 1);
24385 initUconvObjects();
24386 /* sqlite3OSTrace = 1; */
24387 return SQLITE_OK;
24389 SQLITE_API int sqlite3_os_end(void){
24390 freeUconvObjects();
24391 return SQLITE_OK;
24394 #endif /* SQLITE_OS_OS2 */
24396 /************** End of os_os2.c **********************************************/
24397 /************** Begin file os_unix.c *****************************************/
24399 ** 2004 May 22
24401 ** The author disclaims copyright to this source code. In place of
24402 ** a legal notice, here is a blessing:
24404 ** May you do good and not evil.
24405 ** May you find forgiveness for yourself and forgive others.
24406 ** May you share freely, never taking more than you give.
24408 ******************************************************************************
24410 ** This file contains the VFS implementation for unix-like operating systems
24411 ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
24413 ** There are actually several different VFS implementations in this file.
24414 ** The differences are in the way that file locking is done. The default
24415 ** implementation uses Posix Advisory Locks. Alternative implementations
24416 ** use flock(), dot-files, various proprietary locking schemas, or simply
24417 ** skip locking all together.
24419 ** This source file is organized into divisions where the logic for various
24420 ** subfunctions is contained within the appropriate division. PLEASE
24421 ** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
24422 ** in the correct division and should be clearly labeled.
24424 ** The layout of divisions is as follows:
24426 ** * General-purpose declarations and utility functions.
24427 ** * Unique file ID logic used by VxWorks.
24428 ** * Various locking primitive implementations (all except proxy locking):
24429 ** + for Posix Advisory Locks
24430 ** + for no-op locks
24431 ** + for dot-file locks
24432 ** + for flock() locking
24433 ** + for named semaphore locks (VxWorks only)
24434 ** + for AFP filesystem locks (MacOSX only)
24435 ** * sqlite3_file methods not associated with locking.
24436 ** * Definitions of sqlite3_io_methods objects for all locking
24437 ** methods plus "finder" functions for each locking method.
24438 ** * sqlite3_vfs method implementations.
24439 ** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
24440 ** * Definitions of sqlite3_vfs objects for all locking methods
24441 ** plus implementations of sqlite3_os_init() and sqlite3_os_end().
24443 #if SQLITE_OS_UNIX /* This file is used on unix only */
24446 ** There are various methods for file locking used for concurrency
24447 ** control:
24449 ** 1. POSIX locking (the default),
24450 ** 2. No locking,
24451 ** 3. Dot-file locking,
24452 ** 4. flock() locking,
24453 ** 5. AFP locking (OSX only),
24454 ** 6. Named POSIX semaphores (VXWorks only),
24455 ** 7. proxy locking. (OSX only)
24457 ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
24458 ** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
24459 ** selection of the appropriate locking style based on the filesystem
24460 ** where the database is located.
24462 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
24463 # if defined(__APPLE__)
24464 # define SQLITE_ENABLE_LOCKING_STYLE 1
24465 # else
24466 # define SQLITE_ENABLE_LOCKING_STYLE 0
24467 # endif
24468 #endif
24471 ** Define the OS_VXWORKS pre-processor macro to 1 if building on
24472 ** vxworks, or 0 otherwise.
24474 #ifndef OS_VXWORKS
24475 # if defined(__RTP__) || defined(_WRS_KERNEL)
24476 # define OS_VXWORKS 1
24477 # else
24478 # define OS_VXWORKS 0
24479 # endif
24480 #endif
24483 ** These #defines should enable >2GB file support on Posix if the
24484 ** underlying operating system supports it. If the OS lacks
24485 ** large file support, these should be no-ops.
24487 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
24488 ** on the compiler command line. This is necessary if you are compiling
24489 ** on a recent machine (ex: RedHat 7.2) but you want your code to work
24490 ** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
24491 ** without this option, LFS is enable. But LFS does not exist in the kernel
24492 ** in RedHat 6.0, so the code won't work. Hence, for maximum binary
24493 ** portability you should omit LFS.
24495 ** The previous paragraph was written in 2005. (This paragraph is written
24496 ** on 2008-11-28.) These days, all Linux kernels support large files, so
24497 ** you should probably leave LFS enabled. But some embedded platforms might
24498 ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
24500 #ifndef SQLITE_DISABLE_LFS
24501 # define _LARGE_FILE 1
24502 # ifndef _FILE_OFFSET_BITS
24503 # define _FILE_OFFSET_BITS 64
24504 # endif
24505 # define _LARGEFILE_SOURCE 1
24506 #endif
24509 ** standard include files.
24511 #include <sys/types.h>
24512 #include <sys/stat.h>
24513 #include <fcntl.h>
24514 #include <unistd.h>
24515 /* #include <time.h> */
24516 #include <sys/time.h>
24517 #include <errno.h>
24518 #ifndef SQLITE_OMIT_WAL
24519 #include <sys/mman.h>
24520 #endif
24522 #if SQLITE_ENABLE_LOCKING_STYLE
24523 # include <sys/ioctl.h>
24524 # if OS_VXWORKS
24525 # include <semaphore.h>
24526 # include <limits.h>
24527 # else
24528 # include <sys/file.h>
24529 # include <sys/param.h>
24530 # endif
24531 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
24533 #if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
24534 # include <sys/mount.h>
24535 #endif
24537 #ifdef HAVE_UTIME
24538 # include <utime.h>
24539 #endif
24542 ** Allowed values of unixFile.fsFlags
24544 #define SQLITE_FSFLAGS_IS_MSDOS 0x1
24547 ** If we are to be thread-safe, include the pthreads header and define
24548 ** the SQLITE_UNIX_THREADS macro.
24550 #if SQLITE_THREADSAFE
24551 /* # include <pthread.h> */
24552 # define SQLITE_UNIX_THREADS 1
24553 #endif
24556 ** Default permissions when creating a new file
24558 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
24559 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
24560 #endif
24563 ** Default permissions when creating auto proxy dir
24565 #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
24566 # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
24567 #endif
24570 ** Maximum supported path-length.
24572 #define MAX_PATHNAME 512
24575 ** Only set the lastErrno if the error code is a real error and not
24576 ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
24578 #define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
24580 /* Forward references */
24581 typedef struct unixShm unixShm; /* Connection shared memory */
24582 typedef struct unixShmNode unixShmNode; /* Shared memory instance */
24583 typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
24584 typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
24587 ** Sometimes, after a file handle is closed by SQLite, the file descriptor
24588 ** cannot be closed immediately. In these cases, instances of the following
24589 ** structure are used to store the file descriptor while waiting for an
24590 ** opportunity to either close or reuse it.
24592 struct UnixUnusedFd {
24593 int fd; /* File descriptor to close */
24594 int flags; /* Flags this file descriptor was opened with */
24595 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
24599 ** The unixFile structure is subclass of sqlite3_file specific to the unix
24600 ** VFS implementations.
24602 typedef struct unixFile unixFile;
24603 struct unixFile {
24604 sqlite3_io_methods const *pMethod; /* Always the first entry */
24605 unixInodeInfo *pInode; /* Info about locks on this inode */
24606 int h; /* The file descriptor */
24607 unsigned char eFileLock; /* The type of lock held on this fd */
24608 unsigned char ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
24609 int lastErrno; /* The unix errno from last I/O error */
24610 void *lockingContext; /* Locking style specific state */
24611 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
24612 const char *zPath; /* Name of the file */
24613 unixShm *pShm; /* Shared memory segment information */
24614 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
24615 #if SQLITE_ENABLE_LOCKING_STYLE
24616 int openFlags; /* The flags specified at open() */
24617 #endif
24618 #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
24619 unsigned fsFlags; /* cached details from statfs() */
24620 #endif
24621 #if OS_VXWORKS
24622 int isDelete; /* Delete on close if true */
24623 struct vxworksFileId *pId; /* Unique file ID */
24624 #endif
24625 #ifndef NDEBUG
24626 /* The next group of variables are used to track whether or not the
24627 ** transaction counter in bytes 24-27 of database files are updated
24628 ** whenever any part of the database changes. An assertion fault will
24629 ** occur if a file is updated without also updating the transaction
24630 ** counter. This test is made to avoid new problems similar to the
24631 ** one described by ticket #3584.
24633 unsigned char transCntrChng; /* True if the transaction counter changed */
24634 unsigned char dbUpdate; /* True if any part of database file changed */
24635 unsigned char inNormalWrite; /* True if in a normal write operation */
24636 #endif
24637 #ifdef SQLITE_TEST
24638 /* In test mode, increase the size of this structure a bit so that
24639 ** it is larger than the struct CrashFile defined in test6.c.
24641 char aPadding[32];
24642 #endif
24646 ** Allowed values for the unixFile.ctrlFlags bitmask:
24648 #define UNIXFILE_EXCL 0x01 /* Connections from one process only */
24649 #define UNIXFILE_RDONLY 0x02 /* Connection is read only */
24650 #define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
24651 #ifndef SQLITE_DISABLE_DIRSYNC
24652 # define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
24653 #else
24654 # define UNIXFILE_DIRSYNC 0x00
24655 #endif
24658 ** Include code that is common to all os_*.c files
24660 /************** Include os_common.h in the middle of os_unix.c ***************/
24661 /************** Begin file os_common.h ***************************************/
24663 ** 2004 May 22
24665 ** The author disclaims copyright to this source code. In place of
24666 ** a legal notice, here is a blessing:
24668 ** May you do good and not evil.
24669 ** May you find forgiveness for yourself and forgive others.
24670 ** May you share freely, never taking more than you give.
24672 ******************************************************************************
24674 ** This file contains macros and a little bit of code that is common to
24675 ** all of the platform-specific files (os_*.c) and is #included into those
24676 ** files.
24678 ** This file should be #included by the os_*.c files only. It is not a
24679 ** general purpose header file.
24681 #ifndef _OS_COMMON_H_
24682 #define _OS_COMMON_H_
24685 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
24686 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
24687 ** switch. The following code should catch this problem at compile-time.
24689 #ifdef MEMORY_DEBUG
24690 # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
24691 #endif
24693 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
24694 # ifndef SQLITE_DEBUG_OS_TRACE
24695 # define SQLITE_DEBUG_OS_TRACE 0
24696 # endif
24697 int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
24698 # define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
24699 #else
24700 # define OSTRACE(X)
24701 #endif
24704 ** Macros for performance tracing. Normally turned off. Only works
24705 ** on i486 hardware.
24707 #ifdef SQLITE_PERFORMANCE_TRACE
24710 ** hwtime.h contains inline assembler code for implementing
24711 ** high-performance timing routines.
24713 /************** Include hwtime.h in the middle of os_common.h ****************/
24714 /************** Begin file hwtime.h ******************************************/
24716 ** 2008 May 27
24718 ** The author disclaims copyright to this source code. In place of
24719 ** a legal notice, here is a blessing:
24721 ** May you do good and not evil.
24722 ** May you find forgiveness for yourself and forgive others.
24723 ** May you share freely, never taking more than you give.
24725 ******************************************************************************
24727 ** This file contains inline asm code for retrieving "high-performance"
24728 ** counters for x86 class CPUs.
24730 #ifndef _HWTIME_H_
24731 #define _HWTIME_H_
24734 ** The following routine only works on pentium-class (or newer) processors.
24735 ** It uses the RDTSC opcode to read the cycle count value out of the
24736 ** processor and returns that value. This can be used for high-res
24737 ** profiling.
24739 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
24740 (defined(i386) || defined(__i386__) || defined(_M_IX86))
24742 #if defined(__GNUC__)
24744 __inline__ sqlite_uint64 sqlite3Hwtime(void){
24745 unsigned int lo, hi;
24746 __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
24747 return (sqlite_uint64)hi << 32 | lo;
24750 #elif defined(_MSC_VER)
24752 __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
24753 __asm {
24754 rdtsc
24755 ret ; return value at EDX:EAX
24759 #endif
24761 #elif (defined(__GNUC__) && defined(__x86_64__))
24763 __inline__ sqlite_uint64 sqlite3Hwtime(void){
24764 unsigned long val;
24765 __asm__ __volatile__ ("rdtsc" : "=A" (val));
24766 return val;
24769 #elif (defined(__GNUC__) && defined(__ppc__))
24771 __inline__ sqlite_uint64 sqlite3Hwtime(void){
24772 unsigned long long retval;
24773 unsigned long junk;
24774 __asm__ __volatile__ ("\n\
24775 1: mftbu %1\n\
24776 mftb %L0\n\
24777 mftbu %0\n\
24778 cmpw %0,%1\n\
24779 bne 1b"
24780 : "=r" (retval), "=r" (junk));
24781 return retval;
24784 #else
24786 #error Need implementation of sqlite3Hwtime() for your platform.
24789 ** To compile without implementing sqlite3Hwtime() for your platform,
24790 ** you can remove the above #error and use the following
24791 ** stub function. You will lose timing support for many
24792 ** of the debugging and testing utilities, but it should at
24793 ** least compile and run.
24795 SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
24797 #endif
24799 #endif /* !defined(_HWTIME_H_) */
24801 /************** End of hwtime.h **********************************************/
24802 /************** Continuing where we left off in os_common.h ******************/
24804 static sqlite_uint64 g_start;
24805 static sqlite_uint64 g_elapsed;
24806 #define TIMER_START g_start=sqlite3Hwtime()
24807 #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
24808 #define TIMER_ELAPSED g_elapsed
24809 #else
24810 #define TIMER_START
24811 #define TIMER_END
24812 #define TIMER_ELAPSED ((sqlite_uint64)0)
24813 #endif
24816 ** If we compile with the SQLITE_TEST macro set, then the following block
24817 ** of code will give us the ability to simulate a disk I/O error. This
24818 ** is used for testing the I/O recovery logic.
24820 #ifdef SQLITE_TEST
24821 SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
24822 SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
24823 SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
24824 SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
24825 SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
24826 SQLITE_API int sqlite3_diskfull_pending = 0;
24827 SQLITE_API int sqlite3_diskfull = 0;
24828 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
24829 #define SimulateIOError(CODE) \
24830 if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
24831 || sqlite3_io_error_pending-- == 1 ) \
24832 { local_ioerr(); CODE; }
24833 static void local_ioerr(){
24834 IOTRACE(("IOERR\n"));
24835 sqlite3_io_error_hit++;
24836 if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
24838 #define SimulateDiskfullError(CODE) \
24839 if( sqlite3_diskfull_pending ){ \
24840 if( sqlite3_diskfull_pending == 1 ){ \
24841 local_ioerr(); \
24842 sqlite3_diskfull = 1; \
24843 sqlite3_io_error_hit = 1; \
24844 CODE; \
24845 }else{ \
24846 sqlite3_diskfull_pending--; \
24849 #else
24850 #define SimulateIOErrorBenign(X)
24851 #define SimulateIOError(A)
24852 #define SimulateDiskfullError(A)
24853 #endif
24856 ** When testing, keep a count of the number of open files.
24858 #ifdef SQLITE_TEST
24859 SQLITE_API int sqlite3_open_file_count = 0;
24860 #define OpenCounter(X) sqlite3_open_file_count+=(X)
24861 #else
24862 #define OpenCounter(X)
24863 #endif
24865 #endif /* !defined(_OS_COMMON_H_) */
24867 /************** End of os_common.h *******************************************/
24868 /************** Continuing where we left off in os_unix.c ********************/
24871 ** Define various macros that are missing from some systems.
24873 #ifndef O_LARGEFILE
24874 # define O_LARGEFILE 0
24875 #endif
24876 #ifdef SQLITE_DISABLE_LFS
24877 # undef O_LARGEFILE
24878 # define O_LARGEFILE 0
24879 #endif
24880 #ifndef O_NOFOLLOW
24881 # define O_NOFOLLOW 0
24882 #endif
24883 #ifndef O_BINARY
24884 # define O_BINARY 0
24885 #endif
24888 ** The threadid macro resolves to the thread-id or to 0. Used for
24889 ** testing and debugging only.
24891 #if SQLITE_THREADSAFE
24892 #define threadid pthread_self()
24893 #else
24894 #define threadid 0
24895 #endif
24898 ** Different Unix systems declare open() in different ways. Same use
24899 ** open(const char*,int,mode_t). Others use open(const char*,int,...).
24900 ** The difference is important when using a pointer to the function.
24902 ** The safest way to deal with the problem is to always use this wrapper
24903 ** which always has the same well-defined interface.
24905 static int posixOpen(const char *zFile, int flags, int mode){
24906 return open(zFile, flags, mode);
24909 /* Forward reference */
24910 static int openDirectory(const char*, int*);
24913 ** Many system calls are accessed through pointer-to-functions so that
24914 ** they may be overridden at runtime to facilitate fault injection during
24915 ** testing and sandboxing. The following array holds the names and pointers
24916 ** to all overrideable system calls.
24918 static struct unix_syscall {
24919 const char *zName; /* Name of the sytem call */
24920 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
24921 sqlite3_syscall_ptr pDefault; /* Default value */
24922 } aSyscall[] = {
24923 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
24924 #define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
24926 { "close", (sqlite3_syscall_ptr)close, 0 },
24927 #define osClose ((int(*)(int))aSyscall[1].pCurrent)
24929 { "access", (sqlite3_syscall_ptr)access, 0 },
24930 #define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
24932 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
24933 #define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
24935 { "stat", (sqlite3_syscall_ptr)stat, 0 },
24936 #define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
24939 ** The DJGPP compiler environment looks mostly like Unix, but it
24940 ** lacks the fcntl() system call. So redefine fcntl() to be something
24941 ** that always succeeds. This means that locking does not occur under
24942 ** DJGPP. But it is DOS - what did you expect?
24944 #ifdef __DJGPP__
24945 { "fstat", 0, 0 },
24946 #define osFstat(a,b,c) 0
24947 #else
24948 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
24949 #define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
24950 #endif
24952 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
24953 #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
24955 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
24956 #define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
24958 { "read", (sqlite3_syscall_ptr)read, 0 },
24959 #define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
24961 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
24962 { "pread", (sqlite3_syscall_ptr)pread, 0 },
24963 #else
24964 { "pread", (sqlite3_syscall_ptr)0, 0 },
24965 #endif
24966 #define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
24968 #if defined(USE_PREAD64)
24969 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
24970 #else
24971 { "pread64", (sqlite3_syscall_ptr)0, 0 },
24972 #endif
24973 #define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
24975 { "write", (sqlite3_syscall_ptr)write, 0 },
24976 #define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
24978 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
24979 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
24980 #else
24981 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
24982 #endif
24983 #define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
24984 aSyscall[12].pCurrent)
24986 #if defined(USE_PREAD64)
24987 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
24988 #else
24989 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
24990 #endif
24991 #define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
24992 aSyscall[13].pCurrent)
24994 #if SQLITE_ENABLE_LOCKING_STYLE
24995 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
24996 #else
24997 { "fchmod", (sqlite3_syscall_ptr)0, 0 },
24998 #endif
24999 #define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
25001 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
25002 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
25003 #else
25004 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
25005 #endif
25006 #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
25008 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
25009 #define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
25011 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
25012 #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
25014 }; /* End of the overrideable system calls */
25017 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
25018 ** "unix" VFSes. Return SQLITE_OK opon successfully updating the
25019 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
25020 ** system call named zName.
25022 static int unixSetSystemCall(
25023 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
25024 const char *zName, /* Name of system call to override */
25025 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
25027 unsigned int i;
25028 int rc = SQLITE_NOTFOUND;
25030 UNUSED_PARAMETER(pNotUsed);
25031 if( zName==0 ){
25032 /* If no zName is given, restore all system calls to their default
25033 ** settings and return NULL
25035 rc = SQLITE_OK;
25036 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
25037 if( aSyscall[i].pDefault ){
25038 aSyscall[i].pCurrent = aSyscall[i].pDefault;
25041 }else{
25042 /* If zName is specified, operate on only the one system call
25043 ** specified.
25045 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
25046 if( strcmp(zName, aSyscall[i].zName)==0 ){
25047 if( aSyscall[i].pDefault==0 ){
25048 aSyscall[i].pDefault = aSyscall[i].pCurrent;
25050 rc = SQLITE_OK;
25051 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
25052 aSyscall[i].pCurrent = pNewFunc;
25053 break;
25057 return rc;
25061 ** Return the value of a system call. Return NULL if zName is not a
25062 ** recognized system call name. NULL is also returned if the system call
25063 ** is currently undefined.
25065 static sqlite3_syscall_ptr unixGetSystemCall(
25066 sqlite3_vfs *pNotUsed,
25067 const char *zName
25069 unsigned int i;
25071 UNUSED_PARAMETER(pNotUsed);
25072 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
25073 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
25075 return 0;
25079 ** Return the name of the first system call after zName. If zName==NULL
25080 ** then return the name of the first system call. Return NULL if zName
25081 ** is the last system call or if zName is not the name of a valid
25082 ** system call.
25084 static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
25085 int i = -1;
25087 UNUSED_PARAMETER(p);
25088 if( zName ){
25089 for(i=0; i<ArraySize(aSyscall)-1; i++){
25090 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
25093 for(i++; i<ArraySize(aSyscall); i++){
25094 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
25096 return 0;
25100 ** Retry open() calls that fail due to EINTR
25102 static int robust_open(const char *z, int f, int m){
25103 int rc;
25104 do{ rc = osOpen(z,f,m); }while( rc<0 && errno==EINTR );
25105 return rc;
25109 ** Helper functions to obtain and relinquish the global mutex. The
25110 ** global mutex is used to protect the unixInodeInfo and
25111 ** vxworksFileId objects used by this file, all of which may be
25112 ** shared by multiple threads.
25114 ** Function unixMutexHeld() is used to assert() that the global mutex
25115 ** is held when required. This function is only used as part of assert()
25116 ** statements. e.g.
25118 ** unixEnterMutex()
25119 ** assert( unixMutexHeld() );
25120 ** unixEnterLeave()
25122 static void unixEnterMutex(void){
25123 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
25125 static void unixLeaveMutex(void){
25126 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
25128 #ifdef SQLITE_DEBUG
25129 static int unixMutexHeld(void) {
25130 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
25132 #endif
25135 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
25137 ** Helper function for printing out trace information from debugging
25138 ** binaries. This returns the string represetation of the supplied
25139 ** integer lock-type.
25141 static const char *azFileLock(int eFileLock){
25142 switch( eFileLock ){
25143 case NO_LOCK: return "NONE";
25144 case SHARED_LOCK: return "SHARED";
25145 case RESERVED_LOCK: return "RESERVED";
25146 case PENDING_LOCK: return "PENDING";
25147 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
25149 return "ERROR";
25151 #endif
25153 #ifdef SQLITE_LOCK_TRACE
25155 ** Print out information about all locking operations.
25157 ** This routine is used for troubleshooting locks on multithreaded
25158 ** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
25159 ** command-line option on the compiler. This code is normally
25160 ** turned off.
25162 static int lockTrace(int fd, int op, struct flock *p){
25163 char *zOpName, *zType;
25164 int s;
25165 int savedErrno;
25166 if( op==F_GETLK ){
25167 zOpName = "GETLK";
25168 }else if( op==F_SETLK ){
25169 zOpName = "SETLK";
25170 }else{
25171 s = osFcntl(fd, op, p);
25172 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
25173 return s;
25175 if( p->l_type==F_RDLCK ){
25176 zType = "RDLCK";
25177 }else if( p->l_type==F_WRLCK ){
25178 zType = "WRLCK";
25179 }else if( p->l_type==F_UNLCK ){
25180 zType = "UNLCK";
25181 }else{
25182 assert( 0 );
25184 assert( p->l_whence==SEEK_SET );
25185 s = osFcntl(fd, op, p);
25186 savedErrno = errno;
25187 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
25188 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
25189 (int)p->l_pid, s);
25190 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
25191 struct flock l2;
25192 l2 = *p;
25193 osFcntl(fd, F_GETLK, &l2);
25194 if( l2.l_type==F_RDLCK ){
25195 zType = "RDLCK";
25196 }else if( l2.l_type==F_WRLCK ){
25197 zType = "WRLCK";
25198 }else if( l2.l_type==F_UNLCK ){
25199 zType = "UNLCK";
25200 }else{
25201 assert( 0 );
25203 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
25204 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
25206 errno = savedErrno;
25207 return s;
25209 #undef osFcntl
25210 #define osFcntl lockTrace
25211 #endif /* SQLITE_LOCK_TRACE */
25214 ** Retry ftruncate() calls that fail due to EINTR
25216 static int robust_ftruncate(int h, sqlite3_int64 sz){
25217 int rc;
25218 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
25219 return rc;
25223 ** This routine translates a standard POSIX errno code into something
25224 ** useful to the clients of the sqlite3 functions. Specifically, it is
25225 ** intended to translate a variety of "try again" errors into SQLITE_BUSY
25226 ** and a variety of "please close the file descriptor NOW" errors into
25227 ** SQLITE_IOERR
25229 ** Errors during initialization of locks, or file system support for locks,
25230 ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
25232 static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
25233 switch (posixError) {
25234 #if 0
25235 /* At one point this code was not commented out. In theory, this branch
25236 ** should never be hit, as this function should only be called after
25237 ** a locking-related function (i.e. fcntl()) has returned non-zero with
25238 ** the value of errno as the first argument. Since a system call has failed,
25239 ** errno should be non-zero.
25241 ** Despite this, if errno really is zero, we still don't want to return
25242 ** SQLITE_OK. The system call failed, and *some* SQLite error should be
25243 ** propagated back to the caller. Commenting this branch out means errno==0
25244 ** will be handled by the "default:" case below.
25246 case 0:
25247 return SQLITE_OK;
25248 #endif
25250 case EAGAIN:
25251 case ETIMEDOUT:
25252 case EBUSY:
25253 case EINTR:
25254 case ENOLCK:
25255 /* random NFS retry error, unless during file system support
25256 * introspection, in which it actually means what it says */
25257 return SQLITE_BUSY;
25259 case EACCES:
25260 /* EACCES is like EAGAIN during locking operations, but not any other time*/
25261 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
25262 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
25263 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
25264 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
25265 return SQLITE_BUSY;
25267 /* else fall through */
25268 case EPERM:
25269 return SQLITE_PERM;
25271 /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
25272 ** this module never makes such a call. And the code in SQLite itself
25273 ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
25274 ** this case is also commented out. If the system does set errno to EDEADLK,
25275 ** the default SQLITE_IOERR_XXX code will be returned. */
25276 #if 0
25277 case EDEADLK:
25278 return SQLITE_IOERR_BLOCKED;
25279 #endif
25281 #if EOPNOTSUPP!=ENOTSUP
25282 case EOPNOTSUPP:
25283 /* something went terribly awry, unless during file system support
25284 * introspection, in which it actually means what it says */
25285 #endif
25286 #ifdef ENOTSUP
25287 case ENOTSUP:
25288 /* invalid fd, unless during file system support introspection, in which
25289 * it actually means what it says */
25290 #endif
25291 case EIO:
25292 case EBADF:
25293 case EINVAL:
25294 case ENOTCONN:
25295 case ENODEV:
25296 case ENXIO:
25297 case ENOENT:
25298 #ifdef ESTALE /* ESTALE is not defined on Interix systems */
25299 case ESTALE:
25300 #endif
25301 case ENOSYS:
25302 /* these should force the client to close the file and reconnect */
25304 default:
25305 return sqliteIOErr;
25311 /******************************************************************************
25312 ****************** Begin Unique File ID Utility Used By VxWorks ***************
25314 ** On most versions of unix, we can get a unique ID for a file by concatenating
25315 ** the device number and the inode number. But this does not work on VxWorks.
25316 ** On VxWorks, a unique file id must be based on the canonical filename.
25318 ** A pointer to an instance of the following structure can be used as a
25319 ** unique file ID in VxWorks. Each instance of this structure contains
25320 ** a copy of the canonical filename. There is also a reference count.
25321 ** The structure is reclaimed when the number of pointers to it drops to
25322 ** zero.
25324 ** There are never very many files open at one time and lookups are not
25325 ** a performance-critical path, so it is sufficient to put these
25326 ** structures on a linked list.
25328 struct vxworksFileId {
25329 struct vxworksFileId *pNext; /* Next in a list of them all */
25330 int nRef; /* Number of references to this one */
25331 int nName; /* Length of the zCanonicalName[] string */
25332 char *zCanonicalName; /* Canonical filename */
25335 #if OS_VXWORKS
25337 ** All unique filenames are held on a linked list headed by this
25338 ** variable:
25340 static struct vxworksFileId *vxworksFileList = 0;
25343 ** Simplify a filename into its canonical form
25344 ** by making the following changes:
25346 ** * removing any trailing and duplicate /
25347 ** * convert /./ into just /
25348 ** * convert /A/../ where A is any simple name into just /
25350 ** Changes are made in-place. Return the new name length.
25352 ** The original filename is in z[0..n-1]. Return the number of
25353 ** characters in the simplified name.
25355 static int vxworksSimplifyName(char *z, int n){
25356 int i, j;
25357 while( n>1 && z[n-1]=='/' ){ n--; }
25358 for(i=j=0; i<n; i++){
25359 if( z[i]=='/' ){
25360 if( z[i+1]=='/' ) continue;
25361 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
25362 i += 1;
25363 continue;
25365 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
25366 while( j>0 && z[j-1]!='/' ){ j--; }
25367 if( j>0 ){ j--; }
25368 i += 2;
25369 continue;
25372 z[j++] = z[i];
25374 z[j] = 0;
25375 return j;
25379 ** Find a unique file ID for the given absolute pathname. Return
25380 ** a pointer to the vxworksFileId object. This pointer is the unique
25381 ** file ID.
25383 ** The nRef field of the vxworksFileId object is incremented before
25384 ** the object is returned. A new vxworksFileId object is created
25385 ** and added to the global list if necessary.
25387 ** If a memory allocation error occurs, return NULL.
25389 static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
25390 struct vxworksFileId *pNew; /* search key and new file ID */
25391 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
25392 int n; /* Length of zAbsoluteName string */
25394 assert( zAbsoluteName[0]=='/' );
25395 n = (int)strlen(zAbsoluteName);
25396 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
25397 if( pNew==0 ) return 0;
25398 pNew->zCanonicalName = (char*)&pNew[1];
25399 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
25400 n = vxworksSimplifyName(pNew->zCanonicalName, n);
25402 /* Search for an existing entry that matching the canonical name.
25403 ** If found, increment the reference count and return a pointer to
25404 ** the existing file ID.
25406 unixEnterMutex();
25407 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
25408 if( pCandidate->nName==n
25409 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
25411 sqlite3_free(pNew);
25412 pCandidate->nRef++;
25413 unixLeaveMutex();
25414 return pCandidate;
25418 /* No match was found. We will make a new file ID */
25419 pNew->nRef = 1;
25420 pNew->nName = n;
25421 pNew->pNext = vxworksFileList;
25422 vxworksFileList = pNew;
25423 unixLeaveMutex();
25424 return pNew;
25428 ** Decrement the reference count on a vxworksFileId object. Free
25429 ** the object when the reference count reaches zero.
25431 static void vxworksReleaseFileId(struct vxworksFileId *pId){
25432 unixEnterMutex();
25433 assert( pId->nRef>0 );
25434 pId->nRef--;
25435 if( pId->nRef==0 ){
25436 struct vxworksFileId **pp;
25437 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
25438 assert( *pp==pId );
25439 *pp = pId->pNext;
25440 sqlite3_free(pId);
25442 unixLeaveMutex();
25444 #endif /* OS_VXWORKS */
25445 /*************** End of Unique File ID Utility Used By VxWorks ****************
25446 ******************************************************************************/
25449 /******************************************************************************
25450 *************************** Posix Advisory Locking ****************************
25452 ** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
25453 ** section 6.5.2.2 lines 483 through 490 specify that when a process
25454 ** sets or clears a lock, that operation overrides any prior locks set
25455 ** by the same process. It does not explicitly say so, but this implies
25456 ** that it overrides locks set by the same process using a different
25457 ** file descriptor. Consider this test case:
25459 ** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
25460 ** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
25462 ** Suppose ./file1 and ./file2 are really the same file (because
25463 ** one is a hard or symbolic link to the other) then if you set
25464 ** an exclusive lock on fd1, then try to get an exclusive lock
25465 ** on fd2, it works. I would have expected the second lock to
25466 ** fail since there was already a lock on the file due to fd1.
25467 ** But not so. Since both locks came from the same process, the
25468 ** second overrides the first, even though they were on different
25469 ** file descriptors opened on different file names.
25471 ** This means that we cannot use POSIX locks to synchronize file access
25472 ** among competing threads of the same process. POSIX locks will work fine
25473 ** to synchronize access for threads in separate processes, but not
25474 ** threads within the same process.
25476 ** To work around the problem, SQLite has to manage file locks internally
25477 ** on its own. Whenever a new database is opened, we have to find the
25478 ** specific inode of the database file (the inode is determined by the
25479 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
25480 ** and check for locks already existing on that inode. When locks are
25481 ** created or removed, we have to look at our own internal record of the
25482 ** locks to see if another thread has previously set a lock on that same
25483 ** inode.
25485 ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
25486 ** For VxWorks, we have to use the alternative unique ID system based on
25487 ** canonical filename and implemented in the previous division.)
25489 ** The sqlite3_file structure for POSIX is no longer just an integer file
25490 ** descriptor. It is now a structure that holds the integer file
25491 ** descriptor and a pointer to a structure that describes the internal
25492 ** locks on the corresponding inode. There is one locking structure
25493 ** per inode, so if the same inode is opened twice, both unixFile structures
25494 ** point to the same locking structure. The locking structure keeps
25495 ** a reference count (so we will know when to delete it) and a "cnt"
25496 ** field that tells us its internal lock status. cnt==0 means the
25497 ** file is unlocked. cnt==-1 means the file has an exclusive lock.
25498 ** cnt>0 means there are cnt shared locks on the file.
25500 ** Any attempt to lock or unlock a file first checks the locking
25501 ** structure. The fcntl() system call is only invoked to set a
25502 ** POSIX lock if the internal lock structure transitions between
25503 ** a locked and an unlocked state.
25505 ** But wait: there are yet more problems with POSIX advisory locks.
25507 ** If you close a file descriptor that points to a file that has locks,
25508 ** all locks on that file that are owned by the current process are
25509 ** released. To work around this problem, each unixInodeInfo object
25510 ** maintains a count of the number of pending locks on tha inode.
25511 ** When an attempt is made to close an unixFile, if there are
25512 ** other unixFile open on the same inode that are holding locks, the call
25513 ** to close() the file descriptor is deferred until all of the locks clear.
25514 ** The unixInodeInfo structure keeps a list of file descriptors that need to
25515 ** be closed and that list is walked (and cleared) when the last lock
25516 ** clears.
25518 ** Yet another problem: LinuxThreads do not play well with posix locks.
25520 ** Many older versions of linux use the LinuxThreads library which is
25521 ** not posix compliant. Under LinuxThreads, a lock created by thread
25522 ** A cannot be modified or overridden by a different thread B.
25523 ** Only thread A can modify the lock. Locking behavior is correct
25524 ** if the appliation uses the newer Native Posix Thread Library (NPTL)
25525 ** on linux - with NPTL a lock created by thread A can override locks
25526 ** in thread B. But there is no way to know at compile-time which
25527 ** threading library is being used. So there is no way to know at
25528 ** compile-time whether or not thread A can override locks on thread B.
25529 ** One has to do a run-time check to discover the behavior of the
25530 ** current process.
25532 ** SQLite used to support LinuxThreads. But support for LinuxThreads
25533 ** was dropped beginning with version 3.7.0. SQLite will still work with
25534 ** LinuxThreads provided that (1) there is no more than one connection
25535 ** per database file in the same process and (2) database connections
25536 ** do not move across threads.
25540 ** An instance of the following structure serves as the key used
25541 ** to locate a particular unixInodeInfo object.
25543 struct unixFileId {
25544 dev_t dev; /* Device number */
25545 #if OS_VXWORKS
25546 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
25547 #else
25548 ino_t ino; /* Inode number */
25549 #endif
25553 ** An instance of the following structure is allocated for each open
25554 ** inode. Or, on LinuxThreads, there is one of these structures for
25555 ** each inode opened by each thread.
25557 ** A single inode can have multiple file descriptors, so each unixFile
25558 ** structure contains a pointer to an instance of this object and this
25559 ** object keeps a count of the number of unixFile pointing to it.
25561 struct unixInodeInfo {
25562 struct unixFileId fileId; /* The lookup key */
25563 int nShared; /* Number of SHARED locks held */
25564 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
25565 unsigned char bProcessLock; /* An exclusive process lock is held */
25566 int nRef; /* Number of pointers to this structure */
25567 unixShmNode *pShmNode; /* Shared memory associated with this inode */
25568 int nLock; /* Number of outstanding file locks */
25569 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
25570 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
25571 unixInodeInfo *pPrev; /* .... doubly linked */
25572 #if SQLITE_ENABLE_LOCKING_STYLE
25573 unsigned long long sharedByte; /* for AFP simulated shared lock */
25574 #endif
25575 #if OS_VXWORKS
25576 sem_t *pSem; /* Named POSIX semaphore */
25577 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
25578 #endif
25582 ** A lists of all unixInodeInfo objects.
25584 static unixInodeInfo *inodeList = 0;
25588 ** This function - unixLogError_x(), is only ever called via the macro
25589 ** unixLogError().
25591 ** It is invoked after an error occurs in an OS function and errno has been
25592 ** set. It logs a message using sqlite3_log() containing the current value of
25593 ** errno and, if possible, the human-readable equivalent from strerror() or
25594 ** strerror_r().
25596 ** The first argument passed to the macro should be the error code that
25597 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
25598 ** The two subsequent arguments should be the name of the OS function that
25599 ** failed (e.g. "unlink", "open") and the the associated file-system path,
25600 ** if any.
25602 #define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
25603 static int unixLogErrorAtLine(
25604 int errcode, /* SQLite error code */
25605 const char *zFunc, /* Name of OS function that failed */
25606 const char *zPath, /* File path associated with error */
25607 int iLine /* Source line number where error occurred */
25609 char *zErr; /* Message from strerror() or equivalent */
25610 int iErrno = errno; /* Saved syscall error number */
25612 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
25613 ** the strerror() function to obtain the human-readable error message
25614 ** equivalent to errno. Otherwise, use strerror_r().
25616 #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
25617 char aErr[80];
25618 memset(aErr, 0, sizeof(aErr));
25619 zErr = aErr;
25621 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
25622 ** assume that the system provides the the GNU version of strerror_r() that
25623 ** returns a pointer to a buffer containing the error message. That pointer
25624 ** may point to aErr[], or it may point to some static storage somewhere.
25625 ** Otherwise, assume that the system provides the POSIX version of
25626 ** strerror_r(), which always writes an error message into aErr[].
25628 ** If the code incorrectly assumes that it is the POSIX version that is
25629 ** available, the error message will often be an empty string. Not a
25630 ** huge problem. Incorrectly concluding that the GNU version is available
25631 ** could lead to a segfault though.
25633 #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
25634 zErr =
25635 # endif
25636 strerror_r(iErrno, aErr, sizeof(aErr)-1);
25638 #elif SQLITE_THREADSAFE
25639 /* This is a threadsafe build, but strerror_r() is not available. */
25640 zErr = "";
25641 #else
25642 /* Non-threadsafe build, use strerror(). */
25643 zErr = strerror(iErrno);
25644 #endif
25646 assert( errcode!=SQLITE_OK );
25647 if( zPath==0 ) zPath = "";
25648 sqlite3_log(errcode,
25649 "os_unix.c:%d: (%d) %s(%s) - %s",
25650 iLine, iErrno, zFunc, zPath, zErr
25653 return errcode;
25657 ** Close a file descriptor.
25659 ** We assume that close() almost always works, since it is only in a
25660 ** very sick application or on a very sick platform that it might fail.
25661 ** If it does fail, simply leak the file descriptor, but do log the
25662 ** error.
25664 ** Note that it is not safe to retry close() after EINTR since the
25665 ** file descriptor might have already been reused by another thread.
25666 ** So we don't even try to recover from an EINTR. Just log the error
25667 ** and move on.
25669 static void robust_close(unixFile *pFile, int h, int lineno){
25670 if( osClose(h) ){
25671 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
25672 pFile ? pFile->zPath : 0, lineno);
25677 ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
25679 static void closePendingFds(unixFile *pFile){
25680 unixInodeInfo *pInode = pFile->pInode;
25681 UnixUnusedFd *p;
25682 UnixUnusedFd *pNext;
25683 for(p=pInode->pUnused; p; p=pNext){
25684 pNext = p->pNext;
25685 robust_close(pFile, p->fd, __LINE__);
25686 sqlite3_free(p);
25688 pInode->pUnused = 0;
25692 ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
25694 ** The mutex entered using the unixEnterMutex() function must be held
25695 ** when this function is called.
25697 static void releaseInodeInfo(unixFile *pFile){
25698 unixInodeInfo *pInode = pFile->pInode;
25699 assert( unixMutexHeld() );
25700 if( ALWAYS(pInode) ){
25701 pInode->nRef--;
25702 if( pInode->nRef==0 ){
25703 assert( pInode->pShmNode==0 );
25704 closePendingFds(pFile);
25705 if( pInode->pPrev ){
25706 assert( pInode->pPrev->pNext==pInode );
25707 pInode->pPrev->pNext = pInode->pNext;
25708 }else{
25709 assert( inodeList==pInode );
25710 inodeList = pInode->pNext;
25712 if( pInode->pNext ){
25713 assert( pInode->pNext->pPrev==pInode );
25714 pInode->pNext->pPrev = pInode->pPrev;
25716 sqlite3_free(pInode);
25722 ** Given a file descriptor, locate the unixInodeInfo object that
25723 ** describes that file descriptor. Create a new one if necessary. The
25724 ** return value might be uninitialized if an error occurs.
25726 ** The mutex entered using the unixEnterMutex() function must be held
25727 ** when this function is called.
25729 ** Return an appropriate error code.
25731 static int findInodeInfo(
25732 unixFile *pFile, /* Unix file with file desc used in the key */
25733 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
25735 int rc; /* System call return code */
25736 int fd; /* The file descriptor for pFile */
25737 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
25738 struct stat statbuf; /* Low-level file information */
25739 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
25741 assert( unixMutexHeld() );
25743 /* Get low-level information about the file that we can used to
25744 ** create a unique name for the file.
25746 fd = pFile->h;
25747 rc = osFstat(fd, &statbuf);
25748 if( rc!=0 ){
25749 pFile->lastErrno = errno;
25750 #ifdef EOVERFLOW
25751 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
25752 #endif
25753 return SQLITE_IOERR;
25756 #ifdef __APPLE__
25757 /* On OS X on an msdos filesystem, the inode number is reported
25758 ** incorrectly for zero-size files. See ticket #3260. To work
25759 ** around this problem (we consider it a bug in OS X, not SQLite)
25760 ** we always increase the file size to 1 by writing a single byte
25761 ** prior to accessing the inode number. The one byte written is
25762 ** an ASCII 'S' character which also happens to be the first byte
25763 ** in the header of every SQLite database. In this way, if there
25764 ** is a race condition such that another thread has already populated
25765 ** the first page of the database, no damage is done.
25767 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
25768 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
25769 if( rc!=1 ){
25770 pFile->lastErrno = errno;
25771 return SQLITE_IOERR;
25773 rc = osFstat(fd, &statbuf);
25774 if( rc!=0 ){
25775 pFile->lastErrno = errno;
25776 return SQLITE_IOERR;
25779 #endif
25781 memset(&fileId, 0, sizeof(fileId));
25782 fileId.dev = statbuf.st_dev;
25783 #if OS_VXWORKS
25784 fileId.pId = pFile->pId;
25785 #else
25786 fileId.ino = statbuf.st_ino;
25787 #endif
25788 pInode = inodeList;
25789 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
25790 pInode = pInode->pNext;
25792 if( pInode==0 ){
25793 pInode = sqlite3_malloc( sizeof(*pInode) );
25794 if( pInode==0 ){
25795 return SQLITE_NOMEM;
25797 memset(pInode, 0, sizeof(*pInode));
25798 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
25799 pInode->nRef = 1;
25800 pInode->pNext = inodeList;
25801 pInode->pPrev = 0;
25802 if( inodeList ) inodeList->pPrev = pInode;
25803 inodeList = pInode;
25804 }else{
25805 pInode->nRef++;
25807 *ppInode = pInode;
25808 return SQLITE_OK;
25813 ** This routine checks if there is a RESERVED lock held on the specified
25814 ** file by this or any other process. If such a lock is held, set *pResOut
25815 ** to a non-zero value otherwise *pResOut is set to zero. The return value
25816 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
25818 static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
25819 int rc = SQLITE_OK;
25820 int reserved = 0;
25821 unixFile *pFile = (unixFile*)id;
25823 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
25825 assert( pFile );
25826 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
25828 /* Check if a thread in this process holds such a lock */
25829 if( pFile->pInode->eFileLock>SHARED_LOCK ){
25830 reserved = 1;
25833 /* Otherwise see if some other process holds it.
25835 #ifndef __DJGPP__
25836 if( !reserved && !pFile->pInode->bProcessLock ){
25837 struct flock lock;
25838 lock.l_whence = SEEK_SET;
25839 lock.l_start = RESERVED_BYTE;
25840 lock.l_len = 1;
25841 lock.l_type = F_WRLCK;
25842 if( osFcntl(pFile->h, F_GETLK, &lock) ){
25843 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
25844 pFile->lastErrno = errno;
25845 } else if( lock.l_type!=F_UNLCK ){
25846 reserved = 1;
25849 #endif
25851 unixLeaveMutex();
25852 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
25854 *pResOut = reserved;
25855 return rc;
25859 ** Attempt to set a system-lock on the file pFile. The lock is
25860 ** described by pLock.
25862 ** If the pFile was opened read/write from unix-excl, then the only lock
25863 ** ever obtained is an exclusive lock, and it is obtained exactly once
25864 ** the first time any lock is attempted. All subsequent system locking
25865 ** operations become no-ops. Locking operations still happen internally,
25866 ** in order to coordinate access between separate database connections
25867 ** within this process, but all of that is handled in memory and the
25868 ** operating system does not participate.
25870 ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
25871 ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
25872 ** and is read-only.
25874 ** Zero is returned if the call completes successfully, or -1 if a call
25875 ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
25877 static int unixFileLock(unixFile *pFile, struct flock *pLock){
25878 int rc;
25879 unixInodeInfo *pInode = pFile->pInode;
25880 assert( unixMutexHeld() );
25881 assert( pInode!=0 );
25882 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
25883 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
25885 if( pInode->bProcessLock==0 ){
25886 struct flock lock;
25887 assert( pInode->nLock==0 );
25888 lock.l_whence = SEEK_SET;
25889 lock.l_start = SHARED_FIRST;
25890 lock.l_len = SHARED_SIZE;
25891 lock.l_type = F_WRLCK;
25892 rc = osFcntl(pFile->h, F_SETLK, &lock);
25893 if( rc<0 ) return rc;
25894 pInode->bProcessLock = 1;
25895 pInode->nLock++;
25896 }else{
25897 rc = 0;
25899 }else{
25900 rc = osFcntl(pFile->h, F_SETLK, pLock);
25902 return rc;
25906 ** Lock the file with the lock specified by parameter eFileLock - one
25907 ** of the following:
25909 ** (1) SHARED_LOCK
25910 ** (2) RESERVED_LOCK
25911 ** (3) PENDING_LOCK
25912 ** (4) EXCLUSIVE_LOCK
25914 ** Sometimes when requesting one lock state, additional lock states
25915 ** are inserted in between. The locking might fail on one of the later
25916 ** transitions leaving the lock state different from what it started but
25917 ** still short of its goal. The following chart shows the allowed
25918 ** transitions and the inserted intermediate states:
25920 ** UNLOCKED -> SHARED
25921 ** SHARED -> RESERVED
25922 ** SHARED -> (PENDING) -> EXCLUSIVE
25923 ** RESERVED -> (PENDING) -> EXCLUSIVE
25924 ** PENDING -> EXCLUSIVE
25926 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
25927 ** routine to lower a locking level.
25929 static int unixLock(sqlite3_file *id, int eFileLock){
25930 /* The following describes the implementation of the various locks and
25931 ** lock transitions in terms of the POSIX advisory shared and exclusive
25932 ** lock primitives (called read-locks and write-locks below, to avoid
25933 ** confusion with SQLite lock names). The algorithms are complicated
25934 ** slightly in order to be compatible with windows systems simultaneously
25935 ** accessing the same database file, in case that is ever required.
25937 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
25938 ** byte', each single bytes at well known offsets, and the 'shared byte
25939 ** range', a range of 510 bytes at a well known offset.
25941 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
25942 ** byte'. If this is successful, a random byte from the 'shared byte
25943 ** range' is read-locked and the lock on the 'pending byte' released.
25945 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
25946 ** A RESERVED lock is implemented by grabbing a write-lock on the
25947 ** 'reserved byte'.
25949 ** A process may only obtain a PENDING lock after it has obtained a
25950 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
25951 ** on the 'pending byte'. This ensures that no new SHARED locks can be
25952 ** obtained, but existing SHARED locks are allowed to persist. A process
25953 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
25954 ** This property is used by the algorithm for rolling back a journal file
25955 ** after a crash.
25957 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
25958 ** implemented by obtaining a write-lock on the entire 'shared byte
25959 ** range'. Since all other locks require a read-lock on one of the bytes
25960 ** within this range, this ensures that no other locks are held on the
25961 ** database.
25963 ** The reason a single byte cannot be used instead of the 'shared byte
25964 ** range' is that some versions of windows do not support read-locks. By
25965 ** locking a random byte from a range, concurrent SHARED locks may exist
25966 ** even if the locking primitive used is always a write-lock.
25968 int rc = SQLITE_OK;
25969 unixFile *pFile = (unixFile*)id;
25970 unixInodeInfo *pInode;
25971 struct flock lock;
25972 int tErrno = 0;
25974 assert( pFile );
25975 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
25976 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
25977 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
25979 /* If there is already a lock of this type or more restrictive on the
25980 ** unixFile, do nothing. Don't use the end_lock: exit path, as
25981 ** unixEnterMutex() hasn't been called yet.
25983 if( pFile->eFileLock>=eFileLock ){
25984 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
25985 azFileLock(eFileLock)));
25986 return SQLITE_OK;
25989 /* Make sure the locking sequence is correct.
25990 ** (1) We never move from unlocked to anything higher than shared lock.
25991 ** (2) SQLite never explicitly requests a pendig lock.
25992 ** (3) A shared lock is always held when a reserve lock is requested.
25994 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
25995 assert( eFileLock!=PENDING_LOCK );
25996 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
25998 /* This mutex is needed because pFile->pInode is shared across threads
26000 unixEnterMutex();
26001 pInode = pFile->pInode;
26003 /* If some thread using this PID has a lock via a different unixFile*
26004 ** handle that precludes the requested lock, return BUSY.
26006 if( (pFile->eFileLock!=pInode->eFileLock &&
26007 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
26009 rc = SQLITE_BUSY;
26010 goto end_lock;
26013 /* If a SHARED lock is requested, and some thread using this PID already
26014 ** has a SHARED or RESERVED lock, then increment reference counts and
26015 ** return SQLITE_OK.
26017 if( eFileLock==SHARED_LOCK &&
26018 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
26019 assert( eFileLock==SHARED_LOCK );
26020 assert( pFile->eFileLock==0 );
26021 assert( pInode->nShared>0 );
26022 pFile->eFileLock = SHARED_LOCK;
26023 pInode->nShared++;
26024 pInode->nLock++;
26025 goto end_lock;
26029 /* A PENDING lock is needed before acquiring a SHARED lock and before
26030 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
26031 ** be released.
26033 lock.l_len = 1L;
26034 lock.l_whence = SEEK_SET;
26035 if( eFileLock==SHARED_LOCK
26036 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
26038 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
26039 lock.l_start = PENDING_BYTE;
26040 if( unixFileLock(pFile, &lock) ){
26041 tErrno = errno;
26042 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
26043 if( rc!=SQLITE_BUSY ){
26044 pFile->lastErrno = tErrno;
26046 goto end_lock;
26051 /* If control gets to this point, then actually go ahead and make
26052 ** operating system calls for the specified lock.
26054 if( eFileLock==SHARED_LOCK ){
26055 assert( pInode->nShared==0 );
26056 assert( pInode->eFileLock==0 );
26057 assert( rc==SQLITE_OK );
26059 /* Now get the read-lock */
26060 lock.l_start = SHARED_FIRST;
26061 lock.l_len = SHARED_SIZE;
26062 if( unixFileLock(pFile, &lock) ){
26063 tErrno = errno;
26064 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
26067 /* Drop the temporary PENDING lock */
26068 lock.l_start = PENDING_BYTE;
26069 lock.l_len = 1L;
26070 lock.l_type = F_UNLCK;
26071 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
26072 /* This could happen with a network mount */
26073 tErrno = errno;
26074 rc = SQLITE_IOERR_UNLOCK;
26077 if( rc ){
26078 if( rc!=SQLITE_BUSY ){
26079 pFile->lastErrno = tErrno;
26081 goto end_lock;
26082 }else{
26083 pFile->eFileLock = SHARED_LOCK;
26084 pInode->nLock++;
26085 pInode->nShared = 1;
26087 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
26088 /* We are trying for an exclusive lock but another thread in this
26089 ** same process is still holding a shared lock. */
26090 rc = SQLITE_BUSY;
26091 }else{
26092 /* The request was for a RESERVED or EXCLUSIVE lock. It is
26093 ** assumed that there is a SHARED or greater lock on the file
26094 ** already.
26096 assert( 0!=pFile->eFileLock );
26097 lock.l_type = F_WRLCK;
26099 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
26100 if( eFileLock==RESERVED_LOCK ){
26101 lock.l_start = RESERVED_BYTE;
26102 lock.l_len = 1L;
26103 }else{
26104 lock.l_start = SHARED_FIRST;
26105 lock.l_len = SHARED_SIZE;
26108 if( unixFileLock(pFile, &lock) ){
26109 tErrno = errno;
26110 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
26111 if( rc!=SQLITE_BUSY ){
26112 pFile->lastErrno = tErrno;
26118 #ifndef NDEBUG
26119 /* Set up the transaction-counter change checking flags when
26120 ** transitioning from a SHARED to a RESERVED lock. The change
26121 ** from SHARED to RESERVED marks the beginning of a normal
26122 ** write operation (not a hot journal rollback).
26124 if( rc==SQLITE_OK
26125 && pFile->eFileLock<=SHARED_LOCK
26126 && eFileLock==RESERVED_LOCK
26128 pFile->transCntrChng = 0;
26129 pFile->dbUpdate = 0;
26130 pFile->inNormalWrite = 1;
26132 #endif
26135 if( rc==SQLITE_OK ){
26136 pFile->eFileLock = eFileLock;
26137 pInode->eFileLock = eFileLock;
26138 }else if( eFileLock==EXCLUSIVE_LOCK ){
26139 pFile->eFileLock = PENDING_LOCK;
26140 pInode->eFileLock = PENDING_LOCK;
26143 end_lock:
26144 unixLeaveMutex();
26145 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
26146 rc==SQLITE_OK ? "ok" : "failed"));
26147 return rc;
26151 ** Add the file descriptor used by file handle pFile to the corresponding
26152 ** pUnused list.
26154 static void setPendingFd(unixFile *pFile){
26155 unixInodeInfo *pInode = pFile->pInode;
26156 UnixUnusedFd *p = pFile->pUnused;
26157 p->pNext = pInode->pUnused;
26158 pInode->pUnused = p;
26159 pFile->h = -1;
26160 pFile->pUnused = 0;
26164 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
26165 ** must be either NO_LOCK or SHARED_LOCK.
26167 ** If the locking level of the file descriptor is already at or below
26168 ** the requested locking level, this routine is a no-op.
26170 ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
26171 ** the byte range is divided into 2 parts and the first part is unlocked then
26172 ** set to a read lock, then the other part is simply unlocked. This works
26173 ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
26174 ** remove the write lock on a region when a read lock is set.
26176 static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
26177 unixFile *pFile = (unixFile*)id;
26178 unixInodeInfo *pInode;
26179 struct flock lock;
26180 int rc = SQLITE_OK;
26182 assert( pFile );
26183 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
26184 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
26185 getpid()));
26187 assert( eFileLock<=SHARED_LOCK );
26188 if( pFile->eFileLock<=eFileLock ){
26189 return SQLITE_OK;
26191 unixEnterMutex();
26192 pInode = pFile->pInode;
26193 assert( pInode->nShared!=0 );
26194 if( pFile->eFileLock>SHARED_LOCK ){
26195 assert( pInode->eFileLock==pFile->eFileLock );
26197 #ifndef NDEBUG
26198 /* When reducing a lock such that other processes can start
26199 ** reading the database file again, make sure that the
26200 ** transaction counter was updated if any part of the database
26201 ** file changed. If the transaction counter is not updated,
26202 ** other connections to the same file might not realize that
26203 ** the file has changed and hence might not know to flush their
26204 ** cache. The use of a stale cache can lead to database corruption.
26206 pFile->inNormalWrite = 0;
26207 #endif
26209 /* downgrading to a shared lock on NFS involves clearing the write lock
26210 ** before establishing the readlock - to avoid a race condition we downgrade
26211 ** the lock in 2 blocks, so that part of the range will be covered by a
26212 ** write lock until the rest is covered by a read lock:
26213 ** 1: [WWWWW]
26214 ** 2: [....W]
26215 ** 3: [RRRRW]
26216 ** 4: [RRRR.]
26218 if( eFileLock==SHARED_LOCK ){
26220 #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
26221 (void)handleNFSUnlock;
26222 assert( handleNFSUnlock==0 );
26223 #endif
26224 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26225 if( handleNFSUnlock ){
26226 int tErrno; /* Error code from system call errors */
26227 off_t divSize = SHARED_SIZE - 1;
26229 lock.l_type = F_UNLCK;
26230 lock.l_whence = SEEK_SET;
26231 lock.l_start = SHARED_FIRST;
26232 lock.l_len = divSize;
26233 if( unixFileLock(pFile, &lock)==(-1) ){
26234 tErrno = errno;
26235 rc = SQLITE_IOERR_UNLOCK;
26236 if( IS_LOCK_ERROR(rc) ){
26237 pFile->lastErrno = tErrno;
26239 goto end_unlock;
26241 lock.l_type = F_RDLCK;
26242 lock.l_whence = SEEK_SET;
26243 lock.l_start = SHARED_FIRST;
26244 lock.l_len = divSize;
26245 if( unixFileLock(pFile, &lock)==(-1) ){
26246 tErrno = errno;
26247 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
26248 if( IS_LOCK_ERROR(rc) ){
26249 pFile->lastErrno = tErrno;
26251 goto end_unlock;
26253 lock.l_type = F_UNLCK;
26254 lock.l_whence = SEEK_SET;
26255 lock.l_start = SHARED_FIRST+divSize;
26256 lock.l_len = SHARED_SIZE-divSize;
26257 if( unixFileLock(pFile, &lock)==(-1) ){
26258 tErrno = errno;
26259 rc = SQLITE_IOERR_UNLOCK;
26260 if( IS_LOCK_ERROR(rc) ){
26261 pFile->lastErrno = tErrno;
26263 goto end_unlock;
26265 }else
26266 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
26268 lock.l_type = F_RDLCK;
26269 lock.l_whence = SEEK_SET;
26270 lock.l_start = SHARED_FIRST;
26271 lock.l_len = SHARED_SIZE;
26272 if( unixFileLock(pFile, &lock) ){
26273 /* In theory, the call to unixFileLock() cannot fail because another
26274 ** process is holding an incompatible lock. If it does, this
26275 ** indicates that the other process is not following the locking
26276 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
26277 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
26278 ** an assert to fail). */
26279 rc = SQLITE_IOERR_RDLOCK;
26280 pFile->lastErrno = errno;
26281 goto end_unlock;
26285 lock.l_type = F_UNLCK;
26286 lock.l_whence = SEEK_SET;
26287 lock.l_start = PENDING_BYTE;
26288 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
26289 if( unixFileLock(pFile, &lock)==0 ){
26290 pInode->eFileLock = SHARED_LOCK;
26291 }else{
26292 rc = SQLITE_IOERR_UNLOCK;
26293 pFile->lastErrno = errno;
26294 goto end_unlock;
26297 if( eFileLock==NO_LOCK ){
26298 /* Decrement the shared lock counter. Release the lock using an
26299 ** OS call only when all threads in this same process have released
26300 ** the lock.
26302 pInode->nShared--;
26303 if( pInode->nShared==0 ){
26304 lock.l_type = F_UNLCK;
26305 lock.l_whence = SEEK_SET;
26306 lock.l_start = lock.l_len = 0L;
26307 if( unixFileLock(pFile, &lock)==0 ){
26308 pInode->eFileLock = NO_LOCK;
26309 }else{
26310 rc = SQLITE_IOERR_UNLOCK;
26311 pFile->lastErrno = errno;
26312 pInode->eFileLock = NO_LOCK;
26313 pFile->eFileLock = NO_LOCK;
26317 /* Decrement the count of locks against this same file. When the
26318 ** count reaches zero, close any other file descriptors whose close
26319 ** was deferred because of outstanding locks.
26321 pInode->nLock--;
26322 assert( pInode->nLock>=0 );
26323 if( pInode->nLock==0 ){
26324 closePendingFds(pFile);
26328 end_unlock:
26329 unixLeaveMutex();
26330 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
26331 return rc;
26335 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
26336 ** must be either NO_LOCK or SHARED_LOCK.
26338 ** If the locking level of the file descriptor is already at or below
26339 ** the requested locking level, this routine is a no-op.
26341 static int unixUnlock(sqlite3_file *id, int eFileLock){
26342 return posixUnlock(id, eFileLock, 0);
26346 ** This function performs the parts of the "close file" operation
26347 ** common to all locking schemes. It closes the directory and file
26348 ** handles, if they are valid, and sets all fields of the unixFile
26349 ** structure to 0.
26351 ** It is *not* necessary to hold the mutex when this routine is called,
26352 ** even on VxWorks. A mutex will be acquired on VxWorks by the
26353 ** vxworksReleaseFileId() routine.
26355 static int closeUnixFile(sqlite3_file *id){
26356 unixFile *pFile = (unixFile*)id;
26357 if( pFile->h>=0 ){
26358 robust_close(pFile, pFile->h, __LINE__);
26359 pFile->h = -1;
26361 #if OS_VXWORKS
26362 if( pFile->pId ){
26363 if( pFile->isDelete ){
26364 osUnlink(pFile->pId->zCanonicalName);
26366 vxworksReleaseFileId(pFile->pId);
26367 pFile->pId = 0;
26369 #endif
26370 OSTRACE(("CLOSE %-3d\n", pFile->h));
26371 OpenCounter(-1);
26372 sqlite3_free(pFile->pUnused);
26373 memset(pFile, 0, sizeof(unixFile));
26374 return SQLITE_OK;
26378 ** Close a file.
26380 static int unixClose(sqlite3_file *id){
26381 int rc = SQLITE_OK;
26382 unixFile *pFile = (unixFile *)id;
26383 unixUnlock(id, NO_LOCK);
26384 unixEnterMutex();
26386 /* unixFile.pInode is always valid here. Otherwise, a different close
26387 ** routine (e.g. nolockClose()) would be called instead.
26389 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
26390 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
26391 /* If there are outstanding locks, do not actually close the file just
26392 ** yet because that would clear those locks. Instead, add the file
26393 ** descriptor to pInode->pUnused list. It will be automatically closed
26394 ** when the last lock is cleared.
26396 setPendingFd(pFile);
26398 releaseInodeInfo(pFile);
26399 rc = closeUnixFile(id);
26400 unixLeaveMutex();
26401 return rc;
26404 /************** End of the posix advisory lock implementation *****************
26405 ******************************************************************************/
26407 /******************************************************************************
26408 ****************************** No-op Locking **********************************
26410 ** Of the various locking implementations available, this is by far the
26411 ** simplest: locking is ignored. No attempt is made to lock the database
26412 ** file for reading or writing.
26414 ** This locking mode is appropriate for use on read-only databases
26415 ** (ex: databases that are burned into CD-ROM, for example.) It can
26416 ** also be used if the application employs some external mechanism to
26417 ** prevent simultaneous access of the same database by two or more
26418 ** database connections. But there is a serious risk of database
26419 ** corruption if this locking mode is used in situations where multiple
26420 ** database connections are accessing the same database file at the same
26421 ** time and one or more of those connections are writing.
26424 static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
26425 UNUSED_PARAMETER(NotUsed);
26426 *pResOut = 0;
26427 return SQLITE_OK;
26429 static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
26430 UNUSED_PARAMETER2(NotUsed, NotUsed2);
26431 return SQLITE_OK;
26433 static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
26434 UNUSED_PARAMETER2(NotUsed, NotUsed2);
26435 return SQLITE_OK;
26439 ** Close the file.
26441 static int nolockClose(sqlite3_file *id) {
26442 return closeUnixFile(id);
26445 /******************* End of the no-op lock implementation *********************
26446 ******************************************************************************/
26448 /******************************************************************************
26449 ************************* Begin dot-file Locking ******************************
26451 ** The dotfile locking implementation uses the existance of separate lock
26452 ** files in order to control access to the database. This works on just
26453 ** about every filesystem imaginable. But there are serious downsides:
26455 ** (1) There is zero concurrency. A single reader blocks all other
26456 ** connections from reading or writing the database.
26458 ** (2) An application crash or power loss can leave stale lock files
26459 ** sitting around that need to be cleared manually.
26461 ** Nevertheless, a dotlock is an appropriate locking mode for use if no
26462 ** other locking strategy is available.
26464 ** Dotfile locking works by creating a file in the same directory as the
26465 ** database and with the same name but with a ".lock" extension added.
26466 ** The existance of a lock file implies an EXCLUSIVE lock. All other lock
26467 ** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
26471 ** The file suffix added to the data base filename in order to create the
26472 ** lock file.
26474 #define DOTLOCK_SUFFIX ".lock"
26477 ** This routine checks if there is a RESERVED lock held on the specified
26478 ** file by this or any other process. If such a lock is held, set *pResOut
26479 ** to a non-zero value otherwise *pResOut is set to zero. The return value
26480 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
26482 ** In dotfile locking, either a lock exists or it does not. So in this
26483 ** variation of CheckReservedLock(), *pResOut is set to true if any lock
26484 ** is held on the file and false if the file is unlocked.
26486 static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
26487 int rc = SQLITE_OK;
26488 int reserved = 0;
26489 unixFile *pFile = (unixFile*)id;
26491 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
26493 assert( pFile );
26495 /* Check if a thread in this process holds such a lock */
26496 if( pFile->eFileLock>SHARED_LOCK ){
26497 /* Either this connection or some other connection in the same process
26498 ** holds a lock on the file. No need to check further. */
26499 reserved = 1;
26500 }else{
26501 /* The lock is held if and only if the lockfile exists */
26502 const char *zLockFile = (const char*)pFile->lockingContext;
26503 reserved = osAccess(zLockFile, 0)==0;
26505 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
26506 *pResOut = reserved;
26507 return rc;
26511 ** Lock the file with the lock specified by parameter eFileLock - one
26512 ** of the following:
26514 ** (1) SHARED_LOCK
26515 ** (2) RESERVED_LOCK
26516 ** (3) PENDING_LOCK
26517 ** (4) EXCLUSIVE_LOCK
26519 ** Sometimes when requesting one lock state, additional lock states
26520 ** are inserted in between. The locking might fail on one of the later
26521 ** transitions leaving the lock state different from what it started but
26522 ** still short of its goal. The following chart shows the allowed
26523 ** transitions and the inserted intermediate states:
26525 ** UNLOCKED -> SHARED
26526 ** SHARED -> RESERVED
26527 ** SHARED -> (PENDING) -> EXCLUSIVE
26528 ** RESERVED -> (PENDING) -> EXCLUSIVE
26529 ** PENDING -> EXCLUSIVE
26531 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
26532 ** routine to lower a locking level.
26534 ** With dotfile locking, we really only support state (4): EXCLUSIVE.
26535 ** But we track the other locking levels internally.
26537 static int dotlockLock(sqlite3_file *id, int eFileLock) {
26538 unixFile *pFile = (unixFile*)id;
26539 int fd;
26540 char *zLockFile = (char *)pFile->lockingContext;
26541 int rc = SQLITE_OK;
26544 /* If we have any lock, then the lock file already exists. All we have
26545 ** to do is adjust our internal record of the lock level.
26547 if( pFile->eFileLock > NO_LOCK ){
26548 pFile->eFileLock = eFileLock;
26549 /* Always update the timestamp on the old file */
26550 #ifdef HAVE_UTIME
26551 utime(zLockFile, NULL);
26552 #else
26553 utimes(zLockFile, NULL);
26554 #endif
26555 return SQLITE_OK;
26558 /* grab an exclusive lock */
26559 fd = robust_open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
26560 if( fd<0 ){
26561 /* failed to open/create the file, someone else may have stolen the lock */
26562 int tErrno = errno;
26563 if( EEXIST == tErrno ){
26564 rc = SQLITE_BUSY;
26565 } else {
26566 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
26567 if( IS_LOCK_ERROR(rc) ){
26568 pFile->lastErrno = tErrno;
26571 return rc;
26573 robust_close(pFile, fd, __LINE__);
26575 /* got it, set the type and return ok */
26576 pFile->eFileLock = eFileLock;
26577 return rc;
26581 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
26582 ** must be either NO_LOCK or SHARED_LOCK.
26584 ** If the locking level of the file descriptor is already at or below
26585 ** the requested locking level, this routine is a no-op.
26587 ** When the locking level reaches NO_LOCK, delete the lock file.
26589 static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
26590 unixFile *pFile = (unixFile*)id;
26591 char *zLockFile = (char *)pFile->lockingContext;
26593 assert( pFile );
26594 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
26595 pFile->eFileLock, getpid()));
26596 assert( eFileLock<=SHARED_LOCK );
26598 /* no-op if possible */
26599 if( pFile->eFileLock==eFileLock ){
26600 return SQLITE_OK;
26603 /* To downgrade to shared, simply update our internal notion of the
26604 ** lock state. No need to mess with the file on disk.
26606 if( eFileLock==SHARED_LOCK ){
26607 pFile->eFileLock = SHARED_LOCK;
26608 return SQLITE_OK;
26611 /* To fully unlock the database, delete the lock file */
26612 assert( eFileLock==NO_LOCK );
26613 if( osUnlink(zLockFile) ){
26614 int rc = 0;
26615 int tErrno = errno;
26616 if( ENOENT != tErrno ){
26617 rc = SQLITE_IOERR_UNLOCK;
26619 if( IS_LOCK_ERROR(rc) ){
26620 pFile->lastErrno = tErrno;
26622 return rc;
26624 pFile->eFileLock = NO_LOCK;
26625 return SQLITE_OK;
26629 ** Close a file. Make sure the lock has been released before closing.
26631 static int dotlockClose(sqlite3_file *id) {
26632 int rc;
26633 if( id ){
26634 unixFile *pFile = (unixFile*)id;
26635 dotlockUnlock(id, NO_LOCK);
26636 sqlite3_free(pFile->lockingContext);
26638 rc = closeUnixFile(id);
26639 return rc;
26641 /****************** End of the dot-file lock implementation *******************
26642 ******************************************************************************/
26644 /******************************************************************************
26645 ************************** Begin flock Locking ********************************
26647 ** Use the flock() system call to do file locking.
26649 ** flock() locking is like dot-file locking in that the various
26650 ** fine-grain locking levels supported by SQLite are collapsed into
26651 ** a single exclusive lock. In other words, SHARED, RESERVED, and
26652 ** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
26653 ** still works when you do this, but concurrency is reduced since
26654 ** only a single process can be reading the database at a time.
26656 ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
26657 ** compiling for VXWORKS.
26659 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
26662 ** Retry flock() calls that fail with EINTR
26664 #ifdef EINTR
26665 static int robust_flock(int fd, int op){
26666 int rc;
26667 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
26668 return rc;
26670 #else
26671 # define robust_flock(a,b) flock(a,b)
26672 #endif
26676 ** This routine checks if there is a RESERVED lock held on the specified
26677 ** file by this or any other process. If such a lock is held, set *pResOut
26678 ** to a non-zero value otherwise *pResOut is set to zero. The return value
26679 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
26681 static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
26682 int rc = SQLITE_OK;
26683 int reserved = 0;
26684 unixFile *pFile = (unixFile*)id;
26686 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
26688 assert( pFile );
26690 /* Check if a thread in this process holds such a lock */
26691 if( pFile->eFileLock>SHARED_LOCK ){
26692 reserved = 1;
26695 /* Otherwise see if some other process holds it. */
26696 if( !reserved ){
26697 /* attempt to get the lock */
26698 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
26699 if( !lrc ){
26700 /* got the lock, unlock it */
26701 lrc = robust_flock(pFile->h, LOCK_UN);
26702 if ( lrc ) {
26703 int tErrno = errno;
26704 /* unlock failed with an error */
26705 lrc = SQLITE_IOERR_UNLOCK;
26706 if( IS_LOCK_ERROR(lrc) ){
26707 pFile->lastErrno = tErrno;
26708 rc = lrc;
26711 } else {
26712 int tErrno = errno;
26713 reserved = 1;
26714 /* someone else might have it reserved */
26715 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
26716 if( IS_LOCK_ERROR(lrc) ){
26717 pFile->lastErrno = tErrno;
26718 rc = lrc;
26722 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
26724 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
26725 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
26726 rc = SQLITE_OK;
26727 reserved=1;
26729 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
26730 *pResOut = reserved;
26731 return rc;
26735 ** Lock the file with the lock specified by parameter eFileLock - one
26736 ** of the following:
26738 ** (1) SHARED_LOCK
26739 ** (2) RESERVED_LOCK
26740 ** (3) PENDING_LOCK
26741 ** (4) EXCLUSIVE_LOCK
26743 ** Sometimes when requesting one lock state, additional lock states
26744 ** are inserted in between. The locking might fail on one of the later
26745 ** transitions leaving the lock state different from what it started but
26746 ** still short of its goal. The following chart shows the allowed
26747 ** transitions and the inserted intermediate states:
26749 ** UNLOCKED -> SHARED
26750 ** SHARED -> RESERVED
26751 ** SHARED -> (PENDING) -> EXCLUSIVE
26752 ** RESERVED -> (PENDING) -> EXCLUSIVE
26753 ** PENDING -> EXCLUSIVE
26755 ** flock() only really support EXCLUSIVE locks. We track intermediate
26756 ** lock states in the sqlite3_file structure, but all locks SHARED or
26757 ** above are really EXCLUSIVE locks and exclude all other processes from
26758 ** access the file.
26760 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
26761 ** routine to lower a locking level.
26763 static int flockLock(sqlite3_file *id, int eFileLock) {
26764 int rc = SQLITE_OK;
26765 unixFile *pFile = (unixFile*)id;
26767 assert( pFile );
26769 /* if we already have a lock, it is exclusive.
26770 ** Just adjust level and punt on outta here. */
26771 if (pFile->eFileLock > NO_LOCK) {
26772 pFile->eFileLock = eFileLock;
26773 return SQLITE_OK;
26776 /* grab an exclusive lock */
26778 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
26779 int tErrno = errno;
26780 /* didn't get, must be busy */
26781 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
26782 if( IS_LOCK_ERROR(rc) ){
26783 pFile->lastErrno = tErrno;
26785 } else {
26786 /* got it, set the type and return ok */
26787 pFile->eFileLock = eFileLock;
26789 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
26790 rc==SQLITE_OK ? "ok" : "failed"));
26791 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
26792 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
26793 rc = SQLITE_BUSY;
26795 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
26796 return rc;
26801 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
26802 ** must be either NO_LOCK or SHARED_LOCK.
26804 ** If the locking level of the file descriptor is already at or below
26805 ** the requested locking level, this routine is a no-op.
26807 static int flockUnlock(sqlite3_file *id, int eFileLock) {
26808 unixFile *pFile = (unixFile*)id;
26810 assert( pFile );
26811 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
26812 pFile->eFileLock, getpid()));
26813 assert( eFileLock<=SHARED_LOCK );
26815 /* no-op if possible */
26816 if( pFile->eFileLock==eFileLock ){
26817 return SQLITE_OK;
26820 /* shared can just be set because we always have an exclusive */
26821 if (eFileLock==SHARED_LOCK) {
26822 pFile->eFileLock = eFileLock;
26823 return SQLITE_OK;
26826 /* no, really, unlock. */
26827 if( robust_flock(pFile->h, LOCK_UN) ){
26828 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
26829 return SQLITE_OK;
26830 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
26831 return SQLITE_IOERR_UNLOCK;
26832 }else{
26833 pFile->eFileLock = NO_LOCK;
26834 return SQLITE_OK;
26839 ** Close a file.
26841 static int flockClose(sqlite3_file *id) {
26842 if( id ){
26843 flockUnlock(id, NO_LOCK);
26845 return closeUnixFile(id);
26848 #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
26850 /******************* End of the flock lock implementation *********************
26851 ******************************************************************************/
26853 /******************************************************************************
26854 ************************ Begin Named Semaphore Locking ************************
26856 ** Named semaphore locking is only supported on VxWorks.
26858 ** Semaphore locking is like dot-lock and flock in that it really only
26859 ** supports EXCLUSIVE locking. Only a single process can read or write
26860 ** the database file at a time. This reduces potential concurrency, but
26861 ** makes the lock implementation much easier.
26863 #if OS_VXWORKS
26866 ** This routine checks if there is a RESERVED lock held on the specified
26867 ** file by this or any other process. If such a lock is held, set *pResOut
26868 ** to a non-zero value otherwise *pResOut is set to zero. The return value
26869 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
26871 static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
26872 int rc = SQLITE_OK;
26873 int reserved = 0;
26874 unixFile *pFile = (unixFile*)id;
26876 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
26878 assert( pFile );
26880 /* Check if a thread in this process holds such a lock */
26881 if( pFile->eFileLock>SHARED_LOCK ){
26882 reserved = 1;
26885 /* Otherwise see if some other process holds it. */
26886 if( !reserved ){
26887 sem_t *pSem = pFile->pInode->pSem;
26888 struct stat statBuf;
26890 if( sem_trywait(pSem)==-1 ){
26891 int tErrno = errno;
26892 if( EAGAIN != tErrno ){
26893 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
26894 pFile->lastErrno = tErrno;
26895 } else {
26896 /* someone else has the lock when we are in NO_LOCK */
26897 reserved = (pFile->eFileLock < SHARED_LOCK);
26899 }else{
26900 /* we could have it if we want it */
26901 sem_post(pSem);
26904 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
26906 *pResOut = reserved;
26907 return rc;
26911 ** Lock the file with the lock specified by parameter eFileLock - one
26912 ** of the following:
26914 ** (1) SHARED_LOCK
26915 ** (2) RESERVED_LOCK
26916 ** (3) PENDING_LOCK
26917 ** (4) EXCLUSIVE_LOCK
26919 ** Sometimes when requesting one lock state, additional lock states
26920 ** are inserted in between. The locking might fail on one of the later
26921 ** transitions leaving the lock state different from what it started but
26922 ** still short of its goal. The following chart shows the allowed
26923 ** transitions and the inserted intermediate states:
26925 ** UNLOCKED -> SHARED
26926 ** SHARED -> RESERVED
26927 ** SHARED -> (PENDING) -> EXCLUSIVE
26928 ** RESERVED -> (PENDING) -> EXCLUSIVE
26929 ** PENDING -> EXCLUSIVE
26931 ** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
26932 ** lock states in the sqlite3_file structure, but all locks SHARED or
26933 ** above are really EXCLUSIVE locks and exclude all other processes from
26934 ** access the file.
26936 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
26937 ** routine to lower a locking level.
26939 static int semLock(sqlite3_file *id, int eFileLock) {
26940 unixFile *pFile = (unixFile*)id;
26941 int fd;
26942 sem_t *pSem = pFile->pInode->pSem;
26943 int rc = SQLITE_OK;
26945 /* if we already have a lock, it is exclusive.
26946 ** Just adjust level and punt on outta here. */
26947 if (pFile->eFileLock > NO_LOCK) {
26948 pFile->eFileLock = eFileLock;
26949 rc = SQLITE_OK;
26950 goto sem_end_lock;
26953 /* lock semaphore now but bail out when already locked. */
26954 if( sem_trywait(pSem)==-1 ){
26955 rc = SQLITE_BUSY;
26956 goto sem_end_lock;
26959 /* got it, set the type and return ok */
26960 pFile->eFileLock = eFileLock;
26962 sem_end_lock:
26963 return rc;
26967 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
26968 ** must be either NO_LOCK or SHARED_LOCK.
26970 ** If the locking level of the file descriptor is already at or below
26971 ** the requested locking level, this routine is a no-op.
26973 static int semUnlock(sqlite3_file *id, int eFileLock) {
26974 unixFile *pFile = (unixFile*)id;
26975 sem_t *pSem = pFile->pInode->pSem;
26977 assert( pFile );
26978 assert( pSem );
26979 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
26980 pFile->eFileLock, getpid()));
26981 assert( eFileLock<=SHARED_LOCK );
26983 /* no-op if possible */
26984 if( pFile->eFileLock==eFileLock ){
26985 return SQLITE_OK;
26988 /* shared can just be set because we always have an exclusive */
26989 if (eFileLock==SHARED_LOCK) {
26990 pFile->eFileLock = eFileLock;
26991 return SQLITE_OK;
26994 /* no, really unlock. */
26995 if ( sem_post(pSem)==-1 ) {
26996 int rc, tErrno = errno;
26997 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
26998 if( IS_LOCK_ERROR(rc) ){
26999 pFile->lastErrno = tErrno;
27001 return rc;
27003 pFile->eFileLock = NO_LOCK;
27004 return SQLITE_OK;
27008 ** Close a file.
27010 static int semClose(sqlite3_file *id) {
27011 if( id ){
27012 unixFile *pFile = (unixFile*)id;
27013 semUnlock(id, NO_LOCK);
27014 assert( pFile );
27015 unixEnterMutex();
27016 releaseInodeInfo(pFile);
27017 unixLeaveMutex();
27018 closeUnixFile(id);
27020 return SQLITE_OK;
27023 #endif /* OS_VXWORKS */
27025 ** Named semaphore locking is only available on VxWorks.
27027 *************** End of the named semaphore lock implementation ****************
27028 ******************************************************************************/
27031 /******************************************************************************
27032 *************************** Begin AFP Locking *********************************
27034 ** AFP is the Apple Filing Protocol. AFP is a network filesystem found
27035 ** on Apple Macintosh computers - both OS9 and OSX.
27037 ** Third-party implementations of AFP are available. But this code here
27038 ** only works on OSX.
27041 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
27043 ** The afpLockingContext structure contains all afp lock specific state
27045 typedef struct afpLockingContext afpLockingContext;
27046 struct afpLockingContext {
27047 int reserved;
27048 const char *dbPath; /* Name of the open file */
27051 struct ByteRangeLockPB2
27053 unsigned long long offset; /* offset to first byte to lock */
27054 unsigned long long length; /* nbr of bytes to lock */
27055 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
27056 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
27057 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
27058 int fd; /* file desc to assoc this lock with */
27061 #define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
27064 ** This is a utility for setting or clearing a bit-range lock on an
27065 ** AFP filesystem.
27067 ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
27069 static int afpSetLock(
27070 const char *path, /* Name of the file to be locked or unlocked */
27071 unixFile *pFile, /* Open file descriptor on path */
27072 unsigned long long offset, /* First byte to be locked */
27073 unsigned long long length, /* Number of bytes to lock */
27074 int setLockFlag /* True to set lock. False to clear lock */
27076 struct ByteRangeLockPB2 pb;
27077 int err;
27079 pb.unLockFlag = setLockFlag ? 0 : 1;
27080 pb.startEndFlag = 0;
27081 pb.offset = offset;
27082 pb.length = length;
27083 pb.fd = pFile->h;
27085 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
27086 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
27087 offset, length));
27088 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
27089 if ( err==-1 ) {
27090 int rc;
27091 int tErrno = errno;
27092 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
27093 path, tErrno, strerror(tErrno)));
27094 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
27095 rc = SQLITE_BUSY;
27096 #else
27097 rc = sqliteErrorFromPosixError(tErrno,
27098 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
27099 #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
27100 if( IS_LOCK_ERROR(rc) ){
27101 pFile->lastErrno = tErrno;
27103 return rc;
27104 } else {
27105 return SQLITE_OK;
27110 ** This routine checks if there is a RESERVED lock held on the specified
27111 ** file by this or any other process. If such a lock is held, set *pResOut
27112 ** to a non-zero value otherwise *pResOut is set to zero. The return value
27113 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
27115 static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
27116 int rc = SQLITE_OK;
27117 int reserved = 0;
27118 unixFile *pFile = (unixFile*)id;
27119 afpLockingContext *context;
27121 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
27123 assert( pFile );
27124 context = (afpLockingContext *) pFile->lockingContext;
27125 if( context->reserved ){
27126 *pResOut = 1;
27127 return SQLITE_OK;
27129 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
27131 /* Check if a thread in this process holds such a lock */
27132 if( pFile->pInode->eFileLock>SHARED_LOCK ){
27133 reserved = 1;
27136 /* Otherwise see if some other process holds it.
27138 if( !reserved ){
27139 /* lock the RESERVED byte */
27140 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
27141 if( SQLITE_OK==lrc ){
27142 /* if we succeeded in taking the reserved lock, unlock it to restore
27143 ** the original state */
27144 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
27145 } else {
27146 /* if we failed to get the lock then someone else must have it */
27147 reserved = 1;
27149 if( IS_LOCK_ERROR(lrc) ){
27150 rc=lrc;
27154 unixLeaveMutex();
27155 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
27157 *pResOut = reserved;
27158 return rc;
27162 ** Lock the file with the lock specified by parameter eFileLock - one
27163 ** of the following:
27165 ** (1) SHARED_LOCK
27166 ** (2) RESERVED_LOCK
27167 ** (3) PENDING_LOCK
27168 ** (4) EXCLUSIVE_LOCK
27170 ** Sometimes when requesting one lock state, additional lock states
27171 ** are inserted in between. The locking might fail on one of the later
27172 ** transitions leaving the lock state different from what it started but
27173 ** still short of its goal. The following chart shows the allowed
27174 ** transitions and the inserted intermediate states:
27176 ** UNLOCKED -> SHARED
27177 ** SHARED -> RESERVED
27178 ** SHARED -> (PENDING) -> EXCLUSIVE
27179 ** RESERVED -> (PENDING) -> EXCLUSIVE
27180 ** PENDING -> EXCLUSIVE
27182 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
27183 ** routine to lower a locking level.
27185 static int afpLock(sqlite3_file *id, int eFileLock){
27186 int rc = SQLITE_OK;
27187 unixFile *pFile = (unixFile*)id;
27188 unixInodeInfo *pInode = pFile->pInode;
27189 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
27191 assert( pFile );
27192 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
27193 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
27194 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
27196 /* If there is already a lock of this type or more restrictive on the
27197 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
27198 ** unixEnterMutex() hasn't been called yet.
27200 if( pFile->eFileLock>=eFileLock ){
27201 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
27202 azFileLock(eFileLock)));
27203 return SQLITE_OK;
27206 /* Make sure the locking sequence is correct
27207 ** (1) We never move from unlocked to anything higher than shared lock.
27208 ** (2) SQLite never explicitly requests a pendig lock.
27209 ** (3) A shared lock is always held when a reserve lock is requested.
27211 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
27212 assert( eFileLock!=PENDING_LOCK );
27213 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
27215 /* This mutex is needed because pFile->pInode is shared across threads
27217 unixEnterMutex();
27218 pInode = pFile->pInode;
27220 /* If some thread using this PID has a lock via a different unixFile*
27221 ** handle that precludes the requested lock, return BUSY.
27223 if( (pFile->eFileLock!=pInode->eFileLock &&
27224 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
27226 rc = SQLITE_BUSY;
27227 goto afp_end_lock;
27230 /* If a SHARED lock is requested, and some thread using this PID already
27231 ** has a SHARED or RESERVED lock, then increment reference counts and
27232 ** return SQLITE_OK.
27234 if( eFileLock==SHARED_LOCK &&
27235 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
27236 assert( eFileLock==SHARED_LOCK );
27237 assert( pFile->eFileLock==0 );
27238 assert( pInode->nShared>0 );
27239 pFile->eFileLock = SHARED_LOCK;
27240 pInode->nShared++;
27241 pInode->nLock++;
27242 goto afp_end_lock;
27245 /* A PENDING lock is needed before acquiring a SHARED lock and before
27246 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
27247 ** be released.
27249 if( eFileLock==SHARED_LOCK
27250 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
27252 int failed;
27253 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
27254 if (failed) {
27255 rc = failed;
27256 goto afp_end_lock;
27260 /* If control gets to this point, then actually go ahead and make
27261 ** operating system calls for the specified lock.
27263 if( eFileLock==SHARED_LOCK ){
27264 int lrc1, lrc2, lrc1Errno = 0;
27265 long lk, mask;
27267 assert( pInode->nShared==0 );
27268 assert( pInode->eFileLock==0 );
27270 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
27271 /* Now get the read-lock SHARED_LOCK */
27272 /* note that the quality of the randomness doesn't matter that much */
27273 lk = random();
27274 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
27275 lrc1 = afpSetLock(context->dbPath, pFile,
27276 SHARED_FIRST+pInode->sharedByte, 1, 1);
27277 if( IS_LOCK_ERROR(lrc1) ){
27278 lrc1Errno = pFile->lastErrno;
27280 /* Drop the temporary PENDING lock */
27281 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
27283 if( IS_LOCK_ERROR(lrc1) ) {
27284 pFile->lastErrno = lrc1Errno;
27285 rc = lrc1;
27286 goto afp_end_lock;
27287 } else if( IS_LOCK_ERROR(lrc2) ){
27288 rc = lrc2;
27289 goto afp_end_lock;
27290 } else if( lrc1 != SQLITE_OK ) {
27291 rc = lrc1;
27292 } else {
27293 pFile->eFileLock = SHARED_LOCK;
27294 pInode->nLock++;
27295 pInode->nShared = 1;
27297 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
27298 /* We are trying for an exclusive lock but another thread in this
27299 ** same process is still holding a shared lock. */
27300 rc = SQLITE_BUSY;
27301 }else{
27302 /* The request was for a RESERVED or EXCLUSIVE lock. It is
27303 ** assumed that there is a SHARED or greater lock on the file
27304 ** already.
27306 int failed = 0;
27307 assert( 0!=pFile->eFileLock );
27308 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
27309 /* Acquire a RESERVED lock */
27310 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
27311 if( !failed ){
27312 context->reserved = 1;
27315 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
27316 /* Acquire an EXCLUSIVE lock */
27318 /* Remove the shared lock before trying the range. we'll need to
27319 ** reestablish the shared lock if we can't get the afpUnlock
27321 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
27322 pInode->sharedByte, 1, 0)) ){
27323 int failed2 = SQLITE_OK;
27324 /* now attemmpt to get the exclusive lock range */
27325 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
27326 SHARED_SIZE, 1);
27327 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
27328 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
27329 /* Can't reestablish the shared lock. Sqlite can't deal, this is
27330 ** a critical I/O error
27332 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
27333 SQLITE_IOERR_LOCK;
27334 goto afp_end_lock;
27336 }else{
27337 rc = failed;
27340 if( failed ){
27341 rc = failed;
27345 if( rc==SQLITE_OK ){
27346 pFile->eFileLock = eFileLock;
27347 pInode->eFileLock = eFileLock;
27348 }else if( eFileLock==EXCLUSIVE_LOCK ){
27349 pFile->eFileLock = PENDING_LOCK;
27350 pInode->eFileLock = PENDING_LOCK;
27353 afp_end_lock:
27354 unixLeaveMutex();
27355 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
27356 rc==SQLITE_OK ? "ok" : "failed"));
27357 return rc;
27361 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
27362 ** must be either NO_LOCK or SHARED_LOCK.
27364 ** If the locking level of the file descriptor is already at or below
27365 ** the requested locking level, this routine is a no-op.
27367 static int afpUnlock(sqlite3_file *id, int eFileLock) {
27368 int rc = SQLITE_OK;
27369 unixFile *pFile = (unixFile*)id;
27370 unixInodeInfo *pInode;
27371 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
27372 int skipShared = 0;
27373 #ifdef SQLITE_TEST
27374 int h = pFile->h;
27375 #endif
27377 assert( pFile );
27378 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
27379 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
27380 getpid()));
27382 assert( eFileLock<=SHARED_LOCK );
27383 if( pFile->eFileLock<=eFileLock ){
27384 return SQLITE_OK;
27386 unixEnterMutex();
27387 pInode = pFile->pInode;
27388 assert( pInode->nShared!=0 );
27389 if( pFile->eFileLock>SHARED_LOCK ){
27390 assert( pInode->eFileLock==pFile->eFileLock );
27391 SimulateIOErrorBenign(1);
27392 SimulateIOError( h=(-1) )
27393 SimulateIOErrorBenign(0);
27395 #ifndef NDEBUG
27396 /* When reducing a lock such that other processes can start
27397 ** reading the database file again, make sure that the
27398 ** transaction counter was updated if any part of the database
27399 ** file changed. If the transaction counter is not updated,
27400 ** other connections to the same file might not realize that
27401 ** the file has changed and hence might not know to flush their
27402 ** cache. The use of a stale cache can lead to database corruption.
27404 assert( pFile->inNormalWrite==0
27405 || pFile->dbUpdate==0
27406 || pFile->transCntrChng==1 );
27407 pFile->inNormalWrite = 0;
27408 #endif
27410 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
27411 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
27412 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
27413 /* only re-establish the shared lock if necessary */
27414 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
27415 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
27416 } else {
27417 skipShared = 1;
27420 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
27421 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
27423 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
27424 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
27425 if( !rc ){
27426 context->reserved = 0;
27429 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
27430 pInode->eFileLock = SHARED_LOCK;
27433 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
27435 /* Decrement the shared lock counter. Release the lock using an
27436 ** OS call only when all threads in this same process have released
27437 ** the lock.
27439 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
27440 pInode->nShared--;
27441 if( pInode->nShared==0 ){
27442 SimulateIOErrorBenign(1);
27443 SimulateIOError( h=(-1) )
27444 SimulateIOErrorBenign(0);
27445 if( !skipShared ){
27446 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
27448 if( !rc ){
27449 pInode->eFileLock = NO_LOCK;
27450 pFile->eFileLock = NO_LOCK;
27453 if( rc==SQLITE_OK ){
27454 pInode->nLock--;
27455 assert( pInode->nLock>=0 );
27456 if( pInode->nLock==0 ){
27457 closePendingFds(pFile);
27462 unixLeaveMutex();
27463 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
27464 return rc;
27468 ** Close a file & cleanup AFP specific locking context
27470 static int afpClose(sqlite3_file *id) {
27471 int rc = SQLITE_OK;
27472 if( id ){
27473 unixFile *pFile = (unixFile*)id;
27474 afpUnlock(id, NO_LOCK);
27475 unixEnterMutex();
27476 if( pFile->pInode && pFile->pInode->nLock ){
27477 /* If there are outstanding locks, do not actually close the file just
27478 ** yet because that would clear those locks. Instead, add the file
27479 ** descriptor to pInode->aPending. It will be automatically closed when
27480 ** the last lock is cleared.
27482 setPendingFd(pFile);
27484 releaseInodeInfo(pFile);
27485 sqlite3_free(pFile->lockingContext);
27486 rc = closeUnixFile(id);
27487 unixLeaveMutex();
27489 return rc;
27492 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
27494 ** The code above is the AFP lock implementation. The code is specific
27495 ** to MacOSX and does not work on other unix platforms. No alternative
27496 ** is available. If you don't compile for a mac, then the "unix-afp"
27497 ** VFS is not available.
27499 ********************* End of the AFP lock implementation **********************
27500 ******************************************************************************/
27502 /******************************************************************************
27503 *************************** Begin NFS Locking ********************************/
27505 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
27507 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
27508 ** must be either NO_LOCK or SHARED_LOCK.
27510 ** If the locking level of the file descriptor is already at or below
27511 ** the requested locking level, this routine is a no-op.
27513 static int nfsUnlock(sqlite3_file *id, int eFileLock){
27514 return posixUnlock(id, eFileLock, 1);
27517 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
27519 ** The code above is the NFS lock implementation. The code is specific
27520 ** to MacOSX and does not work on other unix platforms. No alternative
27521 ** is available.
27523 ********************* End of the NFS lock implementation **********************
27524 ******************************************************************************/
27526 /******************************************************************************
27527 **************** Non-locking sqlite3_file methods *****************************
27529 ** The next division contains implementations for all methods of the
27530 ** sqlite3_file object other than the locking methods. The locking
27531 ** methods were defined in divisions above (one locking method per
27532 ** division). Those methods that are common to all locking modes
27533 ** are gather together into this division.
27537 ** Seek to the offset passed as the second argument, then read cnt
27538 ** bytes into pBuf. Return the number of bytes actually read.
27540 ** NB: If you define USE_PREAD or USE_PREAD64, then it might also
27541 ** be necessary to define _XOPEN_SOURCE to be 500. This varies from
27542 ** one system to another. Since SQLite does not define USE_PREAD
27543 ** any any form by default, we will not attempt to define _XOPEN_SOURCE.
27544 ** See tickets #2741 and #2681.
27546 ** To avoid stomping the errno value on a failed read the lastErrno value
27547 ** is set before returning.
27549 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
27550 int got;
27551 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
27552 i64 newOffset;
27553 #endif
27554 TIMER_START;
27555 #if defined(USE_PREAD)
27556 do{ got = osPread(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
27557 SimulateIOError( got = -1 );
27558 #elif defined(USE_PREAD64)
27559 do{ got = osPread64(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR);
27560 SimulateIOError( got = -1 );
27561 #else
27562 newOffset = lseek(id->h, offset, SEEK_SET);
27563 SimulateIOError( newOffset-- );
27564 if( newOffset!=offset ){
27565 if( newOffset == -1 ){
27566 ((unixFile*)id)->lastErrno = errno;
27567 }else{
27568 ((unixFile*)id)->lastErrno = 0;
27570 return -1;
27572 do{ got = osRead(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
27573 #endif
27574 TIMER_END;
27575 if( got<0 ){
27576 ((unixFile*)id)->lastErrno = errno;
27578 OSTRACE(("READ %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
27579 return got;
27583 ** Read data from a file into a buffer. Return SQLITE_OK if all
27584 ** bytes were read successfully and SQLITE_IOERR if anything goes
27585 ** wrong.
27587 static int unixRead(
27588 sqlite3_file *id,
27589 void *pBuf,
27590 int amt,
27591 sqlite3_int64 offset
27593 unixFile *pFile = (unixFile *)id;
27594 int got;
27595 assert( id );
27597 /* If this is a database file (not a journal, master-journal or temp
27598 ** file), the bytes in the locking range should never be read or written. */
27599 #if 0
27600 assert( pFile->pUnused==0
27601 || offset>=PENDING_BYTE+512
27602 || offset+amt<=PENDING_BYTE
27604 #endif
27606 got = seekAndRead(pFile, offset, pBuf, amt);
27607 if( got==amt ){
27608 return SQLITE_OK;
27609 }else if( got<0 ){
27610 /* lastErrno set by seekAndRead */
27611 return SQLITE_IOERR_READ;
27612 }else{
27613 pFile->lastErrno = 0; /* not a system error */
27614 /* Unread parts of the buffer must be zero-filled */
27615 memset(&((char*)pBuf)[got], 0, amt-got);
27616 return SQLITE_IOERR_SHORT_READ;
27621 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
27622 ** Return the number of bytes actually read. Update the offset.
27624 ** To avoid stomping the errno value on a failed write the lastErrno value
27625 ** is set before returning.
27627 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
27628 int got;
27629 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
27630 i64 newOffset;
27631 #endif
27632 TIMER_START;
27633 #if defined(USE_PREAD)
27634 do{ got = osPwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
27635 #elif defined(USE_PREAD64)
27636 do{ got = osPwrite64(id->h, pBuf, cnt, offset);}while( got<0 && errno==EINTR);
27637 #else
27639 newOffset = lseek(id->h, offset, SEEK_SET);
27640 SimulateIOError( newOffset-- );
27641 if( newOffset!=offset ){
27642 if( newOffset == -1 ){
27643 ((unixFile*)id)->lastErrno = errno;
27644 }else{
27645 ((unixFile*)id)->lastErrno = 0;
27647 return -1;
27649 got = osWrite(id->h, pBuf, cnt);
27650 }while( got<0 && errno==EINTR );
27651 #endif
27652 TIMER_END;
27653 if( got<0 ){
27654 ((unixFile*)id)->lastErrno = errno;
27657 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
27658 return got;
27663 ** Write data from a buffer into a file. Return SQLITE_OK on success
27664 ** or some other error code on failure.
27666 static int unixWrite(
27667 sqlite3_file *id,
27668 const void *pBuf,
27669 int amt,
27670 sqlite3_int64 offset
27672 unixFile *pFile = (unixFile*)id;
27673 int wrote = 0;
27674 assert( id );
27675 assert( amt>0 );
27677 /* If this is a database file (not a journal, master-journal or temp
27678 ** file), the bytes in the locking range should never be read or written. */
27679 #if 0
27680 assert( pFile->pUnused==0
27681 || offset>=PENDING_BYTE+512
27682 || offset+amt<=PENDING_BYTE
27684 #endif
27686 #ifndef NDEBUG
27687 /* If we are doing a normal write to a database file (as opposed to
27688 ** doing a hot-journal rollback or a write to some file other than a
27689 ** normal database file) then record the fact that the database
27690 ** has changed. If the transaction counter is modified, record that
27691 ** fact too.
27693 if( pFile->inNormalWrite ){
27694 pFile->dbUpdate = 1; /* The database has been modified */
27695 if( offset<=24 && offset+amt>=27 ){
27696 int rc;
27697 char oldCntr[4];
27698 SimulateIOErrorBenign(1);
27699 rc = seekAndRead(pFile, 24, oldCntr, 4);
27700 SimulateIOErrorBenign(0);
27701 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
27702 pFile->transCntrChng = 1; /* The transaction counter has changed */
27706 #endif
27708 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
27709 amt -= wrote;
27710 offset += wrote;
27711 pBuf = &((char*)pBuf)[wrote];
27713 SimulateIOError(( wrote=(-1), amt=1 ));
27714 SimulateDiskfullError(( wrote=0, amt=1 ));
27716 if( amt>0 ){
27717 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
27718 /* lastErrno set by seekAndWrite */
27719 return SQLITE_IOERR_WRITE;
27720 }else{
27721 pFile->lastErrno = 0; /* not a system error */
27722 return SQLITE_FULL;
27726 return SQLITE_OK;
27729 #ifdef SQLITE_TEST
27731 ** Count the number of fullsyncs and normal syncs. This is used to test
27732 ** that syncs and fullsyncs are occurring at the right times.
27734 SQLITE_API int sqlite3_sync_count = 0;
27735 SQLITE_API int sqlite3_fullsync_count = 0;
27736 #endif
27739 ** We do not trust systems to provide a working fdatasync(). Some do.
27740 ** Others do no. To be safe, we will stick with the (slightly slower)
27741 ** fsync(). If you know that your system does support fdatasync() correctly,
27742 ** then simply compile with -Dfdatasync=fdatasync
27744 #if !defined(fdatasync)
27745 # define fdatasync fsync
27746 #endif
27749 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
27750 ** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
27751 ** only available on Mac OS X. But that could change.
27753 #ifdef F_FULLFSYNC
27754 # define HAVE_FULLFSYNC 1
27755 #else
27756 # define HAVE_FULLFSYNC 0
27757 #endif
27761 ** The fsync() system call does not work as advertised on many
27762 ** unix systems. The following procedure is an attempt to make
27763 ** it work better.
27765 ** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
27766 ** for testing when we want to run through the test suite quickly.
27767 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
27768 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
27769 ** or power failure will likely corrupt the database file.
27771 ** SQLite sets the dataOnly flag if the size of the file is unchanged.
27772 ** The idea behind dataOnly is that it should only write the file content
27773 ** to disk, not the inode. We only set dataOnly if the file size is
27774 ** unchanged since the file size is part of the inode. However,
27775 ** Ted Ts'o tells us that fdatasync() will also write the inode if the
27776 ** file size has changed. The only real difference between fdatasync()
27777 ** and fsync(), Ted tells us, is that fdatasync() will not flush the
27778 ** inode if the mtime or owner or other inode attributes have changed.
27779 ** We only care about the file size, not the other file attributes, so
27780 ** as far as SQLite is concerned, an fdatasync() is always adequate.
27781 ** So, we always use fdatasync() if it is available, regardless of
27782 ** the value of the dataOnly flag.
27784 static int full_fsync(int fd, int fullSync, int dataOnly){
27785 int rc;
27787 /* The following "ifdef/elif/else/" block has the same structure as
27788 ** the one below. It is replicated here solely to avoid cluttering
27789 ** up the real code with the UNUSED_PARAMETER() macros.
27791 #ifdef SQLITE_NO_SYNC
27792 UNUSED_PARAMETER(fd);
27793 UNUSED_PARAMETER(fullSync);
27794 UNUSED_PARAMETER(dataOnly);
27795 #elif HAVE_FULLFSYNC
27796 UNUSED_PARAMETER(dataOnly);
27797 #else
27798 UNUSED_PARAMETER(fullSync);
27799 UNUSED_PARAMETER(dataOnly);
27800 #endif
27802 /* Record the number of times that we do a normal fsync() and
27803 ** FULLSYNC. This is used during testing to verify that this procedure
27804 ** gets called with the correct arguments.
27806 #ifdef SQLITE_TEST
27807 if( fullSync ) sqlite3_fullsync_count++;
27808 sqlite3_sync_count++;
27809 #endif
27811 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
27812 ** no-op
27814 #ifdef SQLITE_NO_SYNC
27815 rc = SQLITE_OK;
27816 #elif HAVE_FULLFSYNC
27817 if( fullSync ){
27818 rc = osFcntl(fd, F_FULLFSYNC, 0);
27819 }else{
27820 rc = 1;
27822 /* If the FULLFSYNC failed, fall back to attempting an fsync().
27823 ** It shouldn't be possible for fullfsync to fail on the local
27824 ** file system (on OSX), so failure indicates that FULLFSYNC
27825 ** isn't supported for this file system. So, attempt an fsync
27826 ** and (for now) ignore the overhead of a superfluous fcntl call.
27827 ** It'd be better to detect fullfsync support once and avoid
27828 ** the fcntl call every time sync is called.
27830 if( rc ) rc = fsync(fd);
27832 #elif defined(__APPLE__)
27833 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
27834 ** so currently we default to the macro that redefines fdatasync to fsync
27836 rc = fsync(fd);
27837 #else
27838 rc = fdatasync(fd);
27839 #if OS_VXWORKS
27840 if( rc==-1 && errno==ENOTSUP ){
27841 rc = fsync(fd);
27843 #endif /* OS_VXWORKS */
27844 #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
27846 if( OS_VXWORKS && rc!= -1 ){
27847 rc = 0;
27849 return rc;
27853 ** Open a file descriptor to the directory containing file zFilename.
27854 ** If successful, *pFd is set to the opened file descriptor and
27855 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
27856 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
27857 ** value.
27859 ** The directory file descriptor is used for only one thing - to
27860 ** fsync() a directory to make sure file creation and deletion events
27861 ** are flushed to disk. Such fsyncs are not needed on newer
27862 ** journaling filesystems, but are required on older filesystems.
27864 ** This routine can be overridden using the xSetSysCall interface.
27865 ** The ability to override this routine was added in support of the
27866 ** chromium sandbox. Opening a directory is a security risk (we are
27867 ** told) so making it overrideable allows the chromium sandbox to
27868 ** replace this routine with a harmless no-op. To make this routine
27869 ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
27870 ** *pFd set to a negative number.
27872 ** If SQLITE_OK is returned, the caller is responsible for closing
27873 ** the file descriptor *pFd using close().
27875 static int openDirectory(const char *zFilename, int *pFd){
27876 int ii;
27877 int fd = -1;
27878 char zDirname[MAX_PATHNAME+1];
27880 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
27881 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
27882 if( ii>0 ){
27883 zDirname[ii] = '\0';
27884 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
27885 if( fd>=0 ){
27886 #ifdef FD_CLOEXEC
27887 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
27888 #endif
27889 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
27892 *pFd = fd;
27893 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
27897 ** Make sure all writes to a particular file are committed to disk.
27899 ** If dataOnly==0 then both the file itself and its metadata (file
27900 ** size, access time, etc) are synced. If dataOnly!=0 then only the
27901 ** file data is synced.
27903 ** Under Unix, also make sure that the directory entry for the file
27904 ** has been created by fsync-ing the directory that contains the file.
27905 ** If we do not do this and we encounter a power failure, the directory
27906 ** entry for the journal might not exist after we reboot. The next
27907 ** SQLite to access the file will not know that the journal exists (because
27908 ** the directory entry for the journal was never created) and the transaction
27909 ** will not roll back - possibly leading to database corruption.
27911 static int unixSync(sqlite3_file *id, int flags){
27912 int rc;
27913 unixFile *pFile = (unixFile*)id;
27915 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
27916 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
27918 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
27919 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
27920 || (flags&0x0F)==SQLITE_SYNC_FULL
27923 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
27924 ** line is to test that doing so does not cause any problems.
27926 SimulateDiskfullError( return SQLITE_FULL );
27928 assert( pFile );
27929 OSTRACE(("SYNC %-3d\n", pFile->h));
27930 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
27931 SimulateIOError( rc=1 );
27932 if( rc ){
27933 pFile->lastErrno = errno;
27934 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
27937 /* Also fsync the directory containing the file if the DIRSYNC flag
27938 ** is set. This is a one-time occurrance. Many systems (examples: AIX)
27939 ** are unable to fsync a directory, so ignore errors on the fsync.
27941 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
27942 int dirfd;
27943 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
27944 HAVE_FULLFSYNC, isFullsync));
27945 rc = osOpenDirectory(pFile->zPath, &dirfd);
27946 if( rc==SQLITE_OK && dirfd>=0 ){
27947 full_fsync(dirfd, 0, 0);
27948 robust_close(pFile, dirfd, __LINE__);
27949 }else if( rc==SQLITE_CANTOPEN ){
27950 rc = SQLITE_OK;
27952 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
27954 return rc;
27958 ** Truncate an open file to a specified size
27960 static int unixTruncate(sqlite3_file *id, i64 nByte){
27961 unixFile *pFile = (unixFile *)id;
27962 int rc;
27963 assert( pFile );
27964 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
27966 /* If the user has configured a chunk-size for this file, truncate the
27967 ** file so that it consists of an integer number of chunks (i.e. the
27968 ** actual file size after the operation may be larger than the requested
27969 ** size).
27971 if( pFile->szChunk ){
27972 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
27975 rc = robust_ftruncate(pFile->h, (off_t)nByte);
27976 if( rc ){
27977 pFile->lastErrno = errno;
27978 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
27979 }else{
27980 #ifndef NDEBUG
27981 /* If we are doing a normal write to a database file (as opposed to
27982 ** doing a hot-journal rollback or a write to some file other than a
27983 ** normal database file) and we truncate the file to zero length,
27984 ** that effectively updates the change counter. This might happen
27985 ** when restoring a database using the backup API from a zero-length
27986 ** source.
27988 if( pFile->inNormalWrite && nByte==0 ){
27989 pFile->transCntrChng = 1;
27991 #endif
27993 return SQLITE_OK;
27998 ** Determine the current size of a file in bytes
28000 static int unixFileSize(sqlite3_file *id, i64 *pSize){
28001 int rc;
28002 struct stat buf;
28003 assert( id );
28004 rc = osFstat(((unixFile*)id)->h, &buf);
28005 SimulateIOError( rc=1 );
28006 if( rc!=0 ){
28007 ((unixFile*)id)->lastErrno = errno;
28008 return SQLITE_IOERR_FSTAT;
28010 *pSize = buf.st_size;
28012 /* When opening a zero-size database, the findInodeInfo() procedure
28013 ** writes a single byte into that file in order to work around a bug
28014 ** in the OS-X msdos filesystem. In order to avoid problems with upper
28015 ** layers, we need to report this file size as zero even though it is
28016 ** really 1. Ticket #3260.
28018 if( *pSize==1 ) *pSize = 0;
28021 return SQLITE_OK;
28024 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
28026 ** Handler for proxy-locking file-control verbs. Defined below in the
28027 ** proxying locking division.
28029 static int proxyFileControl(sqlite3_file*,int,void*);
28030 #endif
28033 ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
28034 ** file-control operation. Enlarge the database to nBytes in size
28035 ** (rounded up to the next chunk-size). If the database is already
28036 ** nBytes or larger, this routine is a no-op.
28038 static int fcntlSizeHint(unixFile *pFile, i64 nByte){
28039 if( pFile->szChunk>0 ){
28040 i64 nSize; /* Required file size */
28041 struct stat buf; /* Used to hold return values of fstat() */
28043 if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
28045 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
28046 if( nSize>(i64)buf.st_size ){
28048 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
28049 /* The code below is handling the return value of osFallocate()
28050 ** correctly. posix_fallocate() is defined to "returns zero on success,
28051 ** or an error number on failure". See the manpage for details. */
28052 int err;
28054 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
28055 }while( err==EINTR );
28056 if( err ) return SQLITE_IOERR_WRITE;
28057 #else
28058 /* If the OS does not have posix_fallocate(), fake it. First use
28059 ** ftruncate() to set the file size, then write a single byte to
28060 ** the last byte in each block within the extended region. This
28061 ** is the same technique used by glibc to implement posix_fallocate()
28062 ** on systems that do not have a real fallocate() system call.
28064 int nBlk = buf.st_blksize; /* File-system block size */
28065 i64 iWrite; /* Next offset to write to */
28067 if( robust_ftruncate(pFile->h, nSize) ){
28068 pFile->lastErrno = errno;
28069 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
28071 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
28072 while( iWrite<nSize ){
28073 int nWrite = seekAndWrite(pFile, iWrite, "", 1);
28074 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
28075 iWrite += nBlk;
28077 #endif
28081 return SQLITE_OK;
28085 ** Information and control of an open file handle.
28087 static int unixFileControl(sqlite3_file *id, int op, void *pArg){
28088 unixFile *pFile = (unixFile*)id;
28089 switch( op ){
28090 case SQLITE_FCNTL_LOCKSTATE: {
28091 *(int*)pArg = pFile->eFileLock;
28092 return SQLITE_OK;
28094 case SQLITE_LAST_ERRNO: {
28095 *(int*)pArg = pFile->lastErrno;
28096 return SQLITE_OK;
28098 case SQLITE_FCNTL_CHUNK_SIZE: {
28099 pFile->szChunk = *(int *)pArg;
28100 return SQLITE_OK;
28102 case SQLITE_FCNTL_SIZE_HINT: {
28103 int rc;
28104 SimulateIOErrorBenign(1);
28105 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
28106 SimulateIOErrorBenign(0);
28107 return rc;
28109 case SQLITE_FCNTL_PERSIST_WAL: {
28110 int bPersist = *(int*)pArg;
28111 if( bPersist<0 ){
28112 *(int*)pArg = (pFile->ctrlFlags & UNIXFILE_PERSIST_WAL)!=0;
28113 }else if( bPersist==0 ){
28114 pFile->ctrlFlags &= ~UNIXFILE_PERSIST_WAL;
28115 }else{
28116 pFile->ctrlFlags |= UNIXFILE_PERSIST_WAL;
28118 return SQLITE_OK;
28120 #ifndef NDEBUG
28121 /* The pager calls this method to signal that it has done
28122 ** a rollback and that the database is therefore unchanged and
28123 ** it hence it is OK for the transaction change counter to be
28124 ** unchanged.
28126 case SQLITE_FCNTL_DB_UNCHANGED: {
28127 ((unixFile*)id)->dbUpdate = 0;
28128 return SQLITE_OK;
28130 #endif
28131 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
28132 case SQLITE_SET_LOCKPROXYFILE:
28133 case SQLITE_GET_LOCKPROXYFILE: {
28134 return proxyFileControl(id,op,pArg);
28136 #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
28137 case SQLITE_FCNTL_SYNC_OMITTED: {
28138 return SQLITE_OK; /* A no-op */
28141 return SQLITE_NOTFOUND;
28145 ** Return the sector size in bytes of the underlying block device for
28146 ** the specified file. This is almost always 512 bytes, but may be
28147 ** larger for some devices.
28149 ** SQLite code assumes this function cannot fail. It also assumes that
28150 ** if two files are created in the same file-system directory (i.e.
28151 ** a database and its journal file) that the sector size will be the
28152 ** same for both.
28154 static int unixSectorSize(sqlite3_file *NotUsed){
28155 UNUSED_PARAMETER(NotUsed);
28156 return SQLITE_DEFAULT_SECTOR_SIZE;
28160 ** Return the device characteristics for the file. This is always 0 for unix.
28162 static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
28163 UNUSED_PARAMETER(NotUsed);
28164 return 0;
28167 #ifndef SQLITE_OMIT_WAL
28171 ** Object used to represent an shared memory buffer.
28173 ** When multiple threads all reference the same wal-index, each thread
28174 ** has its own unixShm object, but they all point to a single instance
28175 ** of this unixShmNode object. In other words, each wal-index is opened
28176 ** only once per process.
28178 ** Each unixShmNode object is connected to a single unixInodeInfo object.
28179 ** We could coalesce this object into unixInodeInfo, but that would mean
28180 ** every open file that does not use shared memory (in other words, most
28181 ** open files) would have to carry around this extra information. So
28182 ** the unixInodeInfo object contains a pointer to this unixShmNode object
28183 ** and the unixShmNode object is created only when needed.
28185 ** unixMutexHeld() must be true when creating or destroying
28186 ** this object or while reading or writing the following fields:
28188 ** nRef
28190 ** The following fields are read-only after the object is created:
28192 ** fid
28193 ** zFilename
28195 ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
28196 ** unixMutexHeld() is true when reading or writing any other field
28197 ** in this structure.
28199 struct unixShmNode {
28200 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
28201 sqlite3_mutex *mutex; /* Mutex to access this object */
28202 char *zFilename; /* Name of the mmapped file */
28203 int h; /* Open file descriptor */
28204 int szRegion; /* Size of shared-memory regions */
28205 u16 nRegion; /* Size of array apRegion */
28206 u8 isReadonly; /* True if read-only */
28207 char **apRegion; /* Array of mapped shared-memory regions */
28208 int nRef; /* Number of unixShm objects pointing to this */
28209 unixShm *pFirst; /* All unixShm objects pointing to this */
28210 #ifdef SQLITE_DEBUG
28211 u8 exclMask; /* Mask of exclusive locks held */
28212 u8 sharedMask; /* Mask of shared locks held */
28213 u8 nextShmId; /* Next available unixShm.id value */
28214 #endif
28218 ** Structure used internally by this VFS to record the state of an
28219 ** open shared memory connection.
28221 ** The following fields are initialized when this object is created and
28222 ** are read-only thereafter:
28224 ** unixShm.pFile
28225 ** unixShm.id
28227 ** All other fields are read/write. The unixShm.pFile->mutex must be held
28228 ** while accessing any read/write fields.
28230 struct unixShm {
28231 unixShmNode *pShmNode; /* The underlying unixShmNode object */
28232 unixShm *pNext; /* Next unixShm with the same unixShmNode */
28233 u8 hasMutex; /* True if holding the unixShmNode mutex */
28234 u8 id; /* Id of this connection within its unixShmNode */
28235 u16 sharedMask; /* Mask of shared locks held */
28236 u16 exclMask; /* Mask of exclusive locks held */
28240 ** Constants used for locking
28242 #define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
28243 #define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
28246 ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
28248 ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
28249 ** otherwise.
28251 static int unixShmSystemLock(
28252 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
28253 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
28254 int ofst, /* First byte of the locking range */
28255 int n /* Number of bytes to lock */
28257 struct flock f; /* The posix advisory locking structure */
28258 int rc = SQLITE_OK; /* Result code form fcntl() */
28260 /* Access to the unixShmNode object is serialized by the caller */
28261 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
28263 /* Shared locks never span more than one byte */
28264 assert( n==1 || lockType!=F_RDLCK );
28266 /* Locks are within range */
28267 assert( n>=1 && n<SQLITE_SHM_NLOCK );
28269 if( pShmNode->h>=0 ){
28270 /* Initialize the locking parameters */
28271 memset(&f, 0, sizeof(f));
28272 f.l_type = lockType;
28273 f.l_whence = SEEK_SET;
28274 f.l_start = ofst;
28275 f.l_len = n;
28277 rc = osFcntl(pShmNode->h, F_SETLK, &f);
28278 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
28281 /* Update the global lock state and do debug tracing */
28282 #ifdef SQLITE_DEBUG
28283 { u16 mask;
28284 OSTRACE(("SHM-LOCK "));
28285 mask = (1<<(ofst+n)) - (1<<ofst);
28286 if( rc==SQLITE_OK ){
28287 if( lockType==F_UNLCK ){
28288 OSTRACE(("unlock %d ok", ofst));
28289 pShmNode->exclMask &= ~mask;
28290 pShmNode->sharedMask &= ~mask;
28291 }else if( lockType==F_RDLCK ){
28292 OSTRACE(("read-lock %d ok", ofst));
28293 pShmNode->exclMask &= ~mask;
28294 pShmNode->sharedMask |= mask;
28295 }else{
28296 assert( lockType==F_WRLCK );
28297 OSTRACE(("write-lock %d ok", ofst));
28298 pShmNode->exclMask |= mask;
28299 pShmNode->sharedMask &= ~mask;
28301 }else{
28302 if( lockType==F_UNLCK ){
28303 OSTRACE(("unlock %d failed", ofst));
28304 }else if( lockType==F_RDLCK ){
28305 OSTRACE(("read-lock failed"));
28306 }else{
28307 assert( lockType==F_WRLCK );
28308 OSTRACE(("write-lock %d failed", ofst));
28311 OSTRACE((" - afterwards %03x,%03x\n",
28312 pShmNode->sharedMask, pShmNode->exclMask));
28314 #endif
28316 return rc;
28321 ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
28323 ** This is not a VFS shared-memory method; it is a utility function called
28324 ** by VFS shared-memory methods.
28326 static void unixShmPurge(unixFile *pFd){
28327 unixShmNode *p = pFd->pInode->pShmNode;
28328 assert( unixMutexHeld() );
28329 if( p && p->nRef==0 ){
28330 int i;
28331 assert( p->pInode==pFd->pInode );
28332 sqlite3_mutex_free(p->mutex);
28333 for(i=0; i<p->nRegion; i++){
28334 if( p->h>=0 ){
28335 munmap(p->apRegion[i], p->szRegion);
28336 }else{
28337 sqlite3_free(p->apRegion[i]);
28340 sqlite3_free(p->apRegion);
28341 if( p->h>=0 ){
28342 robust_close(pFd, p->h, __LINE__);
28343 p->h = -1;
28345 p->pInode->pShmNode = 0;
28346 sqlite3_free(p);
28351 ** Open a shared-memory area associated with open database file pDbFd.
28352 ** This particular implementation uses mmapped files.
28354 ** The file used to implement shared-memory is in the same directory
28355 ** as the open database file and has the same name as the open database
28356 ** file with the "-shm" suffix added. For example, if the database file
28357 ** is "/home/user1/config.db" then the file that is created and mmapped
28358 ** for shared memory will be called "/home/user1/config.db-shm".
28360 ** Another approach to is to use files in /dev/shm or /dev/tmp or an
28361 ** some other tmpfs mount. But if a file in a different directory
28362 ** from the database file is used, then differing access permissions
28363 ** or a chroot() might cause two different processes on the same
28364 ** database to end up using different files for shared memory -
28365 ** meaning that their memory would not really be shared - resulting
28366 ** in database corruption. Nevertheless, this tmpfs file usage
28367 ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
28368 ** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
28369 ** option results in an incompatible build of SQLite; builds of SQLite
28370 ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
28371 ** same database file at the same time, database corruption will likely
28372 ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
28373 ** "unsupported" and may go away in a future SQLite release.
28375 ** When opening a new shared-memory file, if no other instances of that
28376 ** file are currently open, in this process or in other processes, then
28377 ** the file must be truncated to zero length or have its header cleared.
28379 ** If the original database file (pDbFd) is using the "unix-excl" VFS
28380 ** that means that an exclusive lock is held on the database file and
28381 ** that no other processes are able to read or write the database. In
28382 ** that case, we do not really need shared memory. No shared memory
28383 ** file is created. The shared memory will be simulated with heap memory.
28385 static int unixOpenSharedMemory(unixFile *pDbFd){
28386 struct unixShm *p = 0; /* The connection to be opened */
28387 struct unixShmNode *pShmNode; /* The underlying mmapped file */
28388 int rc; /* Result code */
28389 unixInodeInfo *pInode; /* The inode of fd */
28390 char *zShmFilename; /* Name of the file used for SHM */
28391 int nShmFilename; /* Size of the SHM filename in bytes */
28393 /* Allocate space for the new unixShm object. */
28394 p = sqlite3_malloc( sizeof(*p) );
28395 if( p==0 ) return SQLITE_NOMEM;
28396 memset(p, 0, sizeof(*p));
28397 assert( pDbFd->pShm==0 );
28399 /* Check to see if a unixShmNode object already exists. Reuse an existing
28400 ** one if present. Create a new one if necessary.
28402 unixEnterMutex();
28403 pInode = pDbFd->pInode;
28404 pShmNode = pInode->pShmNode;
28405 if( pShmNode==0 ){
28406 struct stat sStat; /* fstat() info for database file */
28408 /* Call fstat() to figure out the permissions on the database file. If
28409 ** a new *-shm file is created, an attempt will be made to create it
28410 ** with the same permissions. The actual permissions the file is created
28411 ** with are subject to the current umask setting.
28413 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
28414 rc = SQLITE_IOERR_FSTAT;
28415 goto shm_open_err;
28418 #ifdef SQLITE_SHM_DIRECTORY
28419 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 30;
28420 #else
28421 nShmFilename = 5 + (int)strlen(pDbFd->zPath);
28422 #endif
28423 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
28424 if( pShmNode==0 ){
28425 rc = SQLITE_NOMEM;
28426 goto shm_open_err;
28428 memset(pShmNode, 0, sizeof(*pShmNode));
28429 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
28430 #ifdef SQLITE_SHM_DIRECTORY
28431 sqlite3_snprintf(nShmFilename, zShmFilename,
28432 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
28433 (u32)sStat.st_ino, (u32)sStat.st_dev);
28434 #else
28435 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
28436 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
28437 #endif
28438 pShmNode->h = -1;
28439 pDbFd->pInode->pShmNode = pShmNode;
28440 pShmNode->pInode = pDbFd->pInode;
28441 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
28442 if( pShmNode->mutex==0 ){
28443 rc = SQLITE_NOMEM;
28444 goto shm_open_err;
28447 if( pInode->bProcessLock==0 ){
28448 const char *zRO;
28449 int openFlags = O_RDWR | O_CREAT;
28450 zRO = sqlite3_uri_parameter(pDbFd->zPath, "readonly_shm");
28451 if( zRO && sqlite3GetBoolean(zRO) ){
28452 openFlags = O_RDONLY;
28453 pShmNode->isReadonly = 1;
28455 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
28456 if( pShmNode->h<0 ){
28457 if( pShmNode->h<0 ){
28458 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
28459 goto shm_open_err;
28463 /* Check to see if another process is holding the dead-man switch.
28464 ** If not, truncate the file to zero length.
28466 rc = SQLITE_OK;
28467 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
28468 if( robust_ftruncate(pShmNode->h, 0) ){
28469 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
28472 if( rc==SQLITE_OK ){
28473 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
28475 if( rc ) goto shm_open_err;
28479 /* Make the new connection a child of the unixShmNode */
28480 p->pShmNode = pShmNode;
28481 #ifdef SQLITE_DEBUG
28482 p->id = pShmNode->nextShmId++;
28483 #endif
28484 pShmNode->nRef++;
28485 pDbFd->pShm = p;
28486 unixLeaveMutex();
28488 /* The reference count on pShmNode has already been incremented under
28489 ** the cover of the unixEnterMutex() mutex and the pointer from the
28490 ** new (struct unixShm) object to the pShmNode has been set. All that is
28491 ** left to do is to link the new object into the linked list starting
28492 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
28493 ** mutex.
28495 sqlite3_mutex_enter(pShmNode->mutex);
28496 p->pNext = pShmNode->pFirst;
28497 pShmNode->pFirst = p;
28498 sqlite3_mutex_leave(pShmNode->mutex);
28499 return SQLITE_OK;
28501 /* Jump here on any error */
28502 shm_open_err:
28503 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
28504 sqlite3_free(p);
28505 unixLeaveMutex();
28506 return rc;
28510 ** This function is called to obtain a pointer to region iRegion of the
28511 ** shared-memory associated with the database file fd. Shared-memory regions
28512 ** are numbered starting from zero. Each shared-memory region is szRegion
28513 ** bytes in size.
28515 ** If an error occurs, an error code is returned and *pp is set to NULL.
28517 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
28518 ** region has not been allocated (by any client, including one running in a
28519 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
28520 ** bExtend is non-zero and the requested shared-memory region has not yet
28521 ** been allocated, it is allocated by this function.
28523 ** If the shared-memory region has already been allocated or is allocated by
28524 ** this call as described above, then it is mapped into this processes
28525 ** address space (if it is not already), *pp is set to point to the mapped
28526 ** memory and SQLITE_OK returned.
28528 static int unixShmMap(
28529 sqlite3_file *fd, /* Handle open on database file */
28530 int iRegion, /* Region to retrieve */
28531 int szRegion, /* Size of regions */
28532 int bExtend, /* True to extend file if necessary */
28533 void volatile **pp /* OUT: Mapped memory */
28535 unixFile *pDbFd = (unixFile*)fd;
28536 unixShm *p;
28537 unixShmNode *pShmNode;
28538 int rc = SQLITE_OK;
28540 /* If the shared-memory file has not yet been opened, open it now. */
28541 if( pDbFd->pShm==0 ){
28542 rc = unixOpenSharedMemory(pDbFd);
28543 if( rc!=SQLITE_OK ) return rc;
28546 p = pDbFd->pShm;
28547 pShmNode = p->pShmNode;
28548 sqlite3_mutex_enter(pShmNode->mutex);
28549 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
28550 assert( pShmNode->pInode==pDbFd->pInode );
28551 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
28552 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
28554 if( pShmNode->nRegion<=iRegion ){
28555 char **apNew; /* New apRegion[] array */
28556 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
28557 struct stat sStat; /* Used by fstat() */
28559 pShmNode->szRegion = szRegion;
28561 if( pShmNode->h>=0 ){
28562 /* The requested region is not mapped into this processes address space.
28563 ** Check to see if it has been allocated (i.e. if the wal-index file is
28564 ** large enough to contain the requested region).
28566 if( osFstat(pShmNode->h, &sStat) ){
28567 rc = SQLITE_IOERR_SHMSIZE;
28568 goto shmpage_out;
28571 if( sStat.st_size<nByte ){
28572 /* The requested memory region does not exist. If bExtend is set to
28573 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
28575 ** Alternatively, if bExtend is true, use ftruncate() to allocate
28576 ** the requested memory region.
28578 if( !bExtend ) goto shmpage_out;
28579 if( robust_ftruncate(pShmNode->h, nByte) ){
28580 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "ftruncate",
28581 pShmNode->zFilename);
28582 goto shmpage_out;
28587 /* Map the requested memory region into this processes address space. */
28588 apNew = (char **)sqlite3_realloc(
28589 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
28591 if( !apNew ){
28592 rc = SQLITE_IOERR_NOMEM;
28593 goto shmpage_out;
28595 pShmNode->apRegion = apNew;
28596 while(pShmNode->nRegion<=iRegion){
28597 void *pMem;
28598 if( pShmNode->h>=0 ){
28599 pMem = mmap(0, szRegion,
28600 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
28601 MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
28603 if( pMem==MAP_FAILED ){
28604 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
28605 goto shmpage_out;
28607 }else{
28608 pMem = sqlite3_malloc(szRegion);
28609 if( pMem==0 ){
28610 rc = SQLITE_NOMEM;
28611 goto shmpage_out;
28613 memset(pMem, 0, szRegion);
28615 pShmNode->apRegion[pShmNode->nRegion] = pMem;
28616 pShmNode->nRegion++;
28620 shmpage_out:
28621 if( pShmNode->nRegion>iRegion ){
28622 *pp = pShmNode->apRegion[iRegion];
28623 }else{
28624 *pp = 0;
28626 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
28627 sqlite3_mutex_leave(pShmNode->mutex);
28628 return rc;
28632 ** Change the lock state for a shared-memory segment.
28634 ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
28635 ** different here than in posix. In xShmLock(), one can go from unlocked
28636 ** to shared and back or from unlocked to exclusive and back. But one may
28637 ** not go from shared to exclusive or from exclusive to shared.
28639 static int unixShmLock(
28640 sqlite3_file *fd, /* Database file holding the shared memory */
28641 int ofst, /* First lock to acquire or release */
28642 int n, /* Number of locks to acquire or release */
28643 int flags /* What to do with the lock */
28645 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
28646 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
28647 unixShm *pX; /* For looping over all siblings */
28648 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
28649 int rc = SQLITE_OK; /* Result code */
28650 u16 mask; /* Mask of locks to take or release */
28652 assert( pShmNode==pDbFd->pInode->pShmNode );
28653 assert( pShmNode->pInode==pDbFd->pInode );
28654 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
28655 assert( n>=1 );
28656 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
28657 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
28658 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
28659 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
28660 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
28661 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
28662 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
28664 mask = (1<<(ofst+n)) - (1<<ofst);
28665 assert( n>1 || mask==(1<<ofst) );
28666 sqlite3_mutex_enter(pShmNode->mutex);
28667 if( flags & SQLITE_SHM_UNLOCK ){
28668 u16 allMask = 0; /* Mask of locks held by siblings */
28670 /* See if any siblings hold this same lock */
28671 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
28672 if( pX==p ) continue;
28673 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
28674 allMask |= pX->sharedMask;
28677 /* Unlock the system-level locks */
28678 if( (mask & allMask)==0 ){
28679 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
28680 }else{
28681 rc = SQLITE_OK;
28684 /* Undo the local locks */
28685 if( rc==SQLITE_OK ){
28686 p->exclMask &= ~mask;
28687 p->sharedMask &= ~mask;
28689 }else if( flags & SQLITE_SHM_SHARED ){
28690 u16 allShared = 0; /* Union of locks held by connections other than "p" */
28692 /* Find out which shared locks are already held by sibling connections.
28693 ** If any sibling already holds an exclusive lock, go ahead and return
28694 ** SQLITE_BUSY.
28696 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
28697 if( (pX->exclMask & mask)!=0 ){
28698 rc = SQLITE_BUSY;
28699 break;
28701 allShared |= pX->sharedMask;
28704 /* Get shared locks at the system level, if necessary */
28705 if( rc==SQLITE_OK ){
28706 if( (allShared & mask)==0 ){
28707 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
28708 }else{
28709 rc = SQLITE_OK;
28713 /* Get the local shared locks */
28714 if( rc==SQLITE_OK ){
28715 p->sharedMask |= mask;
28717 }else{
28718 /* Make sure no sibling connections hold locks that will block this
28719 ** lock. If any do, return SQLITE_BUSY right away.
28721 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
28722 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
28723 rc = SQLITE_BUSY;
28724 break;
28728 /* Get the exclusive locks at the system level. Then if successful
28729 ** also mark the local connection as being locked.
28731 if( rc==SQLITE_OK ){
28732 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
28733 if( rc==SQLITE_OK ){
28734 assert( (p->sharedMask & mask)==0 );
28735 p->exclMask |= mask;
28739 sqlite3_mutex_leave(pShmNode->mutex);
28740 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
28741 p->id, getpid(), p->sharedMask, p->exclMask));
28742 return rc;
28746 ** Implement a memory barrier or memory fence on shared memory.
28748 ** All loads and stores begun before the barrier must complete before
28749 ** any load or store begun after the barrier.
28751 static void unixShmBarrier(
28752 sqlite3_file *fd /* Database file holding the shared memory */
28754 UNUSED_PARAMETER(fd);
28755 unixEnterMutex();
28756 unixLeaveMutex();
28760 ** Close a connection to shared-memory. Delete the underlying
28761 ** storage if deleteFlag is true.
28763 ** If there is no shared memory associated with the connection then this
28764 ** routine is a harmless no-op.
28766 static int unixShmUnmap(
28767 sqlite3_file *fd, /* The underlying database file */
28768 int deleteFlag /* Delete shared-memory if true */
28770 unixShm *p; /* The connection to be closed */
28771 unixShmNode *pShmNode; /* The underlying shared-memory file */
28772 unixShm **pp; /* For looping over sibling connections */
28773 unixFile *pDbFd; /* The underlying database file */
28775 pDbFd = (unixFile*)fd;
28776 p = pDbFd->pShm;
28777 if( p==0 ) return SQLITE_OK;
28778 pShmNode = p->pShmNode;
28780 assert( pShmNode==pDbFd->pInode->pShmNode );
28781 assert( pShmNode->pInode==pDbFd->pInode );
28783 /* Remove connection p from the set of connections associated
28784 ** with pShmNode */
28785 sqlite3_mutex_enter(pShmNode->mutex);
28786 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
28787 *pp = p->pNext;
28789 /* Free the connection p */
28790 sqlite3_free(p);
28791 pDbFd->pShm = 0;
28792 sqlite3_mutex_leave(pShmNode->mutex);
28794 /* If pShmNode->nRef has reached 0, then close the underlying
28795 ** shared-memory file, too */
28796 unixEnterMutex();
28797 assert( pShmNode->nRef>0 );
28798 pShmNode->nRef--;
28799 if( pShmNode->nRef==0 ){
28800 if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
28801 unixShmPurge(pDbFd);
28803 unixLeaveMutex();
28805 return SQLITE_OK;
28809 #else
28810 # define unixShmMap 0
28811 # define unixShmLock 0
28812 # define unixShmBarrier 0
28813 # define unixShmUnmap 0
28814 #endif /* #ifndef SQLITE_OMIT_WAL */
28817 ** Here ends the implementation of all sqlite3_file methods.
28819 ********************** End sqlite3_file Methods *******************************
28820 ******************************************************************************/
28823 ** This division contains definitions of sqlite3_io_methods objects that
28824 ** implement various file locking strategies. It also contains definitions
28825 ** of "finder" functions. A finder-function is used to locate the appropriate
28826 ** sqlite3_io_methods object for a particular database file. The pAppData
28827 ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
28828 ** the correct finder-function for that VFS.
28830 ** Most finder functions return a pointer to a fixed sqlite3_io_methods
28831 ** object. The only interesting finder-function is autolockIoFinder, which
28832 ** looks at the filesystem type and tries to guess the best locking
28833 ** strategy from that.
28835 ** For finder-funtion F, two objects are created:
28837 ** (1) The real finder-function named "FImpt()".
28839 ** (2) A constant pointer to this function named just "F".
28842 ** A pointer to the F pointer is used as the pAppData value for VFS
28843 ** objects. We have to do this instead of letting pAppData point
28844 ** directly at the finder-function since C90 rules prevent a void*
28845 ** from be cast into a function pointer.
28848 ** Each instance of this macro generates two objects:
28850 ** * A constant sqlite3_io_methods object call METHOD that has locking
28851 ** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
28853 ** * An I/O method finder function called FINDER that returns a pointer
28854 ** to the METHOD object in the previous bullet.
28856 #define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
28857 static const sqlite3_io_methods METHOD = { \
28858 VERSION, /* iVersion */ \
28859 CLOSE, /* xClose */ \
28860 unixRead, /* xRead */ \
28861 unixWrite, /* xWrite */ \
28862 unixTruncate, /* xTruncate */ \
28863 unixSync, /* xSync */ \
28864 unixFileSize, /* xFileSize */ \
28865 LOCK, /* xLock */ \
28866 UNLOCK, /* xUnlock */ \
28867 CKLOCK, /* xCheckReservedLock */ \
28868 unixFileControl, /* xFileControl */ \
28869 unixSectorSize, /* xSectorSize */ \
28870 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
28871 unixShmMap, /* xShmMap */ \
28872 unixShmLock, /* xShmLock */ \
28873 unixShmBarrier, /* xShmBarrier */ \
28874 unixShmUnmap /* xShmUnmap */ \
28875 }; \
28876 static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
28877 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
28878 return &METHOD; \
28880 static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
28881 = FINDER##Impl;
28884 ** Here are all of the sqlite3_io_methods objects for each of the
28885 ** locking strategies. Functions that return pointers to these methods
28886 ** are also created.
28888 IOMETHODS(
28889 posixIoFinder, /* Finder function name */
28890 posixIoMethods, /* sqlite3_io_methods object name */
28891 2, /* shared memory is enabled */
28892 unixClose, /* xClose method */
28893 unixLock, /* xLock method */
28894 unixUnlock, /* xUnlock method */
28895 unixCheckReservedLock /* xCheckReservedLock method */
28897 IOMETHODS(
28898 nolockIoFinder, /* Finder function name */
28899 nolockIoMethods, /* sqlite3_io_methods object name */
28900 1, /* shared memory is disabled */
28901 nolockClose, /* xClose method */
28902 nolockLock, /* xLock method */
28903 nolockUnlock, /* xUnlock method */
28904 nolockCheckReservedLock /* xCheckReservedLock method */
28906 IOMETHODS(
28907 dotlockIoFinder, /* Finder function name */
28908 dotlockIoMethods, /* sqlite3_io_methods object name */
28909 1, /* shared memory is disabled */
28910 dotlockClose, /* xClose method */
28911 dotlockLock, /* xLock method */
28912 dotlockUnlock, /* xUnlock method */
28913 dotlockCheckReservedLock /* xCheckReservedLock method */
28916 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
28917 IOMETHODS(
28918 flockIoFinder, /* Finder function name */
28919 flockIoMethods, /* sqlite3_io_methods object name */
28920 1, /* shared memory is disabled */
28921 flockClose, /* xClose method */
28922 flockLock, /* xLock method */
28923 flockUnlock, /* xUnlock method */
28924 flockCheckReservedLock /* xCheckReservedLock method */
28926 #endif
28928 #if OS_VXWORKS
28929 IOMETHODS(
28930 semIoFinder, /* Finder function name */
28931 semIoMethods, /* sqlite3_io_methods object name */
28932 1, /* shared memory is disabled */
28933 semClose, /* xClose method */
28934 semLock, /* xLock method */
28935 semUnlock, /* xUnlock method */
28936 semCheckReservedLock /* xCheckReservedLock method */
28938 #endif
28940 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28941 IOMETHODS(
28942 afpIoFinder, /* Finder function name */
28943 afpIoMethods, /* sqlite3_io_methods object name */
28944 1, /* shared memory is disabled */
28945 afpClose, /* xClose method */
28946 afpLock, /* xLock method */
28947 afpUnlock, /* xUnlock method */
28948 afpCheckReservedLock /* xCheckReservedLock method */
28950 #endif
28953 ** The proxy locking method is a "super-method" in the sense that it
28954 ** opens secondary file descriptors for the conch and lock files and
28955 ** it uses proxy, dot-file, AFP, and flock() locking methods on those
28956 ** secondary files. For this reason, the division that implements
28957 ** proxy locking is located much further down in the file. But we need
28958 ** to go ahead and define the sqlite3_io_methods and finder function
28959 ** for proxy locking here. So we forward declare the I/O methods.
28961 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28962 static int proxyClose(sqlite3_file*);
28963 static int proxyLock(sqlite3_file*, int);
28964 static int proxyUnlock(sqlite3_file*, int);
28965 static int proxyCheckReservedLock(sqlite3_file*, int*);
28966 IOMETHODS(
28967 proxyIoFinder, /* Finder function name */
28968 proxyIoMethods, /* sqlite3_io_methods object name */
28969 1, /* shared memory is disabled */
28970 proxyClose, /* xClose method */
28971 proxyLock, /* xLock method */
28972 proxyUnlock, /* xUnlock method */
28973 proxyCheckReservedLock /* xCheckReservedLock method */
28975 #endif
28977 /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
28978 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28979 IOMETHODS(
28980 nfsIoFinder, /* Finder function name */
28981 nfsIoMethods, /* sqlite3_io_methods object name */
28982 1, /* shared memory is disabled */
28983 unixClose, /* xClose method */
28984 unixLock, /* xLock method */
28985 nfsUnlock, /* xUnlock method */
28986 unixCheckReservedLock /* xCheckReservedLock method */
28988 #endif
28990 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28992 ** This "finder" function attempts to determine the best locking strategy
28993 ** for the database file "filePath". It then returns the sqlite3_io_methods
28994 ** object that implements that strategy.
28996 ** This is for MacOSX only.
28998 static const sqlite3_io_methods *autolockIoFinderImpl(
28999 const char *filePath, /* name of the database file */
29000 unixFile *pNew /* open file object for the database file */
29002 static const struct Mapping {
29003 const char *zFilesystem; /* Filesystem type name */
29004 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
29005 } aMap[] = {
29006 { "hfs", &posixIoMethods },
29007 { "ufs", &posixIoMethods },
29008 { "afpfs", &afpIoMethods },
29009 { "smbfs", &afpIoMethods },
29010 { "webdav", &nolockIoMethods },
29011 { 0, 0 }
29013 int i;
29014 struct statfs fsInfo;
29015 struct flock lockInfo;
29017 if( !filePath ){
29018 /* If filePath==NULL that means we are dealing with a transient file
29019 ** that does not need to be locked. */
29020 return &nolockIoMethods;
29022 if( statfs(filePath, &fsInfo) != -1 ){
29023 if( fsInfo.f_flags & MNT_RDONLY ){
29024 return &nolockIoMethods;
29026 for(i=0; aMap[i].zFilesystem; i++){
29027 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
29028 return aMap[i].pMethods;
29033 /* Default case. Handles, amongst others, "nfs".
29034 ** Test byte-range lock using fcntl(). If the call succeeds,
29035 ** assume that the file-system supports POSIX style locks.
29037 lockInfo.l_len = 1;
29038 lockInfo.l_start = 0;
29039 lockInfo.l_whence = SEEK_SET;
29040 lockInfo.l_type = F_RDLCK;
29041 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
29042 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
29043 return &nfsIoMethods;
29044 } else {
29045 return &posixIoMethods;
29047 }else{
29048 return &dotlockIoMethods;
29051 static const sqlite3_io_methods
29052 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
29054 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
29056 #if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
29058 ** This "finder" function attempts to determine the best locking strategy
29059 ** for the database file "filePath". It then returns the sqlite3_io_methods
29060 ** object that implements that strategy.
29062 ** This is for VXWorks only.
29064 static const sqlite3_io_methods *autolockIoFinderImpl(
29065 const char *filePath, /* name of the database file */
29066 unixFile *pNew /* the open file object */
29068 struct flock lockInfo;
29070 if( !filePath ){
29071 /* If filePath==NULL that means we are dealing with a transient file
29072 ** that does not need to be locked. */
29073 return &nolockIoMethods;
29076 /* Test if fcntl() is supported and use POSIX style locks.
29077 ** Otherwise fall back to the named semaphore method.
29079 lockInfo.l_len = 1;
29080 lockInfo.l_start = 0;
29081 lockInfo.l_whence = SEEK_SET;
29082 lockInfo.l_type = F_RDLCK;
29083 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
29084 return &posixIoMethods;
29085 }else{
29086 return &semIoMethods;
29089 static const sqlite3_io_methods
29090 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
29092 #endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
29095 ** An abstract type for a pointer to a IO method finder function:
29097 typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
29100 /****************************************************************************
29101 **************************** sqlite3_vfs methods ****************************
29103 ** This division contains the implementation of methods on the
29104 ** sqlite3_vfs object.
29108 ** Initialize the contents of the unixFile structure pointed to by pId.
29110 static int fillInUnixFile(
29111 sqlite3_vfs *pVfs, /* Pointer to vfs object */
29112 int h, /* Open file descriptor of file being opened */
29113 int syncDir, /* True to sync directory on first sync */
29114 sqlite3_file *pId, /* Write to the unixFile structure here */
29115 const char *zFilename, /* Name of the file being opened */
29116 int noLock, /* Omit locking if true */
29117 int isDelete, /* Delete on close if true */
29118 int isReadOnly /* True if the file is opened read-only */
29120 const sqlite3_io_methods *pLockingStyle;
29121 unixFile *pNew = (unixFile *)pId;
29122 int rc = SQLITE_OK;
29124 assert( pNew->pInode==NULL );
29126 /* Parameter isDelete is only used on vxworks. Express this explicitly
29127 ** here to prevent compiler warnings about unused parameters.
29129 UNUSED_PARAMETER(isDelete);
29131 /* Usually the path zFilename should not be a relative pathname. The
29132 ** exception is when opening the proxy "conch" file in builds that
29133 ** include the special Apple locking styles.
29135 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
29136 assert( zFilename==0 || zFilename[0]=='/'
29137 || pVfs->pAppData==(void*)&autolockIoFinder );
29138 #else
29139 assert( zFilename==0 || zFilename[0]=='/' );
29140 #endif
29142 /* No locking occurs in temporary files */
29143 assert( zFilename!=0 || noLock );
29145 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
29146 pNew->h = h;
29147 pNew->zPath = zFilename;
29148 if( memcmp(pVfs->zName,"unix-excl",10)==0 ){
29149 pNew->ctrlFlags = UNIXFILE_EXCL;
29150 }else{
29151 pNew->ctrlFlags = 0;
29153 if( isReadOnly ){
29154 pNew->ctrlFlags |= UNIXFILE_RDONLY;
29156 if( syncDir ){
29157 pNew->ctrlFlags |= UNIXFILE_DIRSYNC;
29160 #if OS_VXWORKS
29161 pNew->pId = vxworksFindFileId(zFilename);
29162 if( pNew->pId==0 ){
29163 noLock = 1;
29164 rc = SQLITE_NOMEM;
29166 #endif
29168 if( noLock ){
29169 pLockingStyle = &nolockIoMethods;
29170 }else{
29171 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
29172 #if SQLITE_ENABLE_LOCKING_STYLE
29173 /* Cache zFilename in the locking context (AFP and dotlock override) for
29174 ** proxyLock activation is possible (remote proxy is based on db name)
29175 ** zFilename remains valid until file is closed, to support */
29176 pNew->lockingContext = (void*)zFilename;
29177 #endif
29180 if( pLockingStyle == &posixIoMethods
29181 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
29182 || pLockingStyle == &nfsIoMethods
29183 #endif
29185 unixEnterMutex();
29186 rc = findInodeInfo(pNew, &pNew->pInode);
29187 if( rc!=SQLITE_OK ){
29188 /* If an error occured in findInodeInfo(), close the file descriptor
29189 ** immediately, before releasing the mutex. findInodeInfo() may fail
29190 ** in two scenarios:
29192 ** (a) A call to fstat() failed.
29193 ** (b) A malloc failed.
29195 ** Scenario (b) may only occur if the process is holding no other
29196 ** file descriptors open on the same file. If there were other file
29197 ** descriptors on this file, then no malloc would be required by
29198 ** findInodeInfo(). If this is the case, it is quite safe to close
29199 ** handle h - as it is guaranteed that no posix locks will be released
29200 ** by doing so.
29202 ** If scenario (a) caused the error then things are not so safe. The
29203 ** implicit assumption here is that if fstat() fails, things are in
29204 ** such bad shape that dropping a lock or two doesn't matter much.
29206 robust_close(pNew, h, __LINE__);
29207 h = -1;
29209 unixLeaveMutex();
29212 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
29213 else if( pLockingStyle == &afpIoMethods ){
29214 /* AFP locking uses the file path so it needs to be included in
29215 ** the afpLockingContext.
29217 afpLockingContext *pCtx;
29218 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
29219 if( pCtx==0 ){
29220 rc = SQLITE_NOMEM;
29221 }else{
29222 /* NB: zFilename exists and remains valid until the file is closed
29223 ** according to requirement F11141. So we do not need to make a
29224 ** copy of the filename. */
29225 pCtx->dbPath = zFilename;
29226 pCtx->reserved = 0;
29227 srandomdev();
29228 unixEnterMutex();
29229 rc = findInodeInfo(pNew, &pNew->pInode);
29230 if( rc!=SQLITE_OK ){
29231 sqlite3_free(pNew->lockingContext);
29232 robust_close(pNew, h, __LINE__);
29233 h = -1;
29235 unixLeaveMutex();
29238 #endif
29240 else if( pLockingStyle == &dotlockIoMethods ){
29241 /* Dotfile locking uses the file path so it needs to be included in
29242 ** the dotlockLockingContext
29244 char *zLockFile;
29245 int nFilename;
29246 assert( zFilename!=0 );
29247 nFilename = (int)strlen(zFilename) + 6;
29248 zLockFile = (char *)sqlite3_malloc(nFilename);
29249 if( zLockFile==0 ){
29250 rc = SQLITE_NOMEM;
29251 }else{
29252 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
29254 pNew->lockingContext = zLockFile;
29257 #if OS_VXWORKS
29258 else if( pLockingStyle == &semIoMethods ){
29259 /* Named semaphore locking uses the file path so it needs to be
29260 ** included in the semLockingContext
29262 unixEnterMutex();
29263 rc = findInodeInfo(pNew, &pNew->pInode);
29264 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
29265 char *zSemName = pNew->pInode->aSemName;
29266 int n;
29267 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
29268 pNew->pId->zCanonicalName);
29269 for( n=1; zSemName[n]; n++ )
29270 if( zSemName[n]=='/' ) zSemName[n] = '_';
29271 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
29272 if( pNew->pInode->pSem == SEM_FAILED ){
29273 rc = SQLITE_NOMEM;
29274 pNew->pInode->aSemName[0] = '\0';
29277 unixLeaveMutex();
29279 #endif
29281 pNew->lastErrno = 0;
29282 #if OS_VXWORKS
29283 if( rc!=SQLITE_OK ){
29284 if( h>=0 ) robust_close(pNew, h, __LINE__);
29285 h = -1;
29286 osUnlink(zFilename);
29287 isDelete = 0;
29289 pNew->isDelete = isDelete;
29290 #endif
29291 if( rc!=SQLITE_OK ){
29292 if( h>=0 ) robust_close(pNew, h, __LINE__);
29293 }else{
29294 pNew->pMethod = pLockingStyle;
29295 OpenCounter(+1);
29297 return rc;
29301 ** Return the name of a directory in which to put temporary files.
29302 ** If no suitable temporary file directory can be found, return NULL.
29304 static const char *unixTempFileDir(void){
29305 static const char *azDirs[] = {
29308 "/var/tmp",
29309 "/usr/tmp",
29310 "/tmp",
29311 0 /* List terminator */
29313 unsigned int i;
29314 struct stat buf;
29315 const char *zDir = 0;
29317 azDirs[0] = sqlite3_temp_directory;
29318 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
29319 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
29320 if( zDir==0 ) continue;
29321 if( osStat(zDir, &buf) ) continue;
29322 if( !S_ISDIR(buf.st_mode) ) continue;
29323 if( osAccess(zDir, 07) ) continue;
29324 break;
29326 return zDir;
29330 ** Create a temporary file name in zBuf. zBuf must be allocated
29331 ** by the calling process and must be big enough to hold at least
29332 ** pVfs->mxPathname bytes.
29334 static int unixGetTempname(int nBuf, char *zBuf){
29335 static const unsigned char zChars[] =
29336 "abcdefghijklmnopqrstuvwxyz"
29337 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
29338 "0123456789";
29339 unsigned int i, j;
29340 const char *zDir;
29342 /* It's odd to simulate an io-error here, but really this is just
29343 ** using the io-error infrastructure to test that SQLite handles this
29344 ** function failing.
29346 SimulateIOError( return SQLITE_IOERR );
29348 zDir = unixTempFileDir();
29349 if( zDir==0 ) zDir = ".";
29351 /* Check that the output buffer is large enough for the temporary file
29352 ** name. If it is not, return SQLITE_ERROR.
29354 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
29355 return SQLITE_ERROR;
29359 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
29360 j = (int)strlen(zBuf);
29361 sqlite3_randomness(15, &zBuf[j]);
29362 for(i=0; i<15; i++, j++){
29363 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
29365 zBuf[j] = 0;
29366 }while( osAccess(zBuf,0)==0 );
29367 return SQLITE_OK;
29370 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
29372 ** Routine to transform a unixFile into a proxy-locking unixFile.
29373 ** Implementation in the proxy-lock division, but used by unixOpen()
29374 ** if SQLITE_PREFER_PROXY_LOCKING is defined.
29376 static int proxyTransformUnixFile(unixFile*, const char*);
29377 #endif
29380 ** Search for an unused file descriptor that was opened on the database
29381 ** file (not a journal or master-journal file) identified by pathname
29382 ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
29383 ** argument to this function.
29385 ** Such a file descriptor may exist if a database connection was closed
29386 ** but the associated file descriptor could not be closed because some
29387 ** other file descriptor open on the same file is holding a file-lock.
29388 ** Refer to comments in the unixClose() function and the lengthy comment
29389 ** describing "Posix Advisory Locking" at the start of this file for
29390 ** further details. Also, ticket #4018.
29392 ** If a suitable file descriptor is found, then it is returned. If no
29393 ** such file descriptor is located, -1 is returned.
29395 static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
29396 UnixUnusedFd *pUnused = 0;
29398 /* Do not search for an unused file descriptor on vxworks. Not because
29399 ** vxworks would not benefit from the change (it might, we're not sure),
29400 ** but because no way to test it is currently available. It is better
29401 ** not to risk breaking vxworks support for the sake of such an obscure
29402 ** feature. */
29403 #if !OS_VXWORKS
29404 struct stat sStat; /* Results of stat() call */
29406 /* A stat() call may fail for various reasons. If this happens, it is
29407 ** almost certain that an open() call on the same path will also fail.
29408 ** For this reason, if an error occurs in the stat() call here, it is
29409 ** ignored and -1 is returned. The caller will try to open a new file
29410 ** descriptor on the same path, fail, and return an error to SQLite.
29412 ** Even if a subsequent open() call does succeed, the consequences of
29413 ** not searching for a resusable file descriptor are not dire. */
29414 if( 0==osStat(zPath, &sStat) ){
29415 unixInodeInfo *pInode;
29417 unixEnterMutex();
29418 pInode = inodeList;
29419 while( pInode && (pInode->fileId.dev!=sStat.st_dev
29420 || pInode->fileId.ino!=sStat.st_ino) ){
29421 pInode = pInode->pNext;
29423 if( pInode ){
29424 UnixUnusedFd **pp;
29425 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
29426 pUnused = *pp;
29427 if( pUnused ){
29428 *pp = pUnused->pNext;
29431 unixLeaveMutex();
29433 #endif /* if !OS_VXWORKS */
29434 return pUnused;
29438 ** This function is called by unixOpen() to determine the unix permissions
29439 ** to create new files with. If no error occurs, then SQLITE_OK is returned
29440 ** and a value suitable for passing as the third argument to open(2) is
29441 ** written to *pMode. If an IO error occurs, an SQLite error code is
29442 ** returned and the value of *pMode is not modified.
29444 ** If the file being opened is a temporary file, it is always created with
29445 ** the octal permissions 0600 (read/writable by owner only). If the file
29446 ** is a database or master journal file, it is created with the permissions
29447 ** mask SQLITE_DEFAULT_FILE_PERMISSIONS.
29449 ** Finally, if the file being opened is a WAL or regular journal file, then
29450 ** this function queries the file-system for the permissions on the
29451 ** corresponding database file and sets *pMode to this value. Whenever
29452 ** possible, WAL and journal files are created using the same permissions
29453 ** as the associated database file.
29455 ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
29456 ** original filename is unavailable. But 8_3_NAMES is only used for
29457 ** FAT filesystems and permissions do not matter there, so just use
29458 ** the default permissions.
29460 static int findCreateFileMode(
29461 const char *zPath, /* Path of file (possibly) being created */
29462 int flags, /* Flags passed as 4th argument to xOpen() */
29463 mode_t *pMode /* OUT: Permissions to open file with */
29465 int rc = SQLITE_OK; /* Return Code */
29466 *pMode = SQLITE_DEFAULT_FILE_PERMISSIONS;
29467 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
29468 char zDb[MAX_PATHNAME+1]; /* Database file path */
29469 int nDb; /* Number of valid bytes in zDb */
29470 struct stat sStat; /* Output of stat() on database file */
29472 /* zPath is a path to a WAL or journal file. The following block derives
29473 ** the path to the associated database file from zPath. This block handles
29474 ** the following naming conventions:
29476 ** "<path to db>-journal"
29477 ** "<path to db>-wal"
29478 ** "<path to db>-journalNN"
29479 ** "<path to db>-walNN"
29481 ** where NN is a decimal number. The NN naming schemes are
29482 ** used by the test_multiplex.c module.
29484 nDb = sqlite3Strlen30(zPath) - 1;
29485 #ifdef SQLITE_ENABLE_8_3_NAMES
29486 while( nDb>0 && !sqlite3Isalnum(zPath[nDb]) ) nDb--;
29487 if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
29488 #else
29489 while( zPath[nDb]!='-' ){
29490 assert( nDb>0 );
29491 assert( zPath[nDb]!='\n' );
29492 nDb--;
29494 #endif
29495 memcpy(zDb, zPath, nDb);
29496 zDb[nDb] = '\0';
29498 if( 0==osStat(zDb, &sStat) ){
29499 *pMode = sStat.st_mode & 0777;
29500 }else{
29501 rc = SQLITE_IOERR_FSTAT;
29503 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
29504 *pMode = 0600;
29506 return rc;
29510 ** Open the file zPath.
29512 ** Previously, the SQLite OS layer used three functions in place of this
29513 ** one:
29515 ** sqlite3OsOpenReadWrite();
29516 ** sqlite3OsOpenReadOnly();
29517 ** sqlite3OsOpenExclusive();
29519 ** These calls correspond to the following combinations of flags:
29521 ** ReadWrite() -> (READWRITE | CREATE)
29522 ** ReadOnly() -> (READONLY)
29523 ** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
29525 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
29526 ** true, the file was configured to be automatically deleted when the
29527 ** file handle closed. To achieve the same effect using this new
29528 ** interface, add the DELETEONCLOSE flag to those specified above for
29529 ** OpenExclusive().
29531 static int unixOpen(
29532 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
29533 const char *zPath, /* Pathname of file to be opened */
29534 sqlite3_file *pFile, /* The file descriptor to be filled in */
29535 int flags, /* Input flags to control the opening */
29536 int *pOutFlags /* Output flags returned to SQLite core */
29538 unixFile *p = (unixFile *)pFile;
29539 int fd = -1; /* File descriptor returned by open() */
29540 int openFlags = 0; /* Flags to pass to open() */
29541 int eType = flags&0xFFFFFF00; /* Type of file to open */
29542 int noLock; /* True to omit locking primitives */
29543 int rc = SQLITE_OK; /* Function Return Code */
29545 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
29546 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
29547 int isCreate = (flags & SQLITE_OPEN_CREATE);
29548 int isReadonly = (flags & SQLITE_OPEN_READONLY);
29549 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
29550 #if SQLITE_ENABLE_LOCKING_STYLE
29551 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
29552 #endif
29553 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
29554 struct statfs fsInfo;
29555 #endif
29557 /* If creating a master or main-file journal, this function will open
29558 ** a file-descriptor on the directory too. The first time unixSync()
29559 ** is called the directory file descriptor will be fsync()ed and close()d.
29561 int syncDir = (isCreate && (
29562 eType==SQLITE_OPEN_MASTER_JOURNAL
29563 || eType==SQLITE_OPEN_MAIN_JOURNAL
29564 || eType==SQLITE_OPEN_WAL
29567 /* If argument zPath is a NULL pointer, this function is required to open
29568 ** a temporary file. Use this buffer to store the file name in.
29570 char zTmpname[MAX_PATHNAME+1];
29571 const char *zName = zPath;
29573 /* Check the following statements are true:
29575 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
29576 ** (b) if CREATE is set, then READWRITE must also be set, and
29577 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
29578 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
29580 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
29581 assert(isCreate==0 || isReadWrite);
29582 assert(isExclusive==0 || isCreate);
29583 assert(isDelete==0 || isCreate);
29585 /* The main DB, main journal, WAL file and master journal are never
29586 ** automatically deleted. Nor are they ever temporary files. */
29587 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
29588 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
29589 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
29590 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
29592 /* Assert that the upper layer has set one of the "file-type" flags. */
29593 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
29594 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
29595 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
29596 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
29599 memset(p, 0, sizeof(unixFile));
29601 if( eType==SQLITE_OPEN_MAIN_DB ){
29602 UnixUnusedFd *pUnused;
29603 pUnused = findReusableFd(zName, flags);
29604 if( pUnused ){
29605 fd = pUnused->fd;
29606 }else{
29607 pUnused = sqlite3_malloc(sizeof(*pUnused));
29608 if( !pUnused ){
29609 return SQLITE_NOMEM;
29612 p->pUnused = pUnused;
29613 }else if( !zName ){
29614 /* If zName is NULL, the upper layer is requesting a temp file. */
29615 assert(isDelete && !syncDir);
29616 rc = unixGetTempname(MAX_PATHNAME+1, zTmpname);
29617 if( rc!=SQLITE_OK ){
29618 return rc;
29620 zName = zTmpname;
29623 /* Determine the value of the flags parameter passed to POSIX function
29624 ** open(). These must be calculated even if open() is not called, as
29625 ** they may be stored as part of the file handle and used by the
29626 ** 'conch file' locking functions later on. */
29627 if( isReadonly ) openFlags |= O_RDONLY;
29628 if( isReadWrite ) openFlags |= O_RDWR;
29629 if( isCreate ) openFlags |= O_CREAT;
29630 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
29631 openFlags |= (O_LARGEFILE|O_BINARY);
29633 if( fd<0 ){
29634 mode_t openMode; /* Permissions to create file with */
29635 rc = findCreateFileMode(zName, flags, &openMode);
29636 if( rc!=SQLITE_OK ){
29637 assert( !p->pUnused );
29638 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
29639 return rc;
29641 fd = robust_open(zName, openFlags, openMode);
29642 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
29643 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
29644 /* Failed to open the file for read/write access. Try read-only. */
29645 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
29646 openFlags &= ~(O_RDWR|O_CREAT);
29647 flags |= SQLITE_OPEN_READONLY;
29648 openFlags |= O_RDONLY;
29649 isReadonly = 1;
29650 fd = robust_open(zName, openFlags, openMode);
29652 if( fd<0 ){
29653 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
29654 goto open_finished;
29657 assert( fd>=0 );
29658 if( pOutFlags ){
29659 *pOutFlags = flags;
29662 if( p->pUnused ){
29663 p->pUnused->fd = fd;
29664 p->pUnused->flags = flags;
29667 if( isDelete ){
29668 #if OS_VXWORKS
29669 zPath = zName;
29670 #else
29671 osUnlink(zName);
29672 #endif
29674 #if SQLITE_ENABLE_LOCKING_STYLE
29675 else{
29676 p->openFlags = openFlags;
29678 #endif
29680 #ifdef FD_CLOEXEC
29681 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
29682 #endif
29684 noLock = eType!=SQLITE_OPEN_MAIN_DB;
29687 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
29688 if( fstatfs(fd, &fsInfo) == -1 ){
29689 ((unixFile*)pFile)->lastErrno = errno;
29690 robust_close(p, fd, __LINE__);
29691 return SQLITE_IOERR_ACCESS;
29693 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
29694 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
29696 #endif
29698 #if SQLITE_ENABLE_LOCKING_STYLE
29699 #if SQLITE_PREFER_PROXY_LOCKING
29700 isAutoProxy = 1;
29701 #endif
29702 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
29703 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
29704 int useProxy = 0;
29706 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
29707 ** never use proxy, NULL means use proxy for non-local files only. */
29708 if( envforce!=NULL ){
29709 useProxy = atoi(envforce)>0;
29710 }else{
29711 if( statfs(zPath, &fsInfo) == -1 ){
29712 /* In theory, the close(fd) call is sub-optimal. If the file opened
29713 ** with fd is a database file, and there are other connections open
29714 ** on that file that are currently holding advisory locks on it,
29715 ** then the call to close() will cancel those locks. In practice,
29716 ** we're assuming that statfs() doesn't fail very often. At least
29717 ** not while other file descriptors opened by the same process on
29718 ** the same file are working. */
29719 p->lastErrno = errno;
29720 robust_close(p, fd, __LINE__);
29721 rc = SQLITE_IOERR_ACCESS;
29722 goto open_finished;
29724 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
29726 if( useProxy ){
29727 rc = fillInUnixFile(pVfs, fd, syncDir, pFile, zPath, noLock,
29728 isDelete, isReadonly);
29729 if( rc==SQLITE_OK ){
29730 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
29731 if( rc!=SQLITE_OK ){
29732 /* Use unixClose to clean up the resources added in fillInUnixFile
29733 ** and clear all the structure's references. Specifically,
29734 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
29736 unixClose(pFile);
29737 return rc;
29740 goto open_finished;
29743 #endif
29745 rc = fillInUnixFile(pVfs, fd, syncDir, pFile, zPath, noLock,
29746 isDelete, isReadonly);
29747 open_finished:
29748 if( rc!=SQLITE_OK ){
29749 sqlite3_free(p->pUnused);
29751 return rc;
29756 ** Delete the file at zPath. If the dirSync argument is true, fsync()
29757 ** the directory after deleting the file.
29759 static int unixDelete(
29760 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
29761 const char *zPath, /* Name of file to be deleted */
29762 int dirSync /* If true, fsync() directory after deleting file */
29764 int rc = SQLITE_OK;
29765 UNUSED_PARAMETER(NotUsed);
29766 SimulateIOError(return SQLITE_IOERR_DELETE);
29767 if( osUnlink(zPath)==(-1) && errno!=ENOENT ){
29768 return unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
29770 #ifndef SQLITE_DISABLE_DIRSYNC
29771 if( dirSync ){
29772 int fd;
29773 rc = osOpenDirectory(zPath, &fd);
29774 if( rc==SQLITE_OK ){
29775 #if OS_VXWORKS
29776 if( fsync(fd)==-1 )
29777 #else
29778 if( fsync(fd) )
29779 #endif
29781 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
29783 robust_close(0, fd, __LINE__);
29784 }else if( rc==SQLITE_CANTOPEN ){
29785 rc = SQLITE_OK;
29788 #endif
29789 return rc;
29793 ** Test the existance of or access permissions of file zPath. The
29794 ** test performed depends on the value of flags:
29796 ** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
29797 ** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
29798 ** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
29800 ** Otherwise return 0.
29802 static int unixAccess(
29803 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
29804 const char *zPath, /* Path of the file to examine */
29805 int flags, /* What do we want to learn about the zPath file? */
29806 int *pResOut /* Write result boolean here */
29808 int amode = 0;
29809 UNUSED_PARAMETER(NotUsed);
29810 SimulateIOError( return SQLITE_IOERR_ACCESS; );
29811 switch( flags ){
29812 case SQLITE_ACCESS_EXISTS:
29813 amode = F_OK;
29814 break;
29815 case SQLITE_ACCESS_READWRITE:
29816 amode = W_OK|R_OK;
29817 break;
29818 case SQLITE_ACCESS_READ:
29819 amode = R_OK;
29820 break;
29822 default:
29823 assert(!"Invalid flags argument");
29825 *pResOut = (osAccess(zPath, amode)==0);
29826 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
29827 struct stat buf;
29828 if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
29829 *pResOut = 0;
29832 return SQLITE_OK;
29837 ** Turn a relative pathname into a full pathname. The relative path
29838 ** is stored as a nul-terminated string in the buffer pointed to by
29839 ** zPath.
29841 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
29842 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
29843 ** this buffer before returning.
29845 static int unixFullPathname(
29846 sqlite3_vfs *pVfs, /* Pointer to vfs object */
29847 const char *zPath, /* Possibly relative input path */
29848 int nOut, /* Size of output buffer in bytes */
29849 char *zOut /* Output buffer */
29852 /* It's odd to simulate an io-error here, but really this is just
29853 ** using the io-error infrastructure to test that SQLite handles this
29854 ** function failing. This function could fail if, for example, the
29855 ** current working directory has been unlinked.
29857 SimulateIOError( return SQLITE_ERROR );
29859 assert( pVfs->mxPathname==MAX_PATHNAME );
29860 UNUSED_PARAMETER(pVfs);
29862 zOut[nOut-1] = '\0';
29863 if( zPath[0]=='/' ){
29864 sqlite3_snprintf(nOut, zOut, "%s", zPath);
29865 }else{
29866 int nCwd;
29867 if( osGetcwd(zOut, nOut-1)==0 ){
29868 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
29870 nCwd = (int)strlen(zOut);
29871 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
29873 return SQLITE_OK;
29877 #ifndef SQLITE_OMIT_LOAD_EXTENSION
29879 ** Interfaces for opening a shared library, finding entry points
29880 ** within the shared library, and closing the shared library.
29882 #include <dlfcn.h>
29883 static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
29884 UNUSED_PARAMETER(NotUsed);
29885 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
29889 ** SQLite calls this function immediately after a call to unixDlSym() or
29890 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
29891 ** message is available, it is written to zBufOut. If no error message
29892 ** is available, zBufOut is left unmodified and SQLite uses a default
29893 ** error message.
29895 static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
29896 const char *zErr;
29897 UNUSED_PARAMETER(NotUsed);
29898 unixEnterMutex();
29899 zErr = dlerror();
29900 if( zErr ){
29901 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
29903 unixLeaveMutex();
29905 static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
29907 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
29908 ** cast into a pointer to a function. And yet the library dlsym() routine
29909 ** returns a void* which is really a pointer to a function. So how do we
29910 ** use dlsym() with -pedantic-errors?
29912 ** Variable x below is defined to be a pointer to a function taking
29913 ** parameters void* and const char* and returning a pointer to a function.
29914 ** We initialize x by assigning it a pointer to the dlsym() function.
29915 ** (That assignment requires a cast.) Then we call the function that
29916 ** x points to.
29918 ** This work-around is unlikely to work correctly on any system where
29919 ** you really cannot cast a function pointer into void*. But then, on the
29920 ** other hand, dlsym() will not work on such a system either, so we have
29921 ** not really lost anything.
29923 void (*(*x)(void*,const char*))(void);
29924 UNUSED_PARAMETER(NotUsed);
29925 x = (void(*(*)(void*,const char*))(void))dlsym;
29926 return (*x)(p, zSym);
29928 static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
29929 UNUSED_PARAMETER(NotUsed);
29930 dlclose(pHandle);
29932 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
29933 #define unixDlOpen 0
29934 #define unixDlError 0
29935 #define unixDlSym 0
29936 #define unixDlClose 0
29937 #endif
29940 ** Write nBuf bytes of random data to the supplied buffer zBuf.
29942 static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
29943 UNUSED_PARAMETER(NotUsed);
29944 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
29946 /* We have to initialize zBuf to prevent valgrind from reporting
29947 ** errors. The reports issued by valgrind are incorrect - we would
29948 ** prefer that the randomness be increased by making use of the
29949 ** uninitialized space in zBuf - but valgrind errors tend to worry
29950 ** some users. Rather than argue, it seems easier just to initialize
29951 ** the whole array and silence valgrind, even if that means less randomness
29952 ** in the random seed.
29954 ** When testing, initializing zBuf[] to zero is all we do. That means
29955 ** that we always use the same random number sequence. This makes the
29956 ** tests repeatable.
29958 memset(zBuf, 0, nBuf);
29959 #if !defined(SQLITE_TEST)
29961 int pid, fd;
29962 fd = robust_open("/dev/urandom", O_RDONLY, 0);
29963 if( fd<0 ){
29964 time_t t;
29965 time(&t);
29966 memcpy(zBuf, &t, sizeof(t));
29967 pid = getpid();
29968 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
29969 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
29970 nBuf = sizeof(t) + sizeof(pid);
29971 }else{
29972 do{ nBuf = osRead(fd, zBuf, nBuf); }while( nBuf<0 && errno==EINTR );
29973 robust_close(0, fd, __LINE__);
29976 #endif
29977 return nBuf;
29982 ** Sleep for a little while. Return the amount of time slept.
29983 ** The argument is the number of microseconds we want to sleep.
29984 ** The return value is the number of microseconds of sleep actually
29985 ** requested from the underlying operating system, a number which
29986 ** might be greater than or equal to the argument, but not less
29987 ** than the argument.
29989 static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
29990 #if OS_VXWORKS
29991 struct timespec sp;
29993 sp.tv_sec = microseconds / 1000000;
29994 sp.tv_nsec = (microseconds % 1000000) * 1000;
29995 nanosleep(&sp, NULL);
29996 UNUSED_PARAMETER(NotUsed);
29997 return microseconds;
29998 #elif defined(HAVE_USLEEP) && HAVE_USLEEP
29999 usleep(microseconds);
30000 UNUSED_PARAMETER(NotUsed);
30001 return microseconds;
30002 #else
30003 int seconds = (microseconds+999999)/1000000;
30004 sleep(seconds);
30005 UNUSED_PARAMETER(NotUsed);
30006 return seconds*1000000;
30007 #endif
30011 ** The following variable, if set to a non-zero value, is interpreted as
30012 ** the number of seconds since 1970 and is used to set the result of
30013 ** sqlite3OsCurrentTime() during testing.
30015 #ifdef SQLITE_TEST
30016 SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
30017 #endif
30020 ** Find the current time (in Universal Coordinated Time). Write into *piNow
30021 ** the current time and date as a Julian Day number times 86_400_000. In
30022 ** other words, write into *piNow the number of milliseconds since the Julian
30023 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
30024 ** proleptic Gregorian calendar.
30026 ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
30027 ** cannot be found.
30029 static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
30030 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
30031 int rc = SQLITE_OK;
30032 #if defined(NO_GETTOD)
30033 time_t t;
30034 time(&t);
30035 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
30036 #elif OS_VXWORKS
30037 struct timespec sNow;
30038 clock_gettime(CLOCK_REALTIME, &sNow);
30039 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
30040 #else
30041 struct timeval sNow;
30042 if( gettimeofday(&sNow, 0)==0 ){
30043 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
30044 }else{
30045 rc = SQLITE_ERROR;
30047 #endif
30049 #ifdef SQLITE_TEST
30050 if( sqlite3_current_time ){
30051 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
30053 #endif
30054 UNUSED_PARAMETER(NotUsed);
30055 return rc;
30059 ** Find the current time (in Universal Coordinated Time). Write the
30060 ** current time and date as a Julian Day number into *prNow and
30061 ** return 0. Return 1 if the time and date cannot be found.
30063 static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
30064 sqlite3_int64 i = 0;
30065 int rc;
30066 UNUSED_PARAMETER(NotUsed);
30067 rc = unixCurrentTimeInt64(0, &i);
30068 *prNow = i/86400000.0;
30069 return rc;
30073 ** We added the xGetLastError() method with the intention of providing
30074 ** better low-level error messages when operating-system problems come up
30075 ** during SQLite operation. But so far, none of that has been implemented
30076 ** in the core. So this routine is never called. For now, it is merely
30077 ** a place-holder.
30079 static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
30080 UNUSED_PARAMETER(NotUsed);
30081 UNUSED_PARAMETER(NotUsed2);
30082 UNUSED_PARAMETER(NotUsed3);
30083 return 0;
30088 ************************ End of sqlite3_vfs methods ***************************
30089 ******************************************************************************/
30091 /******************************************************************************
30092 ************************** Begin Proxy Locking ********************************
30094 ** Proxy locking is a "uber-locking-method" in this sense: It uses the
30095 ** other locking methods on secondary lock files. Proxy locking is a
30096 ** meta-layer over top of the primitive locking implemented above. For
30097 ** this reason, the division that implements of proxy locking is deferred
30098 ** until late in the file (here) after all of the other I/O methods have
30099 ** been defined - so that the primitive locking methods are available
30100 ** as services to help with the implementation of proxy locking.
30102 ****
30104 ** The default locking schemes in SQLite use byte-range locks on the
30105 ** database file to coordinate safe, concurrent access by multiple readers
30106 ** and writers [http://sqlite.org/lockingv3.html]. The five file locking
30107 ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
30108 ** as POSIX read & write locks over fixed set of locations (via fsctl),
30109 ** on AFP and SMB only exclusive byte-range locks are available via fsctl
30110 ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
30111 ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
30112 ** address in the shared range is taken for a SHARED lock, the entire
30113 ** shared range is taken for an EXCLUSIVE lock):
30115 ** PENDING_BYTE 0x40000000
30116 ** RESERVED_BYTE 0x40000001
30117 ** SHARED_RANGE 0x40000002 -> 0x40000200
30119 ** This works well on the local file system, but shows a nearly 100x
30120 ** slowdown in read performance on AFP because the AFP client disables
30121 ** the read cache when byte-range locks are present. Enabling the read
30122 ** cache exposes a cache coherency problem that is present on all OS X
30123 ** supported network file systems. NFS and AFP both observe the
30124 ** close-to-open semantics for ensuring cache coherency
30125 ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
30126 ** address the requirements for concurrent database access by multiple
30127 ** readers and writers
30128 ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
30130 ** To address the performance and cache coherency issues, proxy file locking
30131 ** changes the way database access is controlled by limiting access to a
30132 ** single host at a time and moving file locks off of the database file
30133 ** and onto a proxy file on the local file system.
30136 ** Using proxy locks
30137 ** -----------------
30139 ** C APIs
30141 ** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
30142 ** <proxy_path> | ":auto:");
30143 ** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
30146 ** SQL pragmas
30148 ** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
30149 ** PRAGMA [database.]lock_proxy_file
30151 ** Specifying ":auto:" means that if there is a conch file with a matching
30152 ** host ID in it, the proxy path in the conch file will be used, otherwise
30153 ** a proxy path based on the user's temp dir
30154 ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
30155 ** actual proxy file name is generated from the name and path of the
30156 ** database file. For example:
30158 ** For database path "/Users/me/foo.db"
30159 ** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
30161 ** Once a lock proxy is configured for a database connection, it can not
30162 ** be removed, however it may be switched to a different proxy path via
30163 ** the above APIs (assuming the conch file is not being held by another
30164 ** connection or process).
30167 ** How proxy locking works
30168 ** -----------------------
30170 ** Proxy file locking relies primarily on two new supporting files:
30172 ** * conch file to limit access to the database file to a single host
30173 ** at a time
30175 ** * proxy file to act as a proxy for the advisory locks normally
30176 ** taken on the database
30178 ** The conch file - to use a proxy file, sqlite must first "hold the conch"
30179 ** by taking an sqlite-style shared lock on the conch file, reading the
30180 ** contents and comparing the host's unique host ID (see below) and lock
30181 ** proxy path against the values stored in the conch. The conch file is
30182 ** stored in the same directory as the database file and the file name
30183 ** is patterned after the database file name as ".<databasename>-conch".
30184 ** If the conch file does not exist, or it's contents do not match the
30185 ** host ID and/or proxy path, then the lock is escalated to an exclusive
30186 ** lock and the conch file contents is updated with the host ID and proxy
30187 ** path and the lock is downgraded to a shared lock again. If the conch
30188 ** is held by another process (with a shared lock), the exclusive lock
30189 ** will fail and SQLITE_BUSY is returned.
30191 ** The proxy file - a single-byte file used for all advisory file locks
30192 ** normally taken on the database file. This allows for safe sharing
30193 ** of the database file for multiple readers and writers on the same
30194 ** host (the conch ensures that they all use the same local lock file).
30196 ** Requesting the lock proxy does not immediately take the conch, it is
30197 ** only taken when the first request to lock database file is made.
30198 ** This matches the semantics of the traditional locking behavior, where
30199 ** opening a connection to a database file does not take a lock on it.
30200 ** The shared lock and an open file descriptor are maintained until
30201 ** the connection to the database is closed.
30203 ** The proxy file and the lock file are never deleted so they only need
30204 ** to be created the first time they are used.
30206 ** Configuration options
30207 ** ---------------------
30209 ** SQLITE_PREFER_PROXY_LOCKING
30211 ** Database files accessed on non-local file systems are
30212 ** automatically configured for proxy locking, lock files are
30213 ** named automatically using the same logic as
30214 ** PRAGMA lock_proxy_file=":auto:"
30216 ** SQLITE_PROXY_DEBUG
30218 ** Enables the logging of error messages during host id file
30219 ** retrieval and creation
30221 ** LOCKPROXYDIR
30223 ** Overrides the default directory used for lock proxy files that
30224 ** are named automatically via the ":auto:" setting
30226 ** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
30228 ** Permissions to use when creating a directory for storing the
30229 ** lock proxy files, only used when LOCKPROXYDIR is not set.
30232 ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
30233 ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
30234 ** force proxy locking to be used for every database file opened, and 0
30235 ** will force automatic proxy locking to be disabled for all database
30236 ** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
30237 ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
30241 ** Proxy locking is only available on MacOSX
30243 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
30246 ** The proxyLockingContext has the path and file structures for the remote
30247 ** and local proxy files in it
30249 typedef struct proxyLockingContext proxyLockingContext;
30250 struct proxyLockingContext {
30251 unixFile *conchFile; /* Open conch file */
30252 char *conchFilePath; /* Name of the conch file */
30253 unixFile *lockProxy; /* Open proxy lock file */
30254 char *lockProxyPath; /* Name of the proxy lock file */
30255 char *dbPath; /* Name of the open file */
30256 int conchHeld; /* 1 if the conch is held, -1 if lockless */
30257 void *oldLockingContext; /* Original lockingcontext to restore on close */
30258 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
30262 ** The proxy lock file path for the database at dbPath is written into lPath,
30263 ** which must point to valid, writable memory large enough for a maxLen length
30264 ** file path.
30266 static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
30267 int len;
30268 int dbLen;
30269 int i;
30271 #ifdef LOCKPROXYDIR
30272 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
30273 #else
30274 # ifdef _CS_DARWIN_USER_TEMP_DIR
30276 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
30277 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
30278 lPath, errno, getpid()));
30279 return SQLITE_IOERR_LOCK;
30281 len = strlcat(lPath, "sqliteplocks", maxLen);
30283 # else
30284 len = strlcpy(lPath, "/tmp/", maxLen);
30285 # endif
30286 #endif
30288 if( lPath[len-1]!='/' ){
30289 len = strlcat(lPath, "/", maxLen);
30292 /* transform the db path to a unique cache name */
30293 dbLen = (int)strlen(dbPath);
30294 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
30295 char c = dbPath[i];
30296 lPath[i+len] = (c=='/')?'_':c;
30298 lPath[i+len]='\0';
30299 strlcat(lPath, ":auto:", maxLen);
30300 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
30301 return SQLITE_OK;
30305 ** Creates the lock file and any missing directories in lockPath
30307 static int proxyCreateLockPath(const char *lockPath){
30308 int i, len;
30309 char buf[MAXPATHLEN];
30310 int start = 0;
30312 assert(lockPath!=NULL);
30313 /* try to create all the intermediate directories */
30314 len = (int)strlen(lockPath);
30315 buf[0] = lockPath[0];
30316 for( i=1; i<len; i++ ){
30317 if( lockPath[i] == '/' && (i - start > 0) ){
30318 /* only mkdir if leaf dir != "." or "/" or ".." */
30319 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
30320 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
30321 buf[i]='\0';
30322 if( mkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
30323 int err=errno;
30324 if( err!=EEXIST ) {
30325 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
30326 "'%s' proxy lock path=%s pid=%d\n",
30327 buf, strerror(err), lockPath, getpid()));
30328 return err;
30332 start=i+1;
30334 buf[i] = lockPath[i];
30336 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
30337 return 0;
30341 ** Create a new VFS file descriptor (stored in memory obtained from
30342 ** sqlite3_malloc) and open the file named "path" in the file descriptor.
30344 ** The caller is responsible not only for closing the file descriptor
30345 ** but also for freeing the memory associated with the file descriptor.
30347 static int proxyCreateUnixFile(
30348 const char *path, /* path for the new unixFile */
30349 unixFile **ppFile, /* unixFile created and returned by ref */
30350 int islockfile /* if non zero missing dirs will be created */
30352 int fd = -1;
30353 unixFile *pNew;
30354 int rc = SQLITE_OK;
30355 int openFlags = O_RDWR | O_CREAT;
30356 sqlite3_vfs dummyVfs;
30357 int terrno = 0;
30358 UnixUnusedFd *pUnused = NULL;
30360 /* 1. first try to open/create the file
30361 ** 2. if that fails, and this is a lock file (not-conch), try creating
30362 ** the parent directories and then try again.
30363 ** 3. if that fails, try to open the file read-only
30364 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
30366 pUnused = findReusableFd(path, openFlags);
30367 if( pUnused ){
30368 fd = pUnused->fd;
30369 }else{
30370 pUnused = sqlite3_malloc(sizeof(*pUnused));
30371 if( !pUnused ){
30372 return SQLITE_NOMEM;
30375 if( fd<0 ){
30376 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
30377 terrno = errno;
30378 if( fd<0 && errno==ENOENT && islockfile ){
30379 if( proxyCreateLockPath(path) == SQLITE_OK ){
30380 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
30384 if( fd<0 ){
30385 openFlags = O_RDONLY;
30386 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
30387 terrno = errno;
30389 if( fd<0 ){
30390 if( islockfile ){
30391 return SQLITE_BUSY;
30393 switch (terrno) {
30394 case EACCES:
30395 return SQLITE_PERM;
30396 case EIO:
30397 return SQLITE_IOERR_LOCK; /* even though it is the conch */
30398 default:
30399 return SQLITE_CANTOPEN_BKPT;
30403 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
30404 if( pNew==NULL ){
30405 rc = SQLITE_NOMEM;
30406 goto end_create_proxy;
30408 memset(pNew, 0, sizeof(unixFile));
30409 pNew->openFlags = openFlags;
30410 memset(&dummyVfs, 0, sizeof(dummyVfs));
30411 dummyVfs.pAppData = (void*)&autolockIoFinder;
30412 dummyVfs.zName = "dummy";
30413 pUnused->fd = fd;
30414 pUnused->flags = openFlags;
30415 pNew->pUnused = pUnused;
30417 rc = fillInUnixFile(&dummyVfs, fd, 0, (sqlite3_file*)pNew, path, 0, 0, 0);
30418 if( rc==SQLITE_OK ){
30419 *ppFile = pNew;
30420 return SQLITE_OK;
30422 end_create_proxy:
30423 robust_close(pNew, fd, __LINE__);
30424 sqlite3_free(pNew);
30425 sqlite3_free(pUnused);
30426 return rc;
30429 #ifdef SQLITE_TEST
30430 /* simulate multiple hosts by creating unique hostid file paths */
30431 SQLITE_API int sqlite3_hostid_num = 0;
30432 #endif
30434 #define PROXY_HOSTIDLEN 16 /* conch file host id length */
30436 /* Not always defined in the headers as it ought to be */
30437 extern int gethostuuid(uuid_t id, const struct timespec *wait);
30439 /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
30440 ** bytes of writable memory.
30442 static int proxyGetHostID(unsigned char *pHostID, int *pError){
30443 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
30444 memset(pHostID, 0, PROXY_HOSTIDLEN);
30445 #if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
30446 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
30448 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
30449 if( gethostuuid(pHostID, &timeout) ){
30450 int err = errno;
30451 if( pError ){
30452 *pError = err;
30454 return SQLITE_IOERR;
30457 #else
30458 UNUSED_PARAMETER(pError);
30459 #endif
30460 #ifdef SQLITE_TEST
30461 /* simulate multiple hosts by creating unique hostid file paths */
30462 if( sqlite3_hostid_num != 0){
30463 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
30465 #endif
30467 return SQLITE_OK;
30470 /* The conch file contains the header, host id and lock file path
30472 #define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
30473 #define PROXY_HEADERLEN 1 /* conch file header length */
30474 #define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
30475 #define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
30478 ** Takes an open conch file, copies the contents to a new path and then moves
30479 ** it back. The newly created file's file descriptor is assigned to the
30480 ** conch file structure and finally the original conch file descriptor is
30481 ** closed. Returns zero if successful.
30483 static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
30484 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30485 unixFile *conchFile = pCtx->conchFile;
30486 char tPath[MAXPATHLEN];
30487 char buf[PROXY_MAXCONCHLEN];
30488 char *cPath = pCtx->conchFilePath;
30489 size_t readLen = 0;
30490 size_t pathLen = 0;
30491 char errmsg[64] = "";
30492 int fd = -1;
30493 int rc = -1;
30494 UNUSED_PARAMETER(myHostID);
30496 /* create a new path by replace the trailing '-conch' with '-break' */
30497 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
30498 if( pathLen>MAXPATHLEN || pathLen<6 ||
30499 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
30500 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
30501 goto end_breaklock;
30503 /* read the conch content */
30504 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
30505 if( readLen<PROXY_PATHINDEX ){
30506 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
30507 goto end_breaklock;
30509 /* write it out to the temporary break file */
30510 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL),
30511 SQLITE_DEFAULT_FILE_PERMISSIONS);
30512 if( fd<0 ){
30513 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
30514 goto end_breaklock;
30516 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
30517 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
30518 goto end_breaklock;
30520 if( rename(tPath, cPath) ){
30521 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
30522 goto end_breaklock;
30524 rc = 0;
30525 fprintf(stderr, "broke stale lock on %s\n", cPath);
30526 robust_close(pFile, conchFile->h, __LINE__);
30527 conchFile->h = fd;
30528 conchFile->openFlags = O_RDWR | O_CREAT;
30530 end_breaklock:
30531 if( rc ){
30532 if( fd>=0 ){
30533 osUnlink(tPath);
30534 robust_close(pFile, fd, __LINE__);
30536 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
30538 return rc;
30541 /* Take the requested lock on the conch file and break a stale lock if the
30542 ** host id matches.
30544 static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
30545 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30546 unixFile *conchFile = pCtx->conchFile;
30547 int rc = SQLITE_OK;
30548 int nTries = 0;
30549 struct timespec conchModTime;
30551 memset(&conchModTime, 0, sizeof(conchModTime));
30552 do {
30553 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
30554 nTries ++;
30555 if( rc==SQLITE_BUSY ){
30556 /* If the lock failed (busy):
30557 * 1st try: get the mod time of the conch, wait 0.5s and try again.
30558 * 2nd try: fail if the mod time changed or host id is different, wait
30559 * 10 sec and try again
30560 * 3rd try: break the lock unless the mod time has changed.
30562 struct stat buf;
30563 if( osFstat(conchFile->h, &buf) ){
30564 pFile->lastErrno = errno;
30565 return SQLITE_IOERR_LOCK;
30568 if( nTries==1 ){
30569 conchModTime = buf.st_mtimespec;
30570 usleep(500000); /* wait 0.5 sec and try the lock again*/
30571 continue;
30574 assert( nTries>1 );
30575 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
30576 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
30577 return SQLITE_BUSY;
30580 if( nTries==2 ){
30581 char tBuf[PROXY_MAXCONCHLEN];
30582 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
30583 if( len<0 ){
30584 pFile->lastErrno = errno;
30585 return SQLITE_IOERR_LOCK;
30587 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
30588 /* don't break the lock if the host id doesn't match */
30589 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
30590 return SQLITE_BUSY;
30592 }else{
30593 /* don't break the lock on short read or a version mismatch */
30594 return SQLITE_BUSY;
30596 usleep(10000000); /* wait 10 sec and try the lock again */
30597 continue;
30600 assert( nTries==3 );
30601 if( 0==proxyBreakConchLock(pFile, myHostID) ){
30602 rc = SQLITE_OK;
30603 if( lockType==EXCLUSIVE_LOCK ){
30604 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
30606 if( !rc ){
30607 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
30611 } while( rc==SQLITE_BUSY && nTries<3 );
30613 return rc;
30616 /* Takes the conch by taking a shared lock and read the contents conch, if
30617 ** lockPath is non-NULL, the host ID and lock file path must match. A NULL
30618 ** lockPath means that the lockPath in the conch file will be used if the
30619 ** host IDs match, or a new lock path will be generated automatically
30620 ** and written to the conch file.
30622 static int proxyTakeConch(unixFile *pFile){
30623 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30625 if( pCtx->conchHeld!=0 ){
30626 return SQLITE_OK;
30627 }else{
30628 unixFile *conchFile = pCtx->conchFile;
30629 uuid_t myHostID;
30630 int pError = 0;
30631 char readBuf[PROXY_MAXCONCHLEN];
30632 char lockPath[MAXPATHLEN];
30633 char *tempLockPath = NULL;
30634 int rc = SQLITE_OK;
30635 int createConch = 0;
30636 int hostIdMatch = 0;
30637 int readLen = 0;
30638 int tryOldLockPath = 0;
30639 int forceNewLockPath = 0;
30641 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
30642 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
30644 rc = proxyGetHostID(myHostID, &pError);
30645 if( (rc&0xff)==SQLITE_IOERR ){
30646 pFile->lastErrno = pError;
30647 goto end_takeconch;
30649 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
30650 if( rc!=SQLITE_OK ){
30651 goto end_takeconch;
30653 /* read the existing conch file */
30654 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
30655 if( readLen<0 ){
30656 /* I/O error: lastErrno set by seekAndRead */
30657 pFile->lastErrno = conchFile->lastErrno;
30658 rc = SQLITE_IOERR_READ;
30659 goto end_takeconch;
30660 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
30661 readBuf[0]!=(char)PROXY_CONCHVERSION ){
30662 /* a short read or version format mismatch means we need to create a new
30663 ** conch file.
30665 createConch = 1;
30667 /* if the host id matches and the lock path already exists in the conch
30668 ** we'll try to use the path there, if we can't open that path, we'll
30669 ** retry with a new auto-generated path
30671 do { /* in case we need to try again for an :auto: named lock file */
30673 if( !createConch && !forceNewLockPath ){
30674 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
30675 PROXY_HOSTIDLEN);
30676 /* if the conch has data compare the contents */
30677 if( !pCtx->lockProxyPath ){
30678 /* for auto-named local lock file, just check the host ID and we'll
30679 ** use the local lock file path that's already in there
30681 if( hostIdMatch ){
30682 size_t pathLen = (readLen - PROXY_PATHINDEX);
30684 if( pathLen>=MAXPATHLEN ){
30685 pathLen=MAXPATHLEN-1;
30687 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
30688 lockPath[pathLen] = 0;
30689 tempLockPath = lockPath;
30690 tryOldLockPath = 1;
30691 /* create a copy of the lock path if the conch is taken */
30692 goto end_takeconch;
30694 }else if( hostIdMatch
30695 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
30696 readLen-PROXY_PATHINDEX)
30698 /* conch host and lock path match */
30699 goto end_takeconch;
30703 /* if the conch isn't writable and doesn't match, we can't take it */
30704 if( (conchFile->openFlags&O_RDWR) == 0 ){
30705 rc = SQLITE_BUSY;
30706 goto end_takeconch;
30709 /* either the conch didn't match or we need to create a new one */
30710 if( !pCtx->lockProxyPath ){
30711 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
30712 tempLockPath = lockPath;
30713 /* create a copy of the lock path _only_ if the conch is taken */
30716 /* update conch with host and path (this will fail if other process
30717 ** has a shared lock already), if the host id matches, use the big
30718 ** stick.
30720 futimes(conchFile->h, NULL);
30721 if( hostIdMatch && !createConch ){
30722 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
30723 /* We are trying for an exclusive lock but another thread in this
30724 ** same process is still holding a shared lock. */
30725 rc = SQLITE_BUSY;
30726 } else {
30727 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
30729 }else{
30730 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
30732 if( rc==SQLITE_OK ){
30733 char writeBuffer[PROXY_MAXCONCHLEN];
30734 int writeSize = 0;
30736 writeBuffer[0] = (char)PROXY_CONCHVERSION;
30737 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
30738 if( pCtx->lockProxyPath!=NULL ){
30739 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
30740 }else{
30741 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
30743 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
30744 robust_ftruncate(conchFile->h, writeSize);
30745 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
30746 fsync(conchFile->h);
30747 /* If we created a new conch file (not just updated the contents of a
30748 ** valid conch file), try to match the permissions of the database
30750 if( rc==SQLITE_OK && createConch ){
30751 struct stat buf;
30752 int err = osFstat(pFile->h, &buf);
30753 if( err==0 ){
30754 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
30755 S_IROTH|S_IWOTH);
30756 /* try to match the database file R/W permissions, ignore failure */
30757 #ifndef SQLITE_PROXY_DEBUG
30758 osFchmod(conchFile->h, cmode);
30759 #else
30761 rc = osFchmod(conchFile->h, cmode);
30762 }while( rc==(-1) && errno==EINTR );
30763 if( rc!=0 ){
30764 int code = errno;
30765 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
30766 cmode, code, strerror(code));
30767 } else {
30768 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
30770 }else{
30771 int code = errno;
30772 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
30773 err, code, strerror(code));
30774 #endif
30778 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
30780 end_takeconch:
30781 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
30782 if( rc==SQLITE_OK && pFile->openFlags ){
30783 int fd;
30784 if( pFile->h>=0 ){
30785 robust_close(pFile, pFile->h, __LINE__);
30787 pFile->h = -1;
30788 fd = robust_open(pCtx->dbPath, pFile->openFlags,
30789 SQLITE_DEFAULT_FILE_PERMISSIONS);
30790 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
30791 if( fd>=0 ){
30792 pFile->h = fd;
30793 }else{
30794 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
30795 during locking */
30798 if( rc==SQLITE_OK && !pCtx->lockProxy ){
30799 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
30800 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
30801 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
30802 /* we couldn't create the proxy lock file with the old lock file path
30803 ** so try again via auto-naming
30805 forceNewLockPath = 1;
30806 tryOldLockPath = 0;
30807 continue; /* go back to the do {} while start point, try again */
30810 if( rc==SQLITE_OK ){
30811 /* Need to make a copy of path if we extracted the value
30812 ** from the conch file or the path was allocated on the stack
30814 if( tempLockPath ){
30815 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
30816 if( !pCtx->lockProxyPath ){
30817 rc = SQLITE_NOMEM;
30821 if( rc==SQLITE_OK ){
30822 pCtx->conchHeld = 1;
30824 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
30825 afpLockingContext *afpCtx;
30826 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
30827 afpCtx->dbPath = pCtx->lockProxyPath;
30829 } else {
30830 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
30832 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
30833 rc==SQLITE_OK?"ok":"failed"));
30834 return rc;
30835 } while (1); /* in case we need to retry the :auto: lock file -
30836 ** we should never get here except via the 'continue' call. */
30841 ** If pFile holds a lock on a conch file, then release that lock.
30843 static int proxyReleaseConch(unixFile *pFile){
30844 int rc = SQLITE_OK; /* Subroutine return code */
30845 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
30846 unixFile *conchFile; /* Name of the conch file */
30848 pCtx = (proxyLockingContext *)pFile->lockingContext;
30849 conchFile = pCtx->conchFile;
30850 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
30851 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
30852 getpid()));
30853 if( pCtx->conchHeld>0 ){
30854 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
30856 pCtx->conchHeld = 0;
30857 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
30858 (rc==SQLITE_OK ? "ok" : "failed")));
30859 return rc;
30863 ** Given the name of a database file, compute the name of its conch file.
30864 ** Store the conch filename in memory obtained from sqlite3_malloc().
30865 ** Make *pConchPath point to the new name. Return SQLITE_OK on success
30866 ** or SQLITE_NOMEM if unable to obtain memory.
30868 ** The caller is responsible for ensuring that the allocated memory
30869 ** space is eventually freed.
30871 ** *pConchPath is set to NULL if a memory allocation error occurs.
30873 static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
30874 int i; /* Loop counter */
30875 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
30876 char *conchPath; /* buffer in which to construct conch name */
30878 /* Allocate space for the conch filename and initialize the name to
30879 ** the name of the original database file. */
30880 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
30881 if( conchPath==0 ){
30882 return SQLITE_NOMEM;
30884 memcpy(conchPath, dbPath, len+1);
30886 /* now insert a "." before the last / character */
30887 for( i=(len-1); i>=0; i-- ){
30888 if( conchPath[i]=='/' ){
30889 i++;
30890 break;
30893 conchPath[i]='.';
30894 while ( i<len ){
30895 conchPath[i+1]=dbPath[i];
30896 i++;
30899 /* append the "-conch" suffix to the file */
30900 memcpy(&conchPath[i+1], "-conch", 7);
30901 assert( (int)strlen(conchPath) == len+7 );
30903 return SQLITE_OK;
30907 /* Takes a fully configured proxy locking-style unix file and switches
30908 ** the local lock file path
30910 static int switchLockProxyPath(unixFile *pFile, const char *path) {
30911 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
30912 char *oldPath = pCtx->lockProxyPath;
30913 int rc = SQLITE_OK;
30915 if( pFile->eFileLock!=NO_LOCK ){
30916 return SQLITE_BUSY;
30919 /* nothing to do if the path is NULL, :auto: or matches the existing path */
30920 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
30921 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
30922 return SQLITE_OK;
30923 }else{
30924 unixFile *lockProxy = pCtx->lockProxy;
30925 pCtx->lockProxy=NULL;
30926 pCtx->conchHeld = 0;
30927 if( lockProxy!=NULL ){
30928 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
30929 if( rc ) return rc;
30930 sqlite3_free(lockProxy);
30932 sqlite3_free(oldPath);
30933 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
30936 return rc;
30940 ** pFile is a file that has been opened by a prior xOpen call. dbPath
30941 ** is a string buffer at least MAXPATHLEN+1 characters in size.
30943 ** This routine find the filename associated with pFile and writes it
30944 ** int dbPath.
30946 static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
30947 #if defined(__APPLE__)
30948 if( pFile->pMethod == &afpIoMethods ){
30949 /* afp style keeps a reference to the db path in the filePath field
30950 ** of the struct */
30951 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
30952 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
30953 } else
30954 #endif
30955 if( pFile->pMethod == &dotlockIoMethods ){
30956 /* dot lock style uses the locking context to store the dot lock
30957 ** file path */
30958 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
30959 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
30960 }else{
30961 /* all other styles use the locking context to store the db file path */
30962 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
30963 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
30965 return SQLITE_OK;
30969 ** Takes an already filled in unix file and alters it so all file locking
30970 ** will be performed on the local proxy lock file. The following fields
30971 ** are preserved in the locking context so that they can be restored and
30972 ** the unix structure properly cleaned up at close time:
30973 ** ->lockingContext
30974 ** ->pMethod
30976 static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
30977 proxyLockingContext *pCtx;
30978 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
30979 char *lockPath=NULL;
30980 int rc = SQLITE_OK;
30982 if( pFile->eFileLock!=NO_LOCK ){
30983 return SQLITE_BUSY;
30985 proxyGetDbPathForUnixFile(pFile, dbPath);
30986 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
30987 lockPath=NULL;
30988 }else{
30989 lockPath=(char *)path;
30992 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
30993 (lockPath ? lockPath : ":auto:"), getpid()));
30995 pCtx = sqlite3_malloc( sizeof(*pCtx) );
30996 if( pCtx==0 ){
30997 return SQLITE_NOMEM;
30999 memset(pCtx, 0, sizeof(*pCtx));
31001 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
31002 if( rc==SQLITE_OK ){
31003 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
31004 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
31005 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
31006 ** (c) the file system is read-only, then enable no-locking access.
31007 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
31008 ** that openFlags will have only one of O_RDONLY or O_RDWR.
31010 struct statfs fsInfo;
31011 struct stat conchInfo;
31012 int goLockless = 0;
31014 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
31015 int err = errno;
31016 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
31017 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
31020 if( goLockless ){
31021 pCtx->conchHeld = -1; /* read only FS/ lockless */
31022 rc = SQLITE_OK;
31026 if( rc==SQLITE_OK && lockPath ){
31027 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
31030 if( rc==SQLITE_OK ){
31031 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
31032 if( pCtx->dbPath==NULL ){
31033 rc = SQLITE_NOMEM;
31036 if( rc==SQLITE_OK ){
31037 /* all memory is allocated, proxys are created and assigned,
31038 ** switch the locking context and pMethod then return.
31040 pCtx->oldLockingContext = pFile->lockingContext;
31041 pFile->lockingContext = pCtx;
31042 pCtx->pOldMethod = pFile->pMethod;
31043 pFile->pMethod = &proxyIoMethods;
31044 }else{
31045 if( pCtx->conchFile ){
31046 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
31047 sqlite3_free(pCtx->conchFile);
31049 sqlite3DbFree(0, pCtx->lockProxyPath);
31050 sqlite3_free(pCtx->conchFilePath);
31051 sqlite3_free(pCtx);
31053 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
31054 (rc==SQLITE_OK ? "ok" : "failed")));
31055 return rc;
31060 ** This routine handles sqlite3_file_control() calls that are specific
31061 ** to proxy locking.
31063 static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
31064 switch( op ){
31065 case SQLITE_GET_LOCKPROXYFILE: {
31066 unixFile *pFile = (unixFile*)id;
31067 if( pFile->pMethod == &proxyIoMethods ){
31068 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
31069 proxyTakeConch(pFile);
31070 if( pCtx->lockProxyPath ){
31071 *(const char **)pArg = pCtx->lockProxyPath;
31072 }else{
31073 *(const char **)pArg = ":auto: (not held)";
31075 } else {
31076 *(const char **)pArg = NULL;
31078 return SQLITE_OK;
31080 case SQLITE_SET_LOCKPROXYFILE: {
31081 unixFile *pFile = (unixFile*)id;
31082 int rc = SQLITE_OK;
31083 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
31084 if( pArg==NULL || (const char *)pArg==0 ){
31085 if( isProxyStyle ){
31086 /* turn off proxy locking - not supported */
31087 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
31088 }else{
31089 /* turn off proxy locking - already off - NOOP */
31090 rc = SQLITE_OK;
31092 }else{
31093 const char *proxyPath = (const char *)pArg;
31094 if( isProxyStyle ){
31095 proxyLockingContext *pCtx =
31096 (proxyLockingContext*)pFile->lockingContext;
31097 if( !strcmp(pArg, ":auto:")
31098 || (pCtx->lockProxyPath &&
31099 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
31101 rc = SQLITE_OK;
31102 }else{
31103 rc = switchLockProxyPath(pFile, proxyPath);
31105 }else{
31106 /* turn on proxy file locking */
31107 rc = proxyTransformUnixFile(pFile, proxyPath);
31110 return rc;
31112 default: {
31113 assert( 0 ); /* The call assures that only valid opcodes are sent */
31116 /*NOTREACHED*/
31117 return SQLITE_ERROR;
31121 ** Within this division (the proxying locking implementation) the procedures
31122 ** above this point are all utilities. The lock-related methods of the
31123 ** proxy-locking sqlite3_io_method object follow.
31128 ** This routine checks if there is a RESERVED lock held on the specified
31129 ** file by this or any other process. If such a lock is held, set *pResOut
31130 ** to a non-zero value otherwise *pResOut is set to zero. The return value
31131 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
31133 static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
31134 unixFile *pFile = (unixFile*)id;
31135 int rc = proxyTakeConch(pFile);
31136 if( rc==SQLITE_OK ){
31137 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
31138 if( pCtx->conchHeld>0 ){
31139 unixFile *proxy = pCtx->lockProxy;
31140 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
31141 }else{ /* conchHeld < 0 is lockless */
31142 pResOut=0;
31145 return rc;
31149 ** Lock the file with the lock specified by parameter eFileLock - one
31150 ** of the following:
31152 ** (1) SHARED_LOCK
31153 ** (2) RESERVED_LOCK
31154 ** (3) PENDING_LOCK
31155 ** (4) EXCLUSIVE_LOCK
31157 ** Sometimes when requesting one lock state, additional lock states
31158 ** are inserted in between. The locking might fail on one of the later
31159 ** transitions leaving the lock state different from what it started but
31160 ** still short of its goal. The following chart shows the allowed
31161 ** transitions and the inserted intermediate states:
31163 ** UNLOCKED -> SHARED
31164 ** SHARED -> RESERVED
31165 ** SHARED -> (PENDING) -> EXCLUSIVE
31166 ** RESERVED -> (PENDING) -> EXCLUSIVE
31167 ** PENDING -> EXCLUSIVE
31169 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
31170 ** routine to lower a locking level.
31172 static int proxyLock(sqlite3_file *id, int eFileLock) {
31173 unixFile *pFile = (unixFile*)id;
31174 int rc = proxyTakeConch(pFile);
31175 if( rc==SQLITE_OK ){
31176 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
31177 if( pCtx->conchHeld>0 ){
31178 unixFile *proxy = pCtx->lockProxy;
31179 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
31180 pFile->eFileLock = proxy->eFileLock;
31181 }else{
31182 /* conchHeld < 0 is lockless */
31185 return rc;
31190 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
31191 ** must be either NO_LOCK or SHARED_LOCK.
31193 ** If the locking level of the file descriptor is already at or below
31194 ** the requested locking level, this routine is a no-op.
31196 static int proxyUnlock(sqlite3_file *id, int eFileLock) {
31197 unixFile *pFile = (unixFile*)id;
31198 int rc = proxyTakeConch(pFile);
31199 if( rc==SQLITE_OK ){
31200 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
31201 if( pCtx->conchHeld>0 ){
31202 unixFile *proxy = pCtx->lockProxy;
31203 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
31204 pFile->eFileLock = proxy->eFileLock;
31205 }else{
31206 /* conchHeld < 0 is lockless */
31209 return rc;
31213 ** Close a file that uses proxy locks.
31215 static int proxyClose(sqlite3_file *id) {
31216 if( id ){
31217 unixFile *pFile = (unixFile*)id;
31218 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
31219 unixFile *lockProxy = pCtx->lockProxy;
31220 unixFile *conchFile = pCtx->conchFile;
31221 int rc = SQLITE_OK;
31223 if( lockProxy ){
31224 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
31225 if( rc ) return rc;
31226 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
31227 if( rc ) return rc;
31228 sqlite3_free(lockProxy);
31229 pCtx->lockProxy = 0;
31231 if( conchFile ){
31232 if( pCtx->conchHeld ){
31233 rc = proxyReleaseConch(pFile);
31234 if( rc ) return rc;
31236 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
31237 if( rc ) return rc;
31238 sqlite3_free(conchFile);
31240 sqlite3DbFree(0, pCtx->lockProxyPath);
31241 sqlite3_free(pCtx->conchFilePath);
31242 sqlite3DbFree(0, pCtx->dbPath);
31243 /* restore the original locking context and pMethod then close it */
31244 pFile->lockingContext = pCtx->oldLockingContext;
31245 pFile->pMethod = pCtx->pOldMethod;
31246 sqlite3_free(pCtx);
31247 return pFile->pMethod->xClose(id);
31249 return SQLITE_OK;
31254 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
31256 ** The proxy locking style is intended for use with AFP filesystems.
31257 ** And since AFP is only supported on MacOSX, the proxy locking is also
31258 ** restricted to MacOSX.
31261 ******************* End of the proxy lock implementation **********************
31262 ******************************************************************************/
31265 ** Initialize the operating system interface.
31267 ** This routine registers all VFS implementations for unix-like operating
31268 ** systems. This routine, and the sqlite3_os_end() routine that follows,
31269 ** should be the only routines in this file that are visible from other
31270 ** files.
31272 ** This routine is called once during SQLite initialization and by a
31273 ** single thread. The memory allocation and mutex subsystems have not
31274 ** necessarily been initialized when this routine is called, and so they
31275 ** should not be used.
31277 SQLITE_API int sqlite3_os_init(void){
31279 ** The following macro defines an initializer for an sqlite3_vfs object.
31280 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
31281 ** to the "finder" function. (pAppData is a pointer to a pointer because
31282 ** silly C90 rules prohibit a void* from being cast to a function pointer
31283 ** and so we have to go through the intermediate pointer to avoid problems
31284 ** when compiling with -pedantic-errors on GCC.)
31286 ** The FINDER parameter to this macro is the name of the pointer to the
31287 ** finder-function. The finder-function returns a pointer to the
31288 ** sqlite_io_methods object that implements the desired locking
31289 ** behaviors. See the division above that contains the IOMETHODS
31290 ** macro for addition information on finder-functions.
31292 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
31293 ** object. But the "autolockIoFinder" available on MacOSX does a little
31294 ** more than that; it looks at the filesystem type that hosts the
31295 ** database file and tries to choose an locking method appropriate for
31296 ** that filesystem time.
31298 #define UNIXVFS(VFSNAME, FINDER) { \
31299 3, /* iVersion */ \
31300 sizeof(unixFile), /* szOsFile */ \
31301 MAX_PATHNAME, /* mxPathname */ \
31302 0, /* pNext */ \
31303 VFSNAME, /* zName */ \
31304 (void*)&FINDER, /* pAppData */ \
31305 unixOpen, /* xOpen */ \
31306 unixDelete, /* xDelete */ \
31307 unixAccess, /* xAccess */ \
31308 unixFullPathname, /* xFullPathname */ \
31309 unixDlOpen, /* xDlOpen */ \
31310 unixDlError, /* xDlError */ \
31311 unixDlSym, /* xDlSym */ \
31312 unixDlClose, /* xDlClose */ \
31313 unixRandomness, /* xRandomness */ \
31314 unixSleep, /* xSleep */ \
31315 unixCurrentTime, /* xCurrentTime */ \
31316 unixGetLastError, /* xGetLastError */ \
31317 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
31318 unixSetSystemCall, /* xSetSystemCall */ \
31319 unixGetSystemCall, /* xGetSystemCall */ \
31320 unixNextSystemCall, /* xNextSystemCall */ \
31324 ** All default VFSes for unix are contained in the following array.
31326 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
31327 ** by the SQLite core when the VFS is registered. So the following
31328 ** array cannot be const.
31330 static sqlite3_vfs aVfs[] = {
31331 #if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
31332 UNIXVFS("unix", autolockIoFinder ),
31333 #else
31334 UNIXVFS("unix", posixIoFinder ),
31335 #endif
31336 UNIXVFS("unix-none", nolockIoFinder ),
31337 UNIXVFS("unix-dotfile", dotlockIoFinder ),
31338 UNIXVFS("unix-excl", posixIoFinder ),
31339 #if OS_VXWORKS
31340 UNIXVFS("unix-namedsem", semIoFinder ),
31341 #endif
31342 #if SQLITE_ENABLE_LOCKING_STYLE
31343 UNIXVFS("unix-posix", posixIoFinder ),
31344 #if !OS_VXWORKS
31345 UNIXVFS("unix-flock", flockIoFinder ),
31346 #endif
31347 #endif
31348 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
31349 UNIXVFS("unix-afp", afpIoFinder ),
31350 UNIXVFS("unix-nfs", nfsIoFinder ),
31351 UNIXVFS("unix-proxy", proxyIoFinder ),
31352 #endif
31354 unsigned int i; /* Loop counter */
31356 /* Double-check that the aSyscall[] array has been constructed
31357 ** correctly. See ticket [bb3a86e890c8e96ab] */
31358 assert( ArraySize(aSyscall)==18 );
31360 /* Register all VFSes defined in the aVfs[] array */
31361 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
31362 sqlite3_vfs_register(&aVfs[i], i==0);
31364 return SQLITE_OK;
31368 ** Shutdown the operating system interface.
31370 ** Some operating systems might need to do some cleanup in this routine,
31371 ** to release dynamically allocated objects. But not on unix.
31372 ** This routine is a no-op for unix.
31374 SQLITE_API int sqlite3_os_end(void){
31375 return SQLITE_OK;
31378 #endif /* SQLITE_OS_UNIX */
31380 /************** End of os_unix.c *********************************************/
31381 /************** Begin file os_win.c ******************************************/
31383 ** 2004 May 22
31385 ** The author disclaims copyright to this source code. In place of
31386 ** a legal notice, here is a blessing:
31388 ** May you do good and not evil.
31389 ** May you find forgiveness for yourself and forgive others.
31390 ** May you share freely, never taking more than you give.
31392 ******************************************************************************
31394 ** This file contains code that is specific to windows.
31396 #if SQLITE_OS_WIN /* This file is used for windows only */
31400 ** A Note About Memory Allocation:
31402 ** This driver uses malloc()/free() directly rather than going through
31403 ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free(). Those wrappers
31404 ** are designed for use on embedded systems where memory is scarce and
31405 ** malloc failures happen frequently. Win32 does not typically run on
31406 ** embedded systems, and when it does the developers normally have bigger
31407 ** problems to worry about than running out of memory. So there is not
31408 ** a compelling need to use the wrappers.
31410 ** But there is a good reason to not use the wrappers. If we use the
31411 ** wrappers then we will get simulated malloc() failures within this
31412 ** driver. And that causes all kinds of problems for our tests. We
31413 ** could enhance SQLite to deal with simulated malloc failures within
31414 ** the OS driver, but the code to deal with those failure would not
31415 ** be exercised on Linux (which does not need to malloc() in the driver)
31416 ** and so we would have difficulty writing coverage tests for that
31417 ** code. Better to leave the code out, we think.
31419 ** The point of this discussion is as follows: When creating a new
31420 ** OS layer for an embedded system, if you use this file as an example,
31421 ** avoid the use of malloc()/free(). Those routines work ok on windows
31422 ** desktops but not so well in embedded systems.
31425 #include <winbase.h>
31427 #ifdef __CYGWIN__
31428 # include <sys/cygwin.h>
31429 #endif
31432 ** Macros used to determine whether or not to use threads.
31434 #if defined(THREADSAFE) && THREADSAFE
31435 # define SQLITE_W32_THREADS 1
31436 #endif
31439 ** Include code that is common to all os_*.c files
31441 /************** Include os_common.h in the middle of os_win.c ****************/
31442 /************** Begin file os_common.h ***************************************/
31444 ** 2004 May 22
31446 ** The author disclaims copyright to this source code. In place of
31447 ** a legal notice, here is a blessing:
31449 ** May you do good and not evil.
31450 ** May you find forgiveness for yourself and forgive others.
31451 ** May you share freely, never taking more than you give.
31453 ******************************************************************************
31455 ** This file contains macros and a little bit of code that is common to
31456 ** all of the platform-specific files (os_*.c) and is #included into those
31457 ** files.
31459 ** This file should be #included by the os_*.c files only. It is not a
31460 ** general purpose header file.
31462 #ifndef _OS_COMMON_H_
31463 #define _OS_COMMON_H_
31466 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
31467 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
31468 ** switch. The following code should catch this problem at compile-time.
31470 #ifdef MEMORY_DEBUG
31471 # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
31472 #endif
31474 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
31475 # ifndef SQLITE_DEBUG_OS_TRACE
31476 # define SQLITE_DEBUG_OS_TRACE 0
31477 # endif
31478 int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
31479 # define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
31480 #else
31481 # define OSTRACE(X)
31482 #endif
31485 ** Macros for performance tracing. Normally turned off. Only works
31486 ** on i486 hardware.
31488 #ifdef SQLITE_PERFORMANCE_TRACE
31491 ** hwtime.h contains inline assembler code for implementing
31492 ** high-performance timing routines.
31494 /************** Include hwtime.h in the middle of os_common.h ****************/
31495 /************** Begin file hwtime.h ******************************************/
31497 ** 2008 May 27
31499 ** The author disclaims copyright to this source code. In place of
31500 ** a legal notice, here is a blessing:
31502 ** May you do good and not evil.
31503 ** May you find forgiveness for yourself and forgive others.
31504 ** May you share freely, never taking more than you give.
31506 ******************************************************************************
31508 ** This file contains inline asm code for retrieving "high-performance"
31509 ** counters for x86 class CPUs.
31511 #ifndef _HWTIME_H_
31512 #define _HWTIME_H_
31515 ** The following routine only works on pentium-class (or newer) processors.
31516 ** It uses the RDTSC opcode to read the cycle count value out of the
31517 ** processor and returns that value. This can be used for high-res
31518 ** profiling.
31520 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
31521 (defined(i386) || defined(__i386__) || defined(_M_IX86))
31523 #if defined(__GNUC__)
31525 __inline__ sqlite_uint64 sqlite3Hwtime(void){
31526 unsigned int lo, hi;
31527 __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
31528 return (sqlite_uint64)hi << 32 | lo;
31531 #elif defined(_MSC_VER)
31533 __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
31534 __asm {
31535 rdtsc
31536 ret ; return value at EDX:EAX
31540 #endif
31542 #elif (defined(__GNUC__) && defined(__x86_64__))
31544 __inline__ sqlite_uint64 sqlite3Hwtime(void){
31545 unsigned long val;
31546 __asm__ __volatile__ ("rdtsc" : "=A" (val));
31547 return val;
31550 #elif (defined(__GNUC__) && defined(__ppc__))
31552 __inline__ sqlite_uint64 sqlite3Hwtime(void){
31553 unsigned long long retval;
31554 unsigned long junk;
31555 __asm__ __volatile__ ("\n\
31556 1: mftbu %1\n\
31557 mftb %L0\n\
31558 mftbu %0\n\
31559 cmpw %0,%1\n\
31560 bne 1b"
31561 : "=r" (retval), "=r" (junk));
31562 return retval;
31565 #else
31567 #error Need implementation of sqlite3Hwtime() for your platform.
31570 ** To compile without implementing sqlite3Hwtime() for your platform,
31571 ** you can remove the above #error and use the following
31572 ** stub function. You will lose timing support for many
31573 ** of the debugging and testing utilities, but it should at
31574 ** least compile and run.
31576 SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
31578 #endif
31580 #endif /* !defined(_HWTIME_H_) */
31582 /************** End of hwtime.h **********************************************/
31583 /************** Continuing where we left off in os_common.h ******************/
31585 static sqlite_uint64 g_start;
31586 static sqlite_uint64 g_elapsed;
31587 #define TIMER_START g_start=sqlite3Hwtime()
31588 #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
31589 #define TIMER_ELAPSED g_elapsed
31590 #else
31591 #define TIMER_START
31592 #define TIMER_END
31593 #define TIMER_ELAPSED ((sqlite_uint64)0)
31594 #endif
31597 ** If we compile with the SQLITE_TEST macro set, then the following block
31598 ** of code will give us the ability to simulate a disk I/O error. This
31599 ** is used for testing the I/O recovery logic.
31601 #ifdef SQLITE_TEST
31602 SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
31603 SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
31604 SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
31605 SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
31606 SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
31607 SQLITE_API int sqlite3_diskfull_pending = 0;
31608 SQLITE_API int sqlite3_diskfull = 0;
31609 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
31610 #define SimulateIOError(CODE) \
31611 if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
31612 || sqlite3_io_error_pending-- == 1 ) \
31613 { local_ioerr(); CODE; }
31614 static void local_ioerr(){
31615 IOTRACE(("IOERR\n"));
31616 sqlite3_io_error_hit++;
31617 if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
31619 #define SimulateDiskfullError(CODE) \
31620 if( sqlite3_diskfull_pending ){ \
31621 if( sqlite3_diskfull_pending == 1 ){ \
31622 local_ioerr(); \
31623 sqlite3_diskfull = 1; \
31624 sqlite3_io_error_hit = 1; \
31625 CODE; \
31626 }else{ \
31627 sqlite3_diskfull_pending--; \
31630 #else
31631 #define SimulateIOErrorBenign(X)
31632 #define SimulateIOError(A)
31633 #define SimulateDiskfullError(A)
31634 #endif
31637 ** When testing, keep a count of the number of open files.
31639 #ifdef SQLITE_TEST
31640 SQLITE_API int sqlite3_open_file_count = 0;
31641 #define OpenCounter(X) sqlite3_open_file_count+=(X)
31642 #else
31643 #define OpenCounter(X)
31644 #endif
31646 #endif /* !defined(_OS_COMMON_H_) */
31648 /************** End of os_common.h *******************************************/
31649 /************** Continuing where we left off in os_win.c *********************/
31652 ** Some microsoft compilers lack this definition.
31654 #ifndef INVALID_FILE_ATTRIBUTES
31655 # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
31656 #endif
31659 ** Determine if we are dealing with WindowsCE - which has a much
31660 ** reduced API.
31662 #if SQLITE_OS_WINCE
31663 # define AreFileApisANSI() 1
31664 # define FormatMessageW(a,b,c,d,e,f,g) 0
31665 #endif
31667 /* Forward references */
31668 typedef struct winShm winShm; /* A connection to shared-memory */
31669 typedef struct winShmNode winShmNode; /* A region of shared-memory */
31672 ** WinCE lacks native support for file locking so we have to fake it
31673 ** with some code of our own.
31675 #if SQLITE_OS_WINCE
31676 typedef struct winceLock {
31677 int nReaders; /* Number of reader locks obtained */
31678 BOOL bPending; /* Indicates a pending lock has been obtained */
31679 BOOL bReserved; /* Indicates a reserved lock has been obtained */
31680 BOOL bExclusive; /* Indicates an exclusive lock has been obtained */
31681 } winceLock;
31682 #endif
31685 ** The winFile structure is a subclass of sqlite3_file* specific to the win32
31686 ** portability layer.
31688 typedef struct winFile winFile;
31689 struct winFile {
31690 const sqlite3_io_methods *pMethod; /*** Must be first ***/
31691 sqlite3_vfs *pVfs; /* The VFS used to open this file */
31692 HANDLE h; /* Handle for accessing the file */
31693 u8 locktype; /* Type of lock currently held on this file */
31694 short sharedLockByte; /* Randomly chosen byte used as a shared lock */
31695 u8 bPersistWal; /* True to persist WAL files */
31696 DWORD lastErrno; /* The Windows errno from the last I/O error */
31697 DWORD sectorSize; /* Sector size of the device file is on */
31698 winShm *pShm; /* Instance of shared memory on this file */
31699 const char *zPath; /* Full pathname of this file */
31700 int szChunk; /* Chunk size configured by FCNTL_CHUNK_SIZE */
31701 #if SQLITE_OS_WINCE
31702 WCHAR *zDeleteOnClose; /* Name of file to delete when closing */
31703 HANDLE hMutex; /* Mutex used to control access to shared lock */
31704 HANDLE hShared; /* Shared memory segment used for locking */
31705 winceLock local; /* Locks obtained by this instance of winFile */
31706 winceLock *shared; /* Global shared lock memory for the file */
31707 #endif
31711 * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
31712 * various Win32 API heap functions instead of our own.
31714 #ifdef SQLITE_WIN32_MALLOC
31716 * The initial size of the Win32-specific heap. This value may be zero.
31718 #ifndef SQLITE_WIN32_HEAP_INIT_SIZE
31719 # define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_DEFAULT_CACHE_SIZE) * \
31720 (SQLITE_DEFAULT_PAGE_SIZE) + 4194304)
31721 #endif
31724 * The maximum size of the Win32-specific heap. This value may be zero.
31726 #ifndef SQLITE_WIN32_HEAP_MAX_SIZE
31727 # define SQLITE_WIN32_HEAP_MAX_SIZE (0)
31728 #endif
31731 * The extra flags to use in calls to the Win32 heap APIs. This value may be
31732 * zero for the default behavior.
31734 #ifndef SQLITE_WIN32_HEAP_FLAGS
31735 # define SQLITE_WIN32_HEAP_FLAGS (0)
31736 #endif
31739 ** The winMemData structure stores information required by the Win32-specific
31740 ** sqlite3_mem_methods implementation.
31742 typedef struct winMemData winMemData;
31743 struct winMemData {
31744 #ifndef NDEBUG
31745 u32 magic; /* Magic number to detect structure corruption. */
31746 #endif
31747 HANDLE hHeap; /* The handle to our heap. */
31748 BOOL bOwned; /* Do we own the heap (i.e. destroy it on shutdown)? */
31751 #ifndef NDEBUG
31752 #define WINMEM_MAGIC 0x42b2830b
31753 #endif
31755 static struct winMemData win_mem_data = {
31756 #ifndef NDEBUG
31757 WINMEM_MAGIC,
31758 #endif
31759 NULL, FALSE
31762 #ifndef NDEBUG
31763 #define winMemAssertMagic() assert( win_mem_data.magic==WINMEM_MAGIC )
31764 #else
31765 #define winMemAssertMagic()
31766 #endif
31768 #define winMemGetHeap() win_mem_data.hHeap
31770 static void *winMemMalloc(int nBytes);
31771 static void winMemFree(void *pPrior);
31772 static void *winMemRealloc(void *pPrior, int nBytes);
31773 static int winMemSize(void *p);
31774 static int winMemRoundup(int n);
31775 static int winMemInit(void *pAppData);
31776 static void winMemShutdown(void *pAppData);
31778 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
31779 #endif /* SQLITE_WIN32_MALLOC */
31782 ** Forward prototypes.
31784 static int getSectorSize(
31785 sqlite3_vfs *pVfs,
31786 const char *zRelative /* UTF-8 file name */
31790 ** The following variable is (normally) set once and never changes
31791 ** thereafter. It records whether the operating system is Win95
31792 ** or WinNT.
31794 ** 0: Operating system unknown.
31795 ** 1: Operating system is Win95.
31796 ** 2: Operating system is WinNT.
31798 ** In order to facilitate testing on a WinNT system, the test fixture
31799 ** can manually set this value to 1 to emulate Win98 behavior.
31801 #ifdef SQLITE_TEST
31802 SQLITE_API int sqlite3_os_type = 0;
31803 #else
31804 static int sqlite3_os_type = 0;
31805 #endif
31808 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
31809 ** or WinCE. Return false (zero) for Win95, Win98, or WinME.
31811 ** Here is an interesting observation: Win95, Win98, and WinME lack
31812 ** the LockFileEx() API. But we can still statically link against that
31813 ** API as long as we don't call it when running Win95/98/ME. A call to
31814 ** this routine is used to determine if the host is Win95/98/ME or
31815 ** WinNT/2K/XP so that we will know whether or not we can safely call
31816 ** the LockFileEx() API.
31818 #if SQLITE_OS_WINCE
31819 # define isNT() (1)
31820 #else
31821 static int isNT(void){
31822 if( sqlite3_os_type==0 ){
31823 OSVERSIONINFO sInfo;
31824 sInfo.dwOSVersionInfoSize = sizeof(sInfo);
31825 GetVersionEx(&sInfo);
31826 sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
31828 return sqlite3_os_type==2;
31830 #endif /* SQLITE_OS_WINCE */
31832 #ifdef SQLITE_WIN32_MALLOC
31834 ** Allocate nBytes of memory.
31836 static void *winMemMalloc(int nBytes){
31837 HANDLE hHeap;
31838 void *p;
31840 winMemAssertMagic();
31841 hHeap = winMemGetHeap();
31842 assert( hHeap!=0 );
31843 assert( hHeap!=INVALID_HANDLE_VALUE );
31844 #ifdef SQLITE_WIN32_MALLOC_VALIDATE
31845 assert ( HeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
31846 #endif
31847 assert( nBytes>=0 );
31848 p = HeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
31849 if( !p ){
31850 sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%d), heap=%p",
31851 nBytes, GetLastError(), (void*)hHeap);
31853 return p;
31857 ** Free memory.
31859 static void winMemFree(void *pPrior){
31860 HANDLE hHeap;
31862 winMemAssertMagic();
31863 hHeap = winMemGetHeap();
31864 assert( hHeap!=0 );
31865 assert( hHeap!=INVALID_HANDLE_VALUE );
31866 #ifdef SQLITE_WIN32_MALLOC_VALIDATE
31867 assert ( HeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
31868 #endif
31869 if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
31870 if( !HeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
31871 sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%d), heap=%p",
31872 pPrior, GetLastError(), (void*)hHeap);
31877 ** Change the size of an existing memory allocation
31879 static void *winMemRealloc(void *pPrior, int nBytes){
31880 HANDLE hHeap;
31881 void *p;
31883 winMemAssertMagic();
31884 hHeap = winMemGetHeap();
31885 assert( hHeap!=0 );
31886 assert( hHeap!=INVALID_HANDLE_VALUE );
31887 #ifdef SQLITE_WIN32_MALLOC_VALIDATE
31888 assert ( HeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
31889 #endif
31890 assert( nBytes>=0 );
31891 if( !pPrior ){
31892 p = HeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
31893 }else{
31894 p = HeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
31896 if( !p ){
31897 sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%d), heap=%p",
31898 pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, GetLastError(),
31899 (void*)hHeap);
31901 return p;
31905 ** Return the size of an outstanding allocation, in bytes.
31907 static int winMemSize(void *p){
31908 HANDLE hHeap;
31909 SIZE_T n;
31911 winMemAssertMagic();
31912 hHeap = winMemGetHeap();
31913 assert( hHeap!=0 );
31914 assert( hHeap!=INVALID_HANDLE_VALUE );
31915 #ifdef SQLITE_WIN32_MALLOC_VALIDATE
31916 assert ( HeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
31917 #endif
31918 if( !p ) return 0;
31919 n = HeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
31920 if( n==(SIZE_T)-1 ){
31921 sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%d), heap=%p",
31922 p, GetLastError(), (void*)hHeap);
31923 return 0;
31925 return (int)n;
31929 ** Round up a request size to the next valid allocation size.
31931 static int winMemRoundup(int n){
31932 return n;
31936 ** Initialize this module.
31938 static int winMemInit(void *pAppData){
31939 winMemData *pWinMemData = (winMemData *)pAppData;
31941 if( !pWinMemData ) return SQLITE_ERROR;
31942 assert( pWinMemData->magic==WINMEM_MAGIC );
31943 if( !pWinMemData->hHeap ){
31944 pWinMemData->hHeap = HeapCreate(SQLITE_WIN32_HEAP_FLAGS,
31945 SQLITE_WIN32_HEAP_INIT_SIZE,
31946 SQLITE_WIN32_HEAP_MAX_SIZE);
31947 if( !pWinMemData->hHeap ){
31948 sqlite3_log(SQLITE_NOMEM,
31949 "failed to HeapCreate (%d), flags=%u, initSize=%u, maxSize=%u",
31950 GetLastError(), SQLITE_WIN32_HEAP_FLAGS, SQLITE_WIN32_HEAP_INIT_SIZE,
31951 SQLITE_WIN32_HEAP_MAX_SIZE);
31952 return SQLITE_NOMEM;
31954 pWinMemData->bOwned = TRUE;
31956 assert( pWinMemData->hHeap!=0 );
31957 assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
31958 #ifdef SQLITE_WIN32_MALLOC_VALIDATE
31959 assert( HeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
31960 #endif
31961 return SQLITE_OK;
31965 ** Deinitialize this module.
31967 static void winMemShutdown(void *pAppData){
31968 winMemData *pWinMemData = (winMemData *)pAppData;
31970 if( !pWinMemData ) return;
31971 if( pWinMemData->hHeap ){
31972 assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
31973 #ifdef SQLITE_WIN32_MALLOC_VALIDATE
31974 assert( HeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
31975 #endif
31976 if( pWinMemData->bOwned ){
31977 if( !HeapDestroy(pWinMemData->hHeap) ){
31978 sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%d), heap=%p",
31979 GetLastError(), (void*)pWinMemData->hHeap);
31981 pWinMemData->bOwned = FALSE;
31983 pWinMemData->hHeap = NULL;
31988 ** Populate the low-level memory allocation function pointers in
31989 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
31990 ** arguments specify the block of memory to manage.
31992 ** This routine is only called by sqlite3_config(), and therefore
31993 ** is not required to be threadsafe (it is not).
31995 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
31996 static const sqlite3_mem_methods winMemMethods = {
31997 winMemMalloc,
31998 winMemFree,
31999 winMemRealloc,
32000 winMemSize,
32001 winMemRoundup,
32002 winMemInit,
32003 winMemShutdown,
32004 &win_mem_data
32006 return &winMemMethods;
32009 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
32010 sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
32012 #endif /* SQLITE_WIN32_MALLOC */
32015 ** Convert a UTF-8 string to microsoft unicode (UTF-16?).
32017 ** Space to hold the returned string is obtained from malloc.
32019 static WCHAR *utf8ToUnicode(const char *zFilename){
32020 int nChar;
32021 WCHAR *zWideFilename;
32023 nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
32024 zWideFilename = malloc( nChar*sizeof(zWideFilename[0]) );
32025 if( zWideFilename==0 ){
32026 return 0;
32028 nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename, nChar);
32029 if( nChar==0 ){
32030 free(zWideFilename);
32031 zWideFilename = 0;
32033 return zWideFilename;
32037 ** Convert microsoft unicode to UTF-8. Space to hold the returned string is
32038 ** obtained from malloc().
32040 static char *unicodeToUtf8(const WCHAR *zWideFilename){
32041 int nByte;
32042 char *zFilename;
32044 nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
32045 zFilename = malloc( nByte );
32046 if( zFilename==0 ){
32047 return 0;
32049 nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
32050 0, 0);
32051 if( nByte == 0 ){
32052 free(zFilename);
32053 zFilename = 0;
32055 return zFilename;
32059 ** Convert an ansi string to microsoft unicode, based on the
32060 ** current codepage settings for file apis.
32062 ** Space to hold the returned string is obtained
32063 ** from malloc.
32065 static WCHAR *mbcsToUnicode(const char *zFilename){
32066 int nByte;
32067 WCHAR *zMbcsFilename;
32068 int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
32070 nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, NULL,0)*sizeof(WCHAR);
32071 zMbcsFilename = malloc( nByte*sizeof(zMbcsFilename[0]) );
32072 if( zMbcsFilename==0 ){
32073 return 0;
32075 nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename, nByte);
32076 if( nByte==0 ){
32077 free(zMbcsFilename);
32078 zMbcsFilename = 0;
32080 return zMbcsFilename;
32084 ** Convert microsoft unicode to multibyte character string, based on the
32085 ** user's Ansi codepage.
32087 ** Space to hold the returned string is obtained from
32088 ** malloc().
32090 static char *unicodeToMbcs(const WCHAR *zWideFilename){
32091 int nByte;
32092 char *zFilename;
32093 int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
32095 nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
32096 zFilename = malloc( nByte );
32097 if( zFilename==0 ){
32098 return 0;
32100 nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename, nByte,
32101 0, 0);
32102 if( nByte == 0 ){
32103 free(zFilename);
32104 zFilename = 0;
32106 return zFilename;
32110 ** Convert multibyte character string to UTF-8. Space to hold the
32111 ** returned string is obtained from malloc().
32113 SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
32114 char *zFilenameUtf8;
32115 WCHAR *zTmpWide;
32117 zTmpWide = mbcsToUnicode(zFilename);
32118 if( zTmpWide==0 ){
32119 return 0;
32121 zFilenameUtf8 = unicodeToUtf8(zTmpWide);
32122 free(zTmpWide);
32123 return zFilenameUtf8;
32127 ** Convert UTF-8 to multibyte character string. Space to hold the
32128 ** returned string is obtained from malloc().
32130 SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zFilename){
32131 char *zFilenameMbcs;
32132 WCHAR *zTmpWide;
32134 zTmpWide = utf8ToUnicode(zFilename);
32135 if( zTmpWide==0 ){
32136 return 0;
32138 zFilenameMbcs = unicodeToMbcs(zTmpWide);
32139 free(zTmpWide);
32140 return zFilenameMbcs;
32145 ** The return value of getLastErrorMsg
32146 ** is zero if the error message fits in the buffer, or non-zero
32147 ** otherwise (if the message was truncated).
32149 static int getLastErrorMsg(int nBuf, char *zBuf){
32150 /* FormatMessage returns 0 on failure. Otherwise it
32151 ** returns the number of TCHARs written to the output
32152 ** buffer, excluding the terminating null char.
32154 DWORD error = GetLastError();
32155 DWORD dwLen = 0;
32156 char *zOut = 0;
32158 if( isNT() ){
32159 WCHAR *zTempWide = NULL;
32160 dwLen = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
32161 NULL,
32162 error,
32164 (LPWSTR) &zTempWide,
32167 if( dwLen > 0 ){
32168 /* allocate a buffer and convert to UTF8 */
32169 zOut = unicodeToUtf8(zTempWide);
32170 /* free the system buffer allocated by FormatMessage */
32171 LocalFree(zTempWide);
32173 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
32174 ** Since the ASCII version of these Windows API do not exist for WINCE,
32175 ** it's important to not reference them for WINCE builds.
32177 #if SQLITE_OS_WINCE==0
32178 }else{
32179 char *zTemp = NULL;
32180 dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
32181 NULL,
32182 error,
32184 (LPSTR) &zTemp,
32187 if( dwLen > 0 ){
32188 /* allocate a buffer and convert to UTF8 */
32189 zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
32190 /* free the system buffer allocated by FormatMessage */
32191 LocalFree(zTemp);
32193 #endif
32195 if( 0 == dwLen ){
32196 sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", error, error);
32197 }else{
32198 /* copy a maximum of nBuf chars to output buffer */
32199 sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
32200 /* free the UTF8 buffer */
32201 free(zOut);
32203 return 0;
32208 ** This function - winLogErrorAtLine() - is only ever called via the macro
32209 ** winLogError().
32211 ** This routine is invoked after an error occurs in an OS function.
32212 ** It logs a message using sqlite3_log() containing the current value of
32213 ** error code and, if possible, the human-readable equivalent from
32214 ** FormatMessage.
32216 ** The first argument passed to the macro should be the error code that
32217 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
32218 ** The two subsequent arguments should be the name of the OS function that
32219 ** failed and the the associated file-system path, if any.
32221 #define winLogError(a,b,c) winLogErrorAtLine(a,b,c,__LINE__)
32222 static int winLogErrorAtLine(
32223 int errcode, /* SQLite error code */
32224 const char *zFunc, /* Name of OS function that failed */
32225 const char *zPath, /* File path associated with error */
32226 int iLine /* Source line number where error occurred */
32228 char zMsg[500]; /* Human readable error text */
32229 int i; /* Loop counter */
32230 DWORD iErrno = GetLastError(); /* Error code */
32232 zMsg[0] = 0;
32233 getLastErrorMsg(sizeof(zMsg), zMsg);
32234 assert( errcode!=SQLITE_OK );
32235 if( zPath==0 ) zPath = "";
32236 for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
32237 zMsg[i] = 0;
32238 sqlite3_log(errcode,
32239 "os_win.c:%d: (%d) %s(%s) - %s",
32240 iLine, iErrno, zFunc, zPath, zMsg
32243 return errcode;
32247 ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
32248 ** will be retried following a locking error - probably caused by
32249 ** antivirus software. Also the initial delay before the first retry.
32250 ** The delay increases linearly with each retry.
32252 #ifndef SQLITE_WIN32_IOERR_RETRY
32253 # define SQLITE_WIN32_IOERR_RETRY 10
32254 #endif
32255 #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
32256 # define SQLITE_WIN32_IOERR_RETRY_DELAY 25
32257 #endif
32258 static int win32IoerrRetry = SQLITE_WIN32_IOERR_RETRY;
32259 static int win32IoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
32262 ** If a ReadFile() or WriteFile() error occurs, invoke this routine
32263 ** to see if it should be retried. Return TRUE to retry. Return FALSE
32264 ** to give up with an error.
32266 static int retryIoerr(int *pnRetry){
32267 DWORD e;
32268 if( *pnRetry>=win32IoerrRetry ){
32269 return 0;
32271 e = GetLastError();
32272 if( e==ERROR_ACCESS_DENIED ||
32273 e==ERROR_LOCK_VIOLATION ||
32274 e==ERROR_SHARING_VIOLATION ){
32275 Sleep(win32IoerrRetryDelay*(1+*pnRetry));
32276 ++*pnRetry;
32277 return 1;
32279 return 0;
32283 ** Log a I/O error retry episode.
32285 static void logIoerr(int nRetry){
32286 if( nRetry ){
32287 sqlite3_log(SQLITE_IOERR,
32288 "delayed %dms for lock/sharing conflict",
32289 win32IoerrRetryDelay*nRetry*(nRetry+1)/2
32294 #if SQLITE_OS_WINCE
32295 /*************************************************************************
32296 ** This section contains code for WinCE only.
32299 ** WindowsCE does not have a localtime() function. So create a
32300 ** substitute.
32302 /* #include <time.h> */
32303 struct tm *__cdecl localtime(const time_t *t)
32305 static struct tm y;
32306 FILETIME uTm, lTm;
32307 SYSTEMTIME pTm;
32308 sqlite3_int64 t64;
32309 t64 = *t;
32310 t64 = (t64 + 11644473600)*10000000;
32311 uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
32312 uTm.dwHighDateTime= (DWORD)(t64 >> 32);
32313 FileTimeToLocalFileTime(&uTm,&lTm);
32314 FileTimeToSystemTime(&lTm,&pTm);
32315 y.tm_year = pTm.wYear - 1900;
32316 y.tm_mon = pTm.wMonth - 1;
32317 y.tm_wday = pTm.wDayOfWeek;
32318 y.tm_mday = pTm.wDay;
32319 y.tm_hour = pTm.wHour;
32320 y.tm_min = pTm.wMinute;
32321 y.tm_sec = pTm.wSecond;
32322 return &y;
32325 /* This will never be called, but defined to make the code compile */
32326 #define GetTempPathA(a,b)
32328 #define LockFile(a,b,c,d,e) winceLockFile(&a, b, c, d, e)
32329 #define UnlockFile(a,b,c,d,e) winceUnlockFile(&a, b, c, d, e)
32330 #define LockFileEx(a,b,c,d,e,f) winceLockFileEx(&a, b, c, d, e, f)
32332 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
32335 ** Acquire a lock on the handle h
32337 static void winceMutexAcquire(HANDLE h){
32338 DWORD dwErr;
32339 do {
32340 dwErr = WaitForSingleObject(h, INFINITE);
32341 } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
32344 ** Release a lock acquired by winceMutexAcquire()
32346 #define winceMutexRelease(h) ReleaseMutex(h)
32349 ** Create the mutex and shared memory used for locking in the file
32350 ** descriptor pFile
32352 static BOOL winceCreateLock(const char *zFilename, winFile *pFile){
32353 WCHAR *zTok;
32354 WCHAR *zName = utf8ToUnicode(zFilename);
32355 BOOL bInit = TRUE;
32357 /* Initialize the local lockdata */
32358 ZeroMemory(&pFile->local, sizeof(pFile->local));
32360 /* Replace the backslashes from the filename and lowercase it
32361 ** to derive a mutex name. */
32362 zTok = CharLowerW(zName);
32363 for (;*zTok;zTok++){
32364 if (*zTok == '\\') *zTok = '_';
32367 /* Create/open the named mutex */
32368 pFile->hMutex = CreateMutexW(NULL, FALSE, zName);
32369 if (!pFile->hMutex){
32370 pFile->lastErrno = GetLastError();
32371 winLogError(SQLITE_ERROR, "winceCreateLock1", zFilename);
32372 free(zName);
32373 return FALSE;
32376 /* Acquire the mutex before continuing */
32377 winceMutexAcquire(pFile->hMutex);
32379 /* Since the names of named mutexes, semaphores, file mappings etc are
32380 ** case-sensitive, take advantage of that by uppercasing the mutex name
32381 ** and using that as the shared filemapping name.
32383 CharUpperW(zName);
32384 pFile->hShared = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
32385 PAGE_READWRITE, 0, sizeof(winceLock),
32386 zName);
32388 /* Set a flag that indicates we're the first to create the memory so it
32389 ** must be zero-initialized */
32390 if (GetLastError() == ERROR_ALREADY_EXISTS){
32391 bInit = FALSE;
32394 free(zName);
32396 /* If we succeeded in making the shared memory handle, map it. */
32397 if (pFile->hShared){
32398 pFile->shared = (winceLock*)MapViewOfFile(pFile->hShared,
32399 FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
32400 /* If mapping failed, close the shared memory handle and erase it */
32401 if (!pFile->shared){
32402 pFile->lastErrno = GetLastError();
32403 winLogError(SQLITE_ERROR, "winceCreateLock2", zFilename);
32404 CloseHandle(pFile->hShared);
32405 pFile->hShared = NULL;
32409 /* If shared memory could not be created, then close the mutex and fail */
32410 if (pFile->hShared == NULL){
32411 winceMutexRelease(pFile->hMutex);
32412 CloseHandle(pFile->hMutex);
32413 pFile->hMutex = NULL;
32414 return FALSE;
32417 /* Initialize the shared memory if we're supposed to */
32418 if (bInit) {
32419 ZeroMemory(pFile->shared, sizeof(winceLock));
32422 winceMutexRelease(pFile->hMutex);
32423 return TRUE;
32427 ** Destroy the part of winFile that deals with wince locks
32429 static void winceDestroyLock(winFile *pFile){
32430 if (pFile->hMutex){
32431 /* Acquire the mutex */
32432 winceMutexAcquire(pFile->hMutex);
32434 /* The following blocks should probably assert in debug mode, but they
32435 are to cleanup in case any locks remained open */
32436 if (pFile->local.nReaders){
32437 pFile->shared->nReaders --;
32439 if (pFile->local.bReserved){
32440 pFile->shared->bReserved = FALSE;
32442 if (pFile->local.bPending){
32443 pFile->shared->bPending = FALSE;
32445 if (pFile->local.bExclusive){
32446 pFile->shared->bExclusive = FALSE;
32449 /* De-reference and close our copy of the shared memory handle */
32450 UnmapViewOfFile(pFile->shared);
32451 CloseHandle(pFile->hShared);
32453 /* Done with the mutex */
32454 winceMutexRelease(pFile->hMutex);
32455 CloseHandle(pFile->hMutex);
32456 pFile->hMutex = NULL;
32461 ** An implementation of the LockFile() API of windows for wince
32463 static BOOL winceLockFile(
32464 HANDLE *phFile,
32465 DWORD dwFileOffsetLow,
32466 DWORD dwFileOffsetHigh,
32467 DWORD nNumberOfBytesToLockLow,
32468 DWORD nNumberOfBytesToLockHigh
32470 winFile *pFile = HANDLE_TO_WINFILE(phFile);
32471 BOOL bReturn = FALSE;
32473 UNUSED_PARAMETER(dwFileOffsetHigh);
32474 UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
32476 if (!pFile->hMutex) return TRUE;
32477 winceMutexAcquire(pFile->hMutex);
32479 /* Wanting an exclusive lock? */
32480 if (dwFileOffsetLow == (DWORD)SHARED_FIRST
32481 && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
32482 if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
32483 pFile->shared->bExclusive = TRUE;
32484 pFile->local.bExclusive = TRUE;
32485 bReturn = TRUE;
32489 /* Want a read-only lock? */
32490 else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
32491 nNumberOfBytesToLockLow == 1){
32492 if (pFile->shared->bExclusive == 0){
32493 pFile->local.nReaders ++;
32494 if (pFile->local.nReaders == 1){
32495 pFile->shared->nReaders ++;
32497 bReturn = TRUE;
32501 /* Want a pending lock? */
32502 else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToLockLow == 1){
32503 /* If no pending lock has been acquired, then acquire it */
32504 if (pFile->shared->bPending == 0) {
32505 pFile->shared->bPending = TRUE;
32506 pFile->local.bPending = TRUE;
32507 bReturn = TRUE;
32511 /* Want a reserved lock? */
32512 else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToLockLow == 1){
32513 if (pFile->shared->bReserved == 0) {
32514 pFile->shared->bReserved = TRUE;
32515 pFile->local.bReserved = TRUE;
32516 bReturn = TRUE;
32520 winceMutexRelease(pFile->hMutex);
32521 return bReturn;
32525 ** An implementation of the UnlockFile API of windows for wince
32527 static BOOL winceUnlockFile(
32528 HANDLE *phFile,
32529 DWORD dwFileOffsetLow,
32530 DWORD dwFileOffsetHigh,
32531 DWORD nNumberOfBytesToUnlockLow,
32532 DWORD nNumberOfBytesToUnlockHigh
32534 winFile *pFile = HANDLE_TO_WINFILE(phFile);
32535 BOOL bReturn = FALSE;
32537 UNUSED_PARAMETER(dwFileOffsetHigh);
32538 UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
32540 if (!pFile->hMutex) return TRUE;
32541 winceMutexAcquire(pFile->hMutex);
32543 /* Releasing a reader lock or an exclusive lock */
32544 if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
32545 /* Did we have an exclusive lock? */
32546 if (pFile->local.bExclusive){
32547 assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
32548 pFile->local.bExclusive = FALSE;
32549 pFile->shared->bExclusive = FALSE;
32550 bReturn = TRUE;
32553 /* Did we just have a reader lock? */
32554 else if (pFile->local.nReaders){
32555 assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE || nNumberOfBytesToUnlockLow == 1);
32556 pFile->local.nReaders --;
32557 if (pFile->local.nReaders == 0)
32559 pFile->shared->nReaders --;
32561 bReturn = TRUE;
32565 /* Releasing a pending lock */
32566 else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){
32567 if (pFile->local.bPending){
32568 pFile->local.bPending = FALSE;
32569 pFile->shared->bPending = FALSE;
32570 bReturn = TRUE;
32573 /* Releasing a reserved lock */
32574 else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){
32575 if (pFile->local.bReserved) {
32576 pFile->local.bReserved = FALSE;
32577 pFile->shared->bReserved = FALSE;
32578 bReturn = TRUE;
32582 winceMutexRelease(pFile->hMutex);
32583 return bReturn;
32587 ** An implementation of the LockFileEx() API of windows for wince
32589 static BOOL winceLockFileEx(
32590 HANDLE *phFile,
32591 DWORD dwFlags,
32592 DWORD dwReserved,
32593 DWORD nNumberOfBytesToLockLow,
32594 DWORD nNumberOfBytesToLockHigh,
32595 LPOVERLAPPED lpOverlapped
32597 UNUSED_PARAMETER(dwReserved);
32598 UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
32600 /* If the caller wants a shared read lock, forward this call
32601 ** to winceLockFile */
32602 if (lpOverlapped->Offset == (DWORD)SHARED_FIRST &&
32603 dwFlags == 1 &&
32604 nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
32605 return winceLockFile(phFile, SHARED_FIRST, 0, 1, 0);
32607 return FALSE;
32610 ** End of the special code for wince
32611 *****************************************************************************/
32612 #endif /* SQLITE_OS_WINCE */
32614 /*****************************************************************************
32615 ** The next group of routines implement the I/O methods specified
32616 ** by the sqlite3_io_methods object.
32617 ******************************************************************************/
32620 ** Some microsoft compilers lack this definition.
32622 #ifndef INVALID_SET_FILE_POINTER
32623 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
32624 #endif
32627 ** Move the current position of the file handle passed as the first
32628 ** argument to offset iOffset within the file. If successful, return 0.
32629 ** Otherwise, set pFile->lastErrno and return non-zero.
32631 static int seekWinFile(winFile *pFile, sqlite3_int64 iOffset){
32632 LONG upperBits; /* Most sig. 32 bits of new offset */
32633 LONG lowerBits; /* Least sig. 32 bits of new offset */
32634 DWORD dwRet; /* Value returned by SetFilePointer() */
32636 upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
32637 lowerBits = (LONG)(iOffset & 0xffffffff);
32639 /* API oddity: If successful, SetFilePointer() returns a dword
32640 ** containing the lower 32-bits of the new file-offset. Or, if it fails,
32641 ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
32642 ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
32643 ** whether an error has actually occured, it is also necessary to call
32644 ** GetLastError().
32646 dwRet = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
32647 if( (dwRet==INVALID_SET_FILE_POINTER && GetLastError()!=NO_ERROR) ){
32648 pFile->lastErrno = GetLastError();
32649 winLogError(SQLITE_IOERR_SEEK, "seekWinFile", pFile->zPath);
32650 return 1;
32653 return 0;
32657 ** Close a file.
32659 ** It is reported that an attempt to close a handle might sometimes
32660 ** fail. This is a very unreasonable result, but windows is notorious
32661 ** for being unreasonable so I do not doubt that it might happen. If
32662 ** the close fails, we pause for 100 milliseconds and try again. As
32663 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
32664 ** giving up and returning an error.
32666 #define MX_CLOSE_ATTEMPT 3
32667 static int winClose(sqlite3_file *id){
32668 int rc, cnt = 0;
32669 winFile *pFile = (winFile*)id;
32671 assert( id!=0 );
32672 assert( pFile->pShm==0 );
32673 OSTRACE(("CLOSE %d\n", pFile->h));
32675 rc = CloseHandle(pFile->h);
32676 /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
32677 }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (Sleep(100), 1) );
32678 #if SQLITE_OS_WINCE
32679 #define WINCE_DELETION_ATTEMPTS 3
32680 winceDestroyLock(pFile);
32681 if( pFile->zDeleteOnClose ){
32682 int cnt = 0;
32683 while(
32684 DeleteFileW(pFile->zDeleteOnClose)==0
32685 && GetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
32686 && cnt++ < WINCE_DELETION_ATTEMPTS
32688 Sleep(100); /* Wait a little before trying again */
32690 free(pFile->zDeleteOnClose);
32692 #endif
32693 OSTRACE(("CLOSE %d %s\n", pFile->h, rc ? "ok" : "failed"));
32694 OpenCounter(-1);
32695 return rc ? SQLITE_OK
32696 : winLogError(SQLITE_IOERR_CLOSE, "winClose", pFile->zPath);
32700 ** Read data from a file into a buffer. Return SQLITE_OK if all
32701 ** bytes were read successfully and SQLITE_IOERR if anything goes
32702 ** wrong.
32704 static int winRead(
32705 sqlite3_file *id, /* File to read from */
32706 void *pBuf, /* Write content into this buffer */
32707 int amt, /* Number of bytes to read */
32708 sqlite3_int64 offset /* Begin reading at this offset */
32710 winFile *pFile = (winFile*)id; /* file handle */
32711 DWORD nRead; /* Number of bytes actually read from file */
32712 int nRetry = 0; /* Number of retrys */
32714 assert( id!=0 );
32715 SimulateIOError(return SQLITE_IOERR_READ);
32716 OSTRACE(("READ %d lock=%d\n", pFile->h, pFile->locktype));
32718 if( seekWinFile(pFile, offset) ){
32719 return SQLITE_FULL;
32721 while( !ReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
32722 if( retryIoerr(&nRetry) ) continue;
32723 pFile->lastErrno = GetLastError();
32724 return winLogError(SQLITE_IOERR_READ, "winRead", pFile->zPath);
32726 logIoerr(nRetry);
32727 if( nRead<(DWORD)amt ){
32728 /* Unread parts of the buffer must be zero-filled */
32729 memset(&((char*)pBuf)[nRead], 0, amt-nRead);
32730 return SQLITE_IOERR_SHORT_READ;
32733 return SQLITE_OK;
32737 ** Write data from a buffer into a file. Return SQLITE_OK on success
32738 ** or some other error code on failure.
32740 static int winWrite(
32741 sqlite3_file *id, /* File to write into */
32742 const void *pBuf, /* The bytes to be written */
32743 int amt, /* Number of bytes to write */
32744 sqlite3_int64 offset /* Offset into the file to begin writing at */
32746 int rc; /* True if error has occured, else false */
32747 winFile *pFile = (winFile*)id; /* File handle */
32748 int nRetry = 0; /* Number of retries */
32750 assert( amt>0 );
32751 assert( pFile );
32752 SimulateIOError(return SQLITE_IOERR_WRITE);
32753 SimulateDiskfullError(return SQLITE_FULL);
32755 OSTRACE(("WRITE %d lock=%d\n", pFile->h, pFile->locktype));
32757 rc = seekWinFile(pFile, offset);
32758 if( rc==0 ){
32759 u8 *aRem = (u8 *)pBuf; /* Data yet to be written */
32760 int nRem = amt; /* Number of bytes yet to be written */
32761 DWORD nWrite; /* Bytes written by each WriteFile() call */
32763 while( nRem>0 ){
32764 if( !WriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
32765 if( retryIoerr(&nRetry) ) continue;
32766 break;
32768 if( nWrite<=0 ) break;
32769 aRem += nWrite;
32770 nRem -= nWrite;
32772 if( nRem>0 ){
32773 pFile->lastErrno = GetLastError();
32774 rc = 1;
32778 if( rc ){
32779 if( ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
32780 || ( pFile->lastErrno==ERROR_DISK_FULL )){
32781 return SQLITE_FULL;
32783 return winLogError(SQLITE_IOERR_WRITE, "winWrite", pFile->zPath);
32784 }else{
32785 logIoerr(nRetry);
32787 return SQLITE_OK;
32791 ** Truncate an open file to a specified size
32793 static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
32794 winFile *pFile = (winFile*)id; /* File handle object */
32795 int rc = SQLITE_OK; /* Return code for this function */
32797 assert( pFile );
32799 OSTRACE(("TRUNCATE %d %lld\n", pFile->h, nByte));
32800 SimulateIOError(return SQLITE_IOERR_TRUNCATE);
32802 /* If the user has configured a chunk-size for this file, truncate the
32803 ** file so that it consists of an integer number of chunks (i.e. the
32804 ** actual file size after the operation may be larger than the requested
32805 ** size).
32807 if( pFile->szChunk>0 ){
32808 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
32811 /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
32812 if( seekWinFile(pFile, nByte) ){
32813 rc = winLogError(SQLITE_IOERR_TRUNCATE, "winTruncate1", pFile->zPath);
32814 }else if( 0==SetEndOfFile(pFile->h) ){
32815 pFile->lastErrno = GetLastError();
32816 rc = winLogError(SQLITE_IOERR_TRUNCATE, "winTruncate2", pFile->zPath);
32819 OSTRACE(("TRUNCATE %d %lld %s\n", pFile->h, nByte, rc ? "failed" : "ok"));
32820 return rc;
32823 #ifdef SQLITE_TEST
32825 ** Count the number of fullsyncs and normal syncs. This is used to test
32826 ** that syncs and fullsyncs are occuring at the right times.
32828 SQLITE_API int sqlite3_sync_count = 0;
32829 SQLITE_API int sqlite3_fullsync_count = 0;
32830 #endif
32833 ** Make sure all writes to a particular file are committed to disk.
32835 static int winSync(sqlite3_file *id, int flags){
32836 #ifndef SQLITE_NO_SYNC
32838 ** Used only when SQLITE_NO_SYNC is not defined.
32840 BOOL rc;
32841 #endif
32842 #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
32843 (defined(SQLITE_TEST) && defined(SQLITE_DEBUG))
32845 ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
32846 ** OSTRACE() macros.
32848 winFile *pFile = (winFile*)id;
32849 #else
32850 UNUSED_PARAMETER(id);
32851 #endif
32853 assert( pFile );
32854 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
32855 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
32856 || (flags&0x0F)==SQLITE_SYNC_FULL
32859 OSTRACE(("SYNC %d lock=%d\n", pFile->h, pFile->locktype));
32861 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
32862 ** line is to test that doing so does not cause any problems.
32864 SimulateDiskfullError( return SQLITE_FULL );
32866 #ifndef SQLITE_TEST
32867 UNUSED_PARAMETER(flags);
32868 #else
32869 if( (flags&0x0F)==SQLITE_SYNC_FULL ){
32870 sqlite3_fullsync_count++;
32872 sqlite3_sync_count++;
32873 #endif
32875 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
32876 ** no-op
32878 #ifdef SQLITE_NO_SYNC
32879 return SQLITE_OK;
32880 #else
32881 rc = FlushFileBuffers(pFile->h);
32882 SimulateIOError( rc=FALSE );
32883 if( rc ){
32884 return SQLITE_OK;
32885 }else{
32886 pFile->lastErrno = GetLastError();
32887 return winLogError(SQLITE_IOERR_FSYNC, "winSync", pFile->zPath);
32889 #endif
32893 ** Determine the current size of a file in bytes
32895 static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
32896 DWORD upperBits;
32897 DWORD lowerBits;
32898 winFile *pFile = (winFile*)id;
32899 DWORD error;
32901 assert( id!=0 );
32902 SimulateIOError(return SQLITE_IOERR_FSTAT);
32903 lowerBits = GetFileSize(pFile->h, &upperBits);
32904 if( (lowerBits == INVALID_FILE_SIZE)
32905 && ((error = GetLastError()) != NO_ERROR) )
32907 pFile->lastErrno = error;
32908 return winLogError(SQLITE_IOERR_FSTAT, "winFileSize", pFile->zPath);
32910 *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
32911 return SQLITE_OK;
32915 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
32917 #ifndef LOCKFILE_FAIL_IMMEDIATELY
32918 # define LOCKFILE_FAIL_IMMEDIATELY 1
32919 #endif
32922 ** Acquire a reader lock.
32923 ** Different API routines are called depending on whether or not this
32924 ** is Win95 or WinNT.
32926 static int getReadLock(winFile *pFile){
32927 int res;
32928 if( isNT() ){
32929 OVERLAPPED ovlp;
32930 ovlp.Offset = SHARED_FIRST;
32931 ovlp.OffsetHigh = 0;
32932 ovlp.hEvent = 0;
32933 res = LockFileEx(pFile->h, LOCKFILE_FAIL_IMMEDIATELY,
32934 0, SHARED_SIZE, 0, &ovlp);
32935 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
32937 #if SQLITE_OS_WINCE==0
32938 }else{
32939 int lk;
32940 sqlite3_randomness(sizeof(lk), &lk);
32941 pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
32942 res = LockFile(pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
32943 #endif
32945 if( res == 0 ){
32946 pFile->lastErrno = GetLastError();
32947 /* No need to log a failure to lock */
32949 return res;
32953 ** Undo a readlock
32955 static int unlockReadLock(winFile *pFile){
32956 int res;
32957 if( isNT() ){
32958 res = UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
32959 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
32961 #if SQLITE_OS_WINCE==0
32962 }else{
32963 res = UnlockFile(pFile->h, SHARED_FIRST + pFile->sharedLockByte, 0, 1, 0);
32964 #endif
32966 if( res==0 && GetLastError()!=ERROR_NOT_LOCKED ){
32967 pFile->lastErrno = GetLastError();
32968 winLogError(SQLITE_IOERR_UNLOCK, "unlockReadLock", pFile->zPath);
32970 return res;
32974 ** Lock the file with the lock specified by parameter locktype - one
32975 ** of the following:
32977 ** (1) SHARED_LOCK
32978 ** (2) RESERVED_LOCK
32979 ** (3) PENDING_LOCK
32980 ** (4) EXCLUSIVE_LOCK
32982 ** Sometimes when requesting one lock state, additional lock states
32983 ** are inserted in between. The locking might fail on one of the later
32984 ** transitions leaving the lock state different from what it started but
32985 ** still short of its goal. The following chart shows the allowed
32986 ** transitions and the inserted intermediate states:
32988 ** UNLOCKED -> SHARED
32989 ** SHARED -> RESERVED
32990 ** SHARED -> (PENDING) -> EXCLUSIVE
32991 ** RESERVED -> (PENDING) -> EXCLUSIVE
32992 ** PENDING -> EXCLUSIVE
32994 ** This routine will only increase a lock. The winUnlock() routine
32995 ** erases all locks at once and returns us immediately to locking level 0.
32996 ** It is not possible to lower the locking level one step at a time. You
32997 ** must go straight to locking level 0.
32999 static int winLock(sqlite3_file *id, int locktype){
33000 int rc = SQLITE_OK; /* Return code from subroutines */
33001 int res = 1; /* Result of a windows lock call */
33002 int newLocktype; /* Set pFile->locktype to this value before exiting */
33003 int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
33004 winFile *pFile = (winFile*)id;
33005 DWORD error = NO_ERROR;
33007 assert( id!=0 );
33008 OSTRACE(("LOCK %d %d was %d(%d)\n",
33009 pFile->h, locktype, pFile->locktype, pFile->sharedLockByte));
33011 /* If there is already a lock of this type or more restrictive on the
33012 ** OsFile, do nothing. Don't use the end_lock: exit path, as
33013 ** sqlite3OsEnterMutex() hasn't been called yet.
33015 if( pFile->locktype>=locktype ){
33016 return SQLITE_OK;
33019 /* Make sure the locking sequence is correct
33021 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
33022 assert( locktype!=PENDING_LOCK );
33023 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
33025 /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
33026 ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of
33027 ** the PENDING_LOCK byte is temporary.
33029 newLocktype = pFile->locktype;
33030 if( (pFile->locktype==NO_LOCK)
33031 || ( (locktype==EXCLUSIVE_LOCK)
33032 && (pFile->locktype==RESERVED_LOCK))
33034 int cnt = 3;
33035 while( cnt-->0 && (res = LockFile(pFile->h, PENDING_BYTE, 0, 1, 0))==0 ){
33036 /* Try 3 times to get the pending lock. The pending lock might be
33037 ** held by another reader process who will release it momentarily.
33039 OSTRACE(("could not get a PENDING lock. cnt=%d\n", cnt));
33040 Sleep(1);
33042 gotPendingLock = res;
33043 if( !res ){
33044 error = GetLastError();
33048 /* Acquire a shared lock
33050 if( locktype==SHARED_LOCK && res ){
33051 assert( pFile->locktype==NO_LOCK );
33052 res = getReadLock(pFile);
33053 if( res ){
33054 newLocktype = SHARED_LOCK;
33055 }else{
33056 error = GetLastError();
33060 /* Acquire a RESERVED lock
33062 if( locktype==RESERVED_LOCK && res ){
33063 assert( pFile->locktype==SHARED_LOCK );
33064 res = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
33065 if( res ){
33066 newLocktype = RESERVED_LOCK;
33067 }else{
33068 error = GetLastError();
33072 /* Acquire a PENDING lock
33074 if( locktype==EXCLUSIVE_LOCK && res ){
33075 newLocktype = PENDING_LOCK;
33076 gotPendingLock = 0;
33079 /* Acquire an EXCLUSIVE lock
33081 if( locktype==EXCLUSIVE_LOCK && res ){
33082 assert( pFile->locktype>=SHARED_LOCK );
33083 res = unlockReadLock(pFile);
33084 OSTRACE(("unreadlock = %d\n", res));
33085 res = LockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
33086 if( res ){
33087 newLocktype = EXCLUSIVE_LOCK;
33088 }else{
33089 error = GetLastError();
33090 OSTRACE(("error-code = %d\n", error));
33091 getReadLock(pFile);
33095 /* If we are holding a PENDING lock that ought to be released, then
33096 ** release it now.
33098 if( gotPendingLock && locktype==SHARED_LOCK ){
33099 UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
33102 /* Update the state of the lock has held in the file descriptor then
33103 ** return the appropriate result code.
33105 if( res ){
33106 rc = SQLITE_OK;
33107 }else{
33108 OSTRACE(("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
33109 locktype, newLocktype));
33110 pFile->lastErrno = error;
33111 rc = SQLITE_BUSY;
33113 pFile->locktype = (u8)newLocktype;
33114 return rc;
33118 ** This routine checks if there is a RESERVED lock held on the specified
33119 ** file by this or any other process. If such a lock is held, return
33120 ** non-zero, otherwise zero.
33122 static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
33123 int rc;
33124 winFile *pFile = (winFile*)id;
33126 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
33128 assert( id!=0 );
33129 if( pFile->locktype>=RESERVED_LOCK ){
33130 rc = 1;
33131 OSTRACE(("TEST WR-LOCK %d %d (local)\n", pFile->h, rc));
33132 }else{
33133 rc = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
33134 if( rc ){
33135 UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
33137 rc = !rc;
33138 OSTRACE(("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc));
33140 *pResOut = rc;
33141 return SQLITE_OK;
33145 ** Lower the locking level on file descriptor id to locktype. locktype
33146 ** must be either NO_LOCK or SHARED_LOCK.
33148 ** If the locking level of the file descriptor is already at or below
33149 ** the requested locking level, this routine is a no-op.
33151 ** It is not possible for this routine to fail if the second argument
33152 ** is NO_LOCK. If the second argument is SHARED_LOCK then this routine
33153 ** might return SQLITE_IOERR;
33155 static int winUnlock(sqlite3_file *id, int locktype){
33156 int type;
33157 winFile *pFile = (winFile*)id;
33158 int rc = SQLITE_OK;
33159 assert( pFile!=0 );
33160 assert( locktype<=SHARED_LOCK );
33161 OSTRACE(("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
33162 pFile->locktype, pFile->sharedLockByte));
33163 type = pFile->locktype;
33164 if( type>=EXCLUSIVE_LOCK ){
33165 UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
33166 if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
33167 /* This should never happen. We should always be able to
33168 ** reacquire the read lock */
33169 rc = winLogError(SQLITE_IOERR_UNLOCK, "winUnlock", pFile->zPath);
33172 if( type>=RESERVED_LOCK ){
33173 UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
33175 if( locktype==NO_LOCK && type>=SHARED_LOCK ){
33176 unlockReadLock(pFile);
33178 if( type>=PENDING_LOCK ){
33179 UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
33181 pFile->locktype = (u8)locktype;
33182 return rc;
33186 ** Control and query of the open file handle.
33188 static int winFileControl(sqlite3_file *id, int op, void *pArg){
33189 winFile *pFile = (winFile*)id;
33190 switch( op ){
33191 case SQLITE_FCNTL_LOCKSTATE: {
33192 *(int*)pArg = pFile->locktype;
33193 return SQLITE_OK;
33195 case SQLITE_LAST_ERRNO: {
33196 *(int*)pArg = (int)pFile->lastErrno;
33197 return SQLITE_OK;
33199 case SQLITE_FCNTL_CHUNK_SIZE: {
33200 pFile->szChunk = *(int *)pArg;
33201 return SQLITE_OK;
33203 case SQLITE_FCNTL_SIZE_HINT: {
33204 if( pFile->szChunk>0 ){
33205 sqlite3_int64 oldSz;
33206 int rc = winFileSize(id, &oldSz);
33207 if( rc==SQLITE_OK ){
33208 sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
33209 if( newSz>oldSz ){
33210 SimulateIOErrorBenign(1);
33211 rc = winTruncate(id, newSz);
33212 SimulateIOErrorBenign(0);
33215 return rc;
33217 return SQLITE_OK;
33219 case SQLITE_FCNTL_PERSIST_WAL: {
33220 int bPersist = *(int*)pArg;
33221 if( bPersist<0 ){
33222 *(int*)pArg = pFile->bPersistWal;
33223 }else{
33224 pFile->bPersistWal = bPersist!=0;
33226 return SQLITE_OK;
33228 case SQLITE_FCNTL_SYNC_OMITTED: {
33229 return SQLITE_OK;
33231 case SQLITE_FCNTL_WIN32_AV_RETRY: {
33232 int *a = (int*)pArg;
33233 if( a[0]>0 ){
33234 win32IoerrRetry = a[0];
33235 }else{
33236 a[0] = win32IoerrRetry;
33238 if( a[1]>0 ){
33239 win32IoerrRetryDelay = a[1];
33240 }else{
33241 a[1] = win32IoerrRetryDelay;
33243 return SQLITE_OK;
33246 return SQLITE_NOTFOUND;
33250 ** Return the sector size in bytes of the underlying block device for
33251 ** the specified file. This is almost always 512 bytes, but may be
33252 ** larger for some devices.
33254 ** SQLite code assumes this function cannot fail. It also assumes that
33255 ** if two files are created in the same file-system directory (i.e.
33256 ** a database and its journal file) that the sector size will be the
33257 ** same for both.
33259 static int winSectorSize(sqlite3_file *id){
33260 assert( id!=0 );
33261 return (int)(((winFile*)id)->sectorSize);
33265 ** Return a vector of device characteristics.
33267 static int winDeviceCharacteristics(sqlite3_file *id){
33268 UNUSED_PARAMETER(id);
33269 return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN;
33272 #ifndef SQLITE_OMIT_WAL
33275 ** Windows will only let you create file view mappings
33276 ** on allocation size granularity boundaries.
33277 ** During sqlite3_os_init() we do a GetSystemInfo()
33278 ** to get the granularity size.
33280 SYSTEM_INFO winSysInfo;
33283 ** Helper functions to obtain and relinquish the global mutex. The
33284 ** global mutex is used to protect the winLockInfo objects used by
33285 ** this file, all of which may be shared by multiple threads.
33287 ** Function winShmMutexHeld() is used to assert() that the global mutex
33288 ** is held when required. This function is only used as part of assert()
33289 ** statements. e.g.
33291 ** winShmEnterMutex()
33292 ** assert( winShmMutexHeld() );
33293 ** winShmLeaveMutex()
33295 static void winShmEnterMutex(void){
33296 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
33298 static void winShmLeaveMutex(void){
33299 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
33301 #ifdef SQLITE_DEBUG
33302 static int winShmMutexHeld(void) {
33303 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
33305 #endif
33308 ** Object used to represent a single file opened and mmapped to provide
33309 ** shared memory. When multiple threads all reference the same
33310 ** log-summary, each thread has its own winFile object, but they all
33311 ** point to a single instance of this object. In other words, each
33312 ** log-summary is opened only once per process.
33314 ** winShmMutexHeld() must be true when creating or destroying
33315 ** this object or while reading or writing the following fields:
33317 ** nRef
33318 ** pNext
33320 ** The following fields are read-only after the object is created:
33322 ** fid
33323 ** zFilename
33325 ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
33326 ** winShmMutexHeld() is true when reading or writing any other field
33327 ** in this structure.
33330 struct winShmNode {
33331 sqlite3_mutex *mutex; /* Mutex to access this object */
33332 char *zFilename; /* Name of the file */
33333 winFile hFile; /* File handle from winOpen */
33335 int szRegion; /* Size of shared-memory regions */
33336 int nRegion; /* Size of array apRegion */
33337 struct ShmRegion {
33338 HANDLE hMap; /* File handle from CreateFileMapping */
33339 void *pMap;
33340 } *aRegion;
33341 DWORD lastErrno; /* The Windows errno from the last I/O error */
33343 int nRef; /* Number of winShm objects pointing to this */
33344 winShm *pFirst; /* All winShm objects pointing to this */
33345 winShmNode *pNext; /* Next in list of all winShmNode objects */
33346 #ifdef SQLITE_DEBUG
33347 u8 nextShmId; /* Next available winShm.id value */
33348 #endif
33352 ** A global array of all winShmNode objects.
33354 ** The winShmMutexHeld() must be true while reading or writing this list.
33356 static winShmNode *winShmNodeList = 0;
33359 ** Structure used internally by this VFS to record the state of an
33360 ** open shared memory connection.
33362 ** The following fields are initialized when this object is created and
33363 ** are read-only thereafter:
33365 ** winShm.pShmNode
33366 ** winShm.id
33368 ** All other fields are read/write. The winShm.pShmNode->mutex must be held
33369 ** while accessing any read/write fields.
33371 struct winShm {
33372 winShmNode *pShmNode; /* The underlying winShmNode object */
33373 winShm *pNext; /* Next winShm with the same winShmNode */
33374 u8 hasMutex; /* True if holding the winShmNode mutex */
33375 u16 sharedMask; /* Mask of shared locks held */
33376 u16 exclMask; /* Mask of exclusive locks held */
33377 #ifdef SQLITE_DEBUG
33378 u8 id; /* Id of this connection with its winShmNode */
33379 #endif
33383 ** Constants used for locking
33385 #define WIN_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
33386 #define WIN_SHM_DMS (WIN_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
33389 ** Apply advisory locks for all n bytes beginning at ofst.
33391 #define _SHM_UNLCK 1
33392 #define _SHM_RDLCK 2
33393 #define _SHM_WRLCK 3
33394 static int winShmSystemLock(
33395 winShmNode *pFile, /* Apply locks to this open shared-memory segment */
33396 int lockType, /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
33397 int ofst, /* Offset to first byte to be locked/unlocked */
33398 int nByte /* Number of bytes to lock or unlock */
33400 OVERLAPPED ovlp;
33401 DWORD dwFlags;
33402 int rc = 0; /* Result code form Lock/UnlockFileEx() */
33404 /* Access to the winShmNode object is serialized by the caller */
33405 assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
33407 /* Initialize the locking parameters */
33408 dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
33409 if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
33411 memset(&ovlp, 0, sizeof(OVERLAPPED));
33412 ovlp.Offset = ofst;
33414 /* Release/Acquire the system-level lock */
33415 if( lockType==_SHM_UNLCK ){
33416 rc = UnlockFileEx(pFile->hFile.h, 0, nByte, 0, &ovlp);
33417 }else{
33418 rc = LockFileEx(pFile->hFile.h, dwFlags, 0, nByte, 0, &ovlp);
33421 if( rc!= 0 ){
33422 rc = SQLITE_OK;
33423 }else{
33424 pFile->lastErrno = GetLastError();
33425 rc = SQLITE_BUSY;
33428 OSTRACE(("SHM-LOCK %d %s %s 0x%08lx\n",
33429 pFile->hFile.h,
33430 rc==SQLITE_OK ? "ok" : "failed",
33431 lockType==_SHM_UNLCK ? "UnlockFileEx" : "LockFileEx",
33432 pFile->lastErrno));
33434 return rc;
33437 /* Forward references to VFS methods */
33438 static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
33439 static int winDelete(sqlite3_vfs *,const char*,int);
33442 ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
33444 ** This is not a VFS shared-memory method; it is a utility function called
33445 ** by VFS shared-memory methods.
33447 static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
33448 winShmNode **pp;
33449 winShmNode *p;
33450 BOOL bRc;
33451 assert( winShmMutexHeld() );
33452 pp = &winShmNodeList;
33453 while( (p = *pp)!=0 ){
33454 if( p->nRef==0 ){
33455 int i;
33456 if( p->mutex ) sqlite3_mutex_free(p->mutex);
33457 for(i=0; i<p->nRegion; i++){
33458 bRc = UnmapViewOfFile(p->aRegion[i].pMap);
33459 OSTRACE(("SHM-PURGE pid-%d unmap region=%d %s\n",
33460 (int)GetCurrentProcessId(), i,
33461 bRc ? "ok" : "failed"));
33462 bRc = CloseHandle(p->aRegion[i].hMap);
33463 OSTRACE(("SHM-PURGE pid-%d close region=%d %s\n",
33464 (int)GetCurrentProcessId(), i,
33465 bRc ? "ok" : "failed"));
33467 if( p->hFile.h != INVALID_HANDLE_VALUE ){
33468 SimulateIOErrorBenign(1);
33469 winClose((sqlite3_file *)&p->hFile);
33470 SimulateIOErrorBenign(0);
33472 if( deleteFlag ){
33473 SimulateIOErrorBenign(1);
33474 winDelete(pVfs, p->zFilename, 0);
33475 SimulateIOErrorBenign(0);
33477 *pp = p->pNext;
33478 sqlite3_free(p->aRegion);
33479 sqlite3_free(p);
33480 }else{
33481 pp = &p->pNext;
33487 ** Open the shared-memory area associated with database file pDbFd.
33489 ** When opening a new shared-memory file, if no other instances of that
33490 ** file are currently open, in this process or in other processes, then
33491 ** the file must be truncated to zero length or have its header cleared.
33493 static int winOpenSharedMemory(winFile *pDbFd){
33494 struct winShm *p; /* The connection to be opened */
33495 struct winShmNode *pShmNode = 0; /* The underlying mmapped file */
33496 int rc; /* Result code */
33497 struct winShmNode *pNew; /* Newly allocated winShmNode */
33498 int nName; /* Size of zName in bytes */
33500 assert( pDbFd->pShm==0 ); /* Not previously opened */
33502 /* Allocate space for the new sqlite3_shm object. Also speculatively
33503 ** allocate space for a new winShmNode and filename.
33505 p = sqlite3_malloc( sizeof(*p) );
33506 if( p==0 ) return SQLITE_NOMEM;
33507 memset(p, 0, sizeof(*p));
33508 nName = sqlite3Strlen30(pDbFd->zPath);
33509 pNew = sqlite3_malloc( sizeof(*pShmNode) + nName + 15 );
33510 if( pNew==0 ){
33511 sqlite3_free(p);
33512 return SQLITE_NOMEM;
33514 memset(pNew, 0, sizeof(*pNew));
33515 pNew->zFilename = (char*)&pNew[1];
33516 sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
33517 sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
33519 /* Look to see if there is an existing winShmNode that can be used.
33520 ** If no matching winShmNode currently exists, create a new one.
33522 winShmEnterMutex();
33523 for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
33524 /* TBD need to come up with better match here. Perhaps
33525 ** use FILE_ID_BOTH_DIR_INFO Structure.
33527 if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
33529 if( pShmNode ){
33530 sqlite3_free(pNew);
33531 }else{
33532 pShmNode = pNew;
33533 pNew = 0;
33534 ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
33535 pShmNode->pNext = winShmNodeList;
33536 winShmNodeList = pShmNode;
33538 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
33539 if( pShmNode->mutex==0 ){
33540 rc = SQLITE_NOMEM;
33541 goto shm_open_err;
33544 rc = winOpen(pDbFd->pVfs,
33545 pShmNode->zFilename, /* Name of the file (UTF-8) */
33546 (sqlite3_file*)&pShmNode->hFile, /* File handle here */
33547 SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, /* Mode flags */
33549 if( SQLITE_OK!=rc ){
33550 rc = SQLITE_CANTOPEN_BKPT;
33551 goto shm_open_err;
33554 /* Check to see if another process is holding the dead-man switch.
33555 ** If not, truncate the file to zero length.
33557 if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
33558 rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
33559 if( rc!=SQLITE_OK ){
33560 rc = winLogError(SQLITE_IOERR_SHMOPEN, "winOpenShm", pDbFd->zPath);
33563 if( rc==SQLITE_OK ){
33564 winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
33565 rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
33567 if( rc ) goto shm_open_err;
33570 /* Make the new connection a child of the winShmNode */
33571 p->pShmNode = pShmNode;
33572 #ifdef SQLITE_DEBUG
33573 p->id = pShmNode->nextShmId++;
33574 #endif
33575 pShmNode->nRef++;
33576 pDbFd->pShm = p;
33577 winShmLeaveMutex();
33579 /* The reference count on pShmNode has already been incremented under
33580 ** the cover of the winShmEnterMutex() mutex and the pointer from the
33581 ** new (struct winShm) object to the pShmNode has been set. All that is
33582 ** left to do is to link the new object into the linked list starting
33583 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
33584 ** mutex.
33586 sqlite3_mutex_enter(pShmNode->mutex);
33587 p->pNext = pShmNode->pFirst;
33588 pShmNode->pFirst = p;
33589 sqlite3_mutex_leave(pShmNode->mutex);
33590 return SQLITE_OK;
33592 /* Jump here on any error */
33593 shm_open_err:
33594 winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
33595 winShmPurge(pDbFd->pVfs, 0); /* This call frees pShmNode if required */
33596 sqlite3_free(p);
33597 sqlite3_free(pNew);
33598 winShmLeaveMutex();
33599 return rc;
33603 ** Close a connection to shared-memory. Delete the underlying
33604 ** storage if deleteFlag is true.
33606 static int winShmUnmap(
33607 sqlite3_file *fd, /* Database holding shared memory */
33608 int deleteFlag /* Delete after closing if true */
33610 winFile *pDbFd; /* Database holding shared-memory */
33611 winShm *p; /* The connection to be closed */
33612 winShmNode *pShmNode; /* The underlying shared-memory file */
33613 winShm **pp; /* For looping over sibling connections */
33615 pDbFd = (winFile*)fd;
33616 p = pDbFd->pShm;
33617 if( p==0 ) return SQLITE_OK;
33618 pShmNode = p->pShmNode;
33620 /* Remove connection p from the set of connections associated
33621 ** with pShmNode */
33622 sqlite3_mutex_enter(pShmNode->mutex);
33623 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
33624 *pp = p->pNext;
33626 /* Free the connection p */
33627 sqlite3_free(p);
33628 pDbFd->pShm = 0;
33629 sqlite3_mutex_leave(pShmNode->mutex);
33631 /* If pShmNode->nRef has reached 0, then close the underlying
33632 ** shared-memory file, too */
33633 winShmEnterMutex();
33634 assert( pShmNode->nRef>0 );
33635 pShmNode->nRef--;
33636 if( pShmNode->nRef==0 ){
33637 winShmPurge(pDbFd->pVfs, deleteFlag);
33639 winShmLeaveMutex();
33641 return SQLITE_OK;
33645 ** Change the lock state for a shared-memory segment.
33647 static int winShmLock(
33648 sqlite3_file *fd, /* Database file holding the shared memory */
33649 int ofst, /* First lock to acquire or release */
33650 int n, /* Number of locks to acquire or release */
33651 int flags /* What to do with the lock */
33653 winFile *pDbFd = (winFile*)fd; /* Connection holding shared memory */
33654 winShm *p = pDbFd->pShm; /* The shared memory being locked */
33655 winShm *pX; /* For looping over all siblings */
33656 winShmNode *pShmNode = p->pShmNode;
33657 int rc = SQLITE_OK; /* Result code */
33658 u16 mask; /* Mask of locks to take or release */
33660 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
33661 assert( n>=1 );
33662 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
33663 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
33664 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
33665 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
33666 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
33668 mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
33669 assert( n>1 || mask==(1<<ofst) );
33670 sqlite3_mutex_enter(pShmNode->mutex);
33671 if( flags & SQLITE_SHM_UNLOCK ){
33672 u16 allMask = 0; /* Mask of locks held by siblings */
33674 /* See if any siblings hold this same lock */
33675 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
33676 if( pX==p ) continue;
33677 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
33678 allMask |= pX->sharedMask;
33681 /* Unlock the system-level locks */
33682 if( (mask & allMask)==0 ){
33683 rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
33684 }else{
33685 rc = SQLITE_OK;
33688 /* Undo the local locks */
33689 if( rc==SQLITE_OK ){
33690 p->exclMask &= ~mask;
33691 p->sharedMask &= ~mask;
33693 }else if( flags & SQLITE_SHM_SHARED ){
33694 u16 allShared = 0; /* Union of locks held by connections other than "p" */
33696 /* Find out which shared locks are already held by sibling connections.
33697 ** If any sibling already holds an exclusive lock, go ahead and return
33698 ** SQLITE_BUSY.
33700 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
33701 if( (pX->exclMask & mask)!=0 ){
33702 rc = SQLITE_BUSY;
33703 break;
33705 allShared |= pX->sharedMask;
33708 /* Get shared locks at the system level, if necessary */
33709 if( rc==SQLITE_OK ){
33710 if( (allShared & mask)==0 ){
33711 rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
33712 }else{
33713 rc = SQLITE_OK;
33717 /* Get the local shared locks */
33718 if( rc==SQLITE_OK ){
33719 p->sharedMask |= mask;
33721 }else{
33722 /* Make sure no sibling connections hold locks that will block this
33723 ** lock. If any do, return SQLITE_BUSY right away.
33725 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
33726 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
33727 rc = SQLITE_BUSY;
33728 break;
33732 /* Get the exclusive locks at the system level. Then if successful
33733 ** also mark the local connection as being locked.
33735 if( rc==SQLITE_OK ){
33736 rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
33737 if( rc==SQLITE_OK ){
33738 assert( (p->sharedMask & mask)==0 );
33739 p->exclMask |= mask;
33743 sqlite3_mutex_leave(pShmNode->mutex);
33744 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x %s\n",
33745 p->id, (int)GetCurrentProcessId(), p->sharedMask, p->exclMask,
33746 rc ? "failed" : "ok"));
33747 return rc;
33751 ** Implement a memory barrier or memory fence on shared memory.
33753 ** All loads and stores begun before the barrier must complete before
33754 ** any load or store begun after the barrier.
33756 static void winShmBarrier(
33757 sqlite3_file *fd /* Database holding the shared memory */
33759 UNUSED_PARAMETER(fd);
33760 /* MemoryBarrier(); // does not work -- do not know why not */
33761 winShmEnterMutex();
33762 winShmLeaveMutex();
33766 ** This function is called to obtain a pointer to region iRegion of the
33767 ** shared-memory associated with the database file fd. Shared-memory regions
33768 ** are numbered starting from zero. Each shared-memory region is szRegion
33769 ** bytes in size.
33771 ** If an error occurs, an error code is returned and *pp is set to NULL.
33773 ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
33774 ** region has not been allocated (by any client, including one running in a
33775 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
33776 ** isWrite is non-zero and the requested shared-memory region has not yet
33777 ** been allocated, it is allocated by this function.
33779 ** If the shared-memory region has already been allocated or is allocated by
33780 ** this call as described above, then it is mapped into this processes
33781 ** address space (if it is not already), *pp is set to point to the mapped
33782 ** memory and SQLITE_OK returned.
33784 static int winShmMap(
33785 sqlite3_file *fd, /* Handle open on database file */
33786 int iRegion, /* Region to retrieve */
33787 int szRegion, /* Size of regions */
33788 int isWrite, /* True to extend file if necessary */
33789 void volatile **pp /* OUT: Mapped memory */
33791 winFile *pDbFd = (winFile*)fd;
33792 winShm *p = pDbFd->pShm;
33793 winShmNode *pShmNode;
33794 int rc = SQLITE_OK;
33796 if( !p ){
33797 rc = winOpenSharedMemory(pDbFd);
33798 if( rc!=SQLITE_OK ) return rc;
33799 p = pDbFd->pShm;
33801 pShmNode = p->pShmNode;
33803 sqlite3_mutex_enter(pShmNode->mutex);
33804 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
33806 if( pShmNode->nRegion<=iRegion ){
33807 struct ShmRegion *apNew; /* New aRegion[] array */
33808 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
33809 sqlite3_int64 sz; /* Current size of wal-index file */
33811 pShmNode->szRegion = szRegion;
33813 /* The requested region is not mapped into this processes address space.
33814 ** Check to see if it has been allocated (i.e. if the wal-index file is
33815 ** large enough to contain the requested region).
33817 rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
33818 if( rc!=SQLITE_OK ){
33819 rc = winLogError(SQLITE_IOERR_SHMSIZE, "winShmMap1", pDbFd->zPath);
33820 goto shmpage_out;
33823 if( sz<nByte ){
33824 /* The requested memory region does not exist. If isWrite is set to
33825 ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
33827 ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
33828 ** the requested memory region.
33830 if( !isWrite ) goto shmpage_out;
33831 rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
33832 if( rc!=SQLITE_OK ){
33833 rc = winLogError(SQLITE_IOERR_SHMSIZE, "winShmMap2", pDbFd->zPath);
33834 goto shmpage_out;
33838 /* Map the requested memory region into this processes address space. */
33839 apNew = (struct ShmRegion *)sqlite3_realloc(
33840 pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
33842 if( !apNew ){
33843 rc = SQLITE_IOERR_NOMEM;
33844 goto shmpage_out;
33846 pShmNode->aRegion = apNew;
33848 while( pShmNode->nRegion<=iRegion ){
33849 HANDLE hMap; /* file-mapping handle */
33850 void *pMap = 0; /* Mapped memory region */
33852 hMap = CreateFileMapping(pShmNode->hFile.h,
33853 NULL, PAGE_READWRITE, 0, nByte, NULL
33855 OSTRACE(("SHM-MAP pid-%d create region=%d nbyte=%d %s\n",
33856 (int)GetCurrentProcessId(), pShmNode->nRegion, nByte,
33857 hMap ? "ok" : "failed"));
33858 if( hMap ){
33859 int iOffset = pShmNode->nRegion*szRegion;
33860 int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
33861 pMap = MapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
33862 0, iOffset - iOffsetShift, szRegion + iOffsetShift
33864 OSTRACE(("SHM-MAP pid-%d map region=%d offset=%d size=%d %s\n",
33865 (int)GetCurrentProcessId(), pShmNode->nRegion, iOffset, szRegion,
33866 pMap ? "ok" : "failed"));
33868 if( !pMap ){
33869 pShmNode->lastErrno = GetLastError();
33870 rc = winLogError(SQLITE_IOERR_SHMMAP, "winShmMap3", pDbFd->zPath);
33871 if( hMap ) CloseHandle(hMap);
33872 goto shmpage_out;
33875 pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
33876 pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
33877 pShmNode->nRegion++;
33881 shmpage_out:
33882 if( pShmNode->nRegion>iRegion ){
33883 int iOffset = iRegion*szRegion;
33884 int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
33885 char *p = (char *)pShmNode->aRegion[iRegion].pMap;
33886 *pp = (void *)&p[iOffsetShift];
33887 }else{
33888 *pp = 0;
33890 sqlite3_mutex_leave(pShmNode->mutex);
33891 return rc;
33894 #else
33895 # define winShmMap 0
33896 # define winShmLock 0
33897 # define winShmBarrier 0
33898 # define winShmUnmap 0
33899 #endif /* #ifndef SQLITE_OMIT_WAL */
33902 ** Here ends the implementation of all sqlite3_file methods.
33904 ********************** End sqlite3_file Methods *******************************
33905 ******************************************************************************/
33908 ** This vector defines all the methods that can operate on an
33909 ** sqlite3_file for win32.
33911 static const sqlite3_io_methods winIoMethod = {
33912 2, /* iVersion */
33913 winClose, /* xClose */
33914 winRead, /* xRead */
33915 winWrite, /* xWrite */
33916 winTruncate, /* xTruncate */
33917 winSync, /* xSync */
33918 winFileSize, /* xFileSize */
33919 winLock, /* xLock */
33920 winUnlock, /* xUnlock */
33921 winCheckReservedLock, /* xCheckReservedLock */
33922 winFileControl, /* xFileControl */
33923 winSectorSize, /* xSectorSize */
33924 winDeviceCharacteristics, /* xDeviceCharacteristics */
33925 winShmMap, /* xShmMap */
33926 winShmLock, /* xShmLock */
33927 winShmBarrier, /* xShmBarrier */
33928 winShmUnmap /* xShmUnmap */
33931 /****************************************************************************
33932 **************************** sqlite3_vfs methods ****************************
33934 ** This division contains the implementation of methods on the
33935 ** sqlite3_vfs object.
33939 ** Convert a UTF-8 filename into whatever form the underlying
33940 ** operating system wants filenames in. Space to hold the result
33941 ** is obtained from malloc and must be freed by the calling
33942 ** function.
33944 static void *convertUtf8Filename(const char *zFilename){
33945 void *zConverted = 0;
33946 if( isNT() ){
33947 zConverted = utf8ToUnicode(zFilename);
33948 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
33950 #if SQLITE_OS_WINCE==0
33951 }else{
33952 zConverted = sqlite3_win32_utf8_to_mbcs(zFilename);
33953 #endif
33955 /* caller will handle out of memory */
33956 return zConverted;
33960 ** Create a temporary file name in zBuf. zBuf must be big enough to
33961 ** hold at pVfs->mxPathname characters.
33963 static int getTempname(int nBuf, char *zBuf){
33964 static char zChars[] =
33965 "abcdefghijklmnopqrstuvwxyz"
33966 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
33967 "0123456789";
33968 size_t i, j;
33969 char zTempPath[MAX_PATH+1];
33971 /* It's odd to simulate an io-error here, but really this is just
33972 ** using the io-error infrastructure to test that SQLite handles this
33973 ** function failing.
33975 SimulateIOError( return SQLITE_IOERR );
33977 if( sqlite3_temp_directory ){
33978 sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
33979 }else if( isNT() ){
33980 char *zMulti;
33981 WCHAR zWidePath[MAX_PATH];
33982 GetTempPathW(MAX_PATH-30, zWidePath);
33983 zMulti = unicodeToUtf8(zWidePath);
33984 if( zMulti ){
33985 sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
33986 free(zMulti);
33987 }else{
33988 return SQLITE_NOMEM;
33990 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
33991 ** Since the ASCII version of these Windows API do not exist for WINCE,
33992 ** it's important to not reference them for WINCE builds.
33994 #if SQLITE_OS_WINCE==0
33995 }else{
33996 char *zUtf8;
33997 char zMbcsPath[MAX_PATH];
33998 GetTempPathA(MAX_PATH-30, zMbcsPath);
33999 zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
34000 if( zUtf8 ){
34001 sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
34002 free(zUtf8);
34003 }else{
34004 return SQLITE_NOMEM;
34006 #endif
34009 /* Check that the output buffer is large enough for the temporary file
34010 ** name. If it is not, return SQLITE_ERROR.
34012 if( (sqlite3Strlen30(zTempPath) + sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX) + 17) >= nBuf ){
34013 return SQLITE_ERROR;
34016 for(i=sqlite3Strlen30(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){}
34017 zTempPath[i] = 0;
34019 sqlite3_snprintf(nBuf-17, zBuf,
34020 "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
34021 j = sqlite3Strlen30(zBuf);
34022 sqlite3_randomness(15, &zBuf[j]);
34023 for(i=0; i<15; i++, j++){
34024 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
34026 zBuf[j] = 0;
34028 OSTRACE(("TEMP FILENAME: %s\n", zBuf));
34029 return SQLITE_OK;
34033 ** Open a file.
34035 static int winOpen(
34036 sqlite3_vfs *pVfs, /* Not used */
34037 const char *zName, /* Name of the file (UTF-8) */
34038 sqlite3_file *id, /* Write the SQLite file handle here */
34039 int flags, /* Open mode flags */
34040 int *pOutFlags /* Status return flags */
34042 HANDLE h;
34043 DWORD dwDesiredAccess;
34044 DWORD dwShareMode;
34045 DWORD dwCreationDisposition;
34046 DWORD dwFlagsAndAttributes = 0;
34047 #if SQLITE_OS_WINCE
34048 int isTemp = 0;
34049 #endif
34050 winFile *pFile = (winFile*)id;
34051 void *zConverted; /* Filename in OS encoding */
34052 const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
34053 int cnt = 0;
34055 /* If argument zPath is a NULL pointer, this function is required to open
34056 ** a temporary file. Use this buffer to store the file name in.
34058 char zTmpname[MAX_PATH+1]; /* Buffer used to create temp filename */
34060 int rc = SQLITE_OK; /* Function Return Code */
34061 #if !defined(NDEBUG) || SQLITE_OS_WINCE
34062 int eType = flags&0xFFFFFF00; /* Type of file to open */
34063 #endif
34065 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
34066 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
34067 int isCreate = (flags & SQLITE_OPEN_CREATE);
34068 #ifndef NDEBUG
34069 int isReadonly = (flags & SQLITE_OPEN_READONLY);
34070 #endif
34071 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
34073 #ifndef NDEBUG
34074 int isOpenJournal = (isCreate && (
34075 eType==SQLITE_OPEN_MASTER_JOURNAL
34076 || eType==SQLITE_OPEN_MAIN_JOURNAL
34077 || eType==SQLITE_OPEN_WAL
34079 #endif
34081 /* Check the following statements are true:
34083 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
34084 ** (b) if CREATE is set, then READWRITE must also be set, and
34085 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
34086 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
34088 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
34089 assert(isCreate==0 || isReadWrite);
34090 assert(isExclusive==0 || isCreate);
34091 assert(isDelete==0 || isCreate);
34093 /* The main DB, main journal, WAL file and master journal are never
34094 ** automatically deleted. Nor are they ever temporary files. */
34095 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
34096 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
34097 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
34098 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
34100 /* Assert that the upper layer has set one of the "file-type" flags. */
34101 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
34102 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
34103 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
34104 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
34107 assert( id!=0 );
34108 UNUSED_PARAMETER(pVfs);
34110 pFile->h = INVALID_HANDLE_VALUE;
34112 /* If the second argument to this function is NULL, generate a
34113 ** temporary file name to use
34115 if( !zUtf8Name ){
34116 assert(isDelete && !isOpenJournal);
34117 rc = getTempname(MAX_PATH+1, zTmpname);
34118 if( rc!=SQLITE_OK ){
34119 return rc;
34121 zUtf8Name = zTmpname;
34124 /* Convert the filename to the system encoding. */
34125 zConverted = convertUtf8Filename(zUtf8Name);
34126 if( zConverted==0 ){
34127 return SQLITE_NOMEM;
34130 if( isReadWrite ){
34131 dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
34132 }else{
34133 dwDesiredAccess = GENERIC_READ;
34136 /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
34137 ** created. SQLite doesn't use it to indicate "exclusive access"
34138 ** as it is usually understood.
34140 if( isExclusive ){
34141 /* Creates a new file, only if it does not already exist. */
34142 /* If the file exists, it fails. */
34143 dwCreationDisposition = CREATE_NEW;
34144 }else if( isCreate ){
34145 /* Open existing file, or create if it doesn't exist */
34146 dwCreationDisposition = OPEN_ALWAYS;
34147 }else{
34148 /* Opens a file, only if it exists. */
34149 dwCreationDisposition = OPEN_EXISTING;
34152 dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
34154 if( isDelete ){
34155 #if SQLITE_OS_WINCE
34156 dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
34157 isTemp = 1;
34158 #else
34159 dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
34160 | FILE_ATTRIBUTE_HIDDEN
34161 | FILE_FLAG_DELETE_ON_CLOSE;
34162 #endif
34163 }else{
34164 dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
34166 /* Reports from the internet are that performance is always
34167 ** better if FILE_FLAG_RANDOM_ACCESS is used. Ticket #2699. */
34168 #if SQLITE_OS_WINCE
34169 dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
34170 #endif
34172 if( isNT() ){
34173 while( (h = CreateFileW((WCHAR*)zConverted,
34174 dwDesiredAccess,
34175 dwShareMode, NULL,
34176 dwCreationDisposition,
34177 dwFlagsAndAttributes,
34178 NULL))==INVALID_HANDLE_VALUE &&
34179 retryIoerr(&cnt) ){}
34180 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
34181 ** Since the ASCII version of these Windows API do not exist for WINCE,
34182 ** it's important to not reference them for WINCE builds.
34184 #if SQLITE_OS_WINCE==0
34185 }else{
34186 while( (h = CreateFileA((char*)zConverted,
34187 dwDesiredAccess,
34188 dwShareMode, NULL,
34189 dwCreationDisposition,
34190 dwFlagsAndAttributes,
34191 NULL))==INVALID_HANDLE_VALUE &&
34192 retryIoerr(&cnt) ){}
34193 #endif
34196 logIoerr(cnt);
34198 OSTRACE(("OPEN %d %s 0x%lx %s\n",
34199 h, zName, dwDesiredAccess,
34200 h==INVALID_HANDLE_VALUE ? "failed" : "ok"));
34202 if( h==INVALID_HANDLE_VALUE ){
34203 pFile->lastErrno = GetLastError();
34204 winLogError(SQLITE_CANTOPEN, "winOpen", zUtf8Name);
34205 free(zConverted);
34206 if( isReadWrite && !isExclusive ){
34207 return winOpen(pVfs, zName, id,
34208 ((flags|SQLITE_OPEN_READONLY)&~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)), pOutFlags);
34209 }else{
34210 return SQLITE_CANTOPEN_BKPT;
34214 if( pOutFlags ){
34215 if( isReadWrite ){
34216 *pOutFlags = SQLITE_OPEN_READWRITE;
34217 }else{
34218 *pOutFlags = SQLITE_OPEN_READONLY;
34222 memset(pFile, 0, sizeof(*pFile));
34223 pFile->pMethod = &winIoMethod;
34224 pFile->h = h;
34225 pFile->lastErrno = NO_ERROR;
34226 pFile->pVfs = pVfs;
34227 pFile->pShm = 0;
34228 pFile->zPath = zName;
34229 pFile->sectorSize = getSectorSize(pVfs, zUtf8Name);
34231 #if SQLITE_OS_WINCE
34232 if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
34233 && !winceCreateLock(zName, pFile)
34235 CloseHandle(h);
34236 free(zConverted);
34237 return SQLITE_CANTOPEN_BKPT;
34239 if( isTemp ){
34240 pFile->zDeleteOnClose = zConverted;
34241 }else
34242 #endif
34244 free(zConverted);
34247 OpenCounter(+1);
34248 return rc;
34252 ** Delete the named file.
34254 ** Note that windows does not allow a file to be deleted if some other
34255 ** process has it open. Sometimes a virus scanner or indexing program
34256 ** will open a journal file shortly after it is created in order to do
34257 ** whatever it does. While this other process is holding the
34258 ** file open, we will be unable to delete it. To work around this
34259 ** problem, we delay 100 milliseconds and try to delete again. Up
34260 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
34261 ** up and returning an error.
34263 static int winDelete(
34264 sqlite3_vfs *pVfs, /* Not used on win32 */
34265 const char *zFilename, /* Name of file to delete */
34266 int syncDir /* Not used on win32 */
34268 int cnt = 0;
34269 int rc;
34270 void *zConverted;
34271 UNUSED_PARAMETER(pVfs);
34272 UNUSED_PARAMETER(syncDir);
34274 SimulateIOError(return SQLITE_IOERR_DELETE);
34275 zConverted = convertUtf8Filename(zFilename);
34276 if( zConverted==0 ){
34277 return SQLITE_NOMEM;
34279 if( isNT() ){
34280 rc = 1;
34281 while( GetFileAttributesW(zConverted)!=INVALID_FILE_ATTRIBUTES &&
34282 (rc = DeleteFileW(zConverted))==0 && retryIoerr(&cnt) ){}
34283 rc = rc ? SQLITE_OK : SQLITE_ERROR;
34284 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
34285 ** Since the ASCII version of these Windows API do not exist for WINCE,
34286 ** it's important to not reference them for WINCE builds.
34288 #if SQLITE_OS_WINCE==0
34289 }else{
34290 rc = 1;
34291 while( GetFileAttributesA(zConverted)!=INVALID_FILE_ATTRIBUTES &&
34292 (rc = DeleteFileA(zConverted))==0 && retryIoerr(&cnt) ){}
34293 rc = rc ? SQLITE_OK : SQLITE_ERROR;
34294 #endif
34296 if( rc ){
34297 rc = winLogError(SQLITE_IOERR_DELETE, "winDelete", zFilename);
34298 }else{
34299 logIoerr(cnt);
34301 free(zConverted);
34302 OSTRACE(("DELETE \"%s\" %s\n", zFilename, (rc ? "failed" : "ok" )));
34303 return rc;
34307 ** Check the existance and status of a file.
34309 static int winAccess(
34310 sqlite3_vfs *pVfs, /* Not used on win32 */
34311 const char *zFilename, /* Name of file to check */
34312 int flags, /* Type of test to make on this file */
34313 int *pResOut /* OUT: Result */
34315 DWORD attr;
34316 int rc = 0;
34317 void *zConverted;
34318 UNUSED_PARAMETER(pVfs);
34320 SimulateIOError( return SQLITE_IOERR_ACCESS; );
34321 zConverted = convertUtf8Filename(zFilename);
34322 if( zConverted==0 ){
34323 return SQLITE_NOMEM;
34325 if( isNT() ){
34326 int cnt = 0;
34327 WIN32_FILE_ATTRIBUTE_DATA sAttrData;
34328 memset(&sAttrData, 0, sizeof(sAttrData));
34329 while( !(rc = GetFileAttributesExW((WCHAR*)zConverted,
34330 GetFileExInfoStandard,
34331 &sAttrData)) && retryIoerr(&cnt) ){}
34332 if( rc ){
34333 /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
34334 ** as if it does not exist.
34336 if( flags==SQLITE_ACCESS_EXISTS
34337 && sAttrData.nFileSizeHigh==0
34338 && sAttrData.nFileSizeLow==0 ){
34339 attr = INVALID_FILE_ATTRIBUTES;
34340 }else{
34341 attr = sAttrData.dwFileAttributes;
34343 }else{
34344 logIoerr(cnt);
34345 if( GetLastError()!=ERROR_FILE_NOT_FOUND ){
34346 winLogError(SQLITE_IOERR_ACCESS, "winAccess", zFilename);
34347 free(zConverted);
34348 return SQLITE_IOERR_ACCESS;
34349 }else{
34350 attr = INVALID_FILE_ATTRIBUTES;
34353 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
34354 ** Since the ASCII version of these Windows API do not exist for WINCE,
34355 ** it's important to not reference them for WINCE builds.
34357 #if SQLITE_OS_WINCE==0
34358 }else{
34359 attr = GetFileAttributesA((char*)zConverted);
34360 #endif
34362 free(zConverted);
34363 switch( flags ){
34364 case SQLITE_ACCESS_READ:
34365 case SQLITE_ACCESS_EXISTS:
34366 rc = attr!=INVALID_FILE_ATTRIBUTES;
34367 break;
34368 case SQLITE_ACCESS_READWRITE:
34369 rc = attr!=INVALID_FILE_ATTRIBUTES &&
34370 (attr & FILE_ATTRIBUTE_READONLY)==0;
34371 break;
34372 default:
34373 assert(!"Invalid flags argument");
34375 *pResOut = rc;
34376 return SQLITE_OK;
34381 ** Turn a relative pathname into a full pathname. Write the full
34382 ** pathname into zOut[]. zOut[] will be at least pVfs->mxPathname
34383 ** bytes in size.
34385 static int winFullPathname(
34386 sqlite3_vfs *pVfs, /* Pointer to vfs object */
34387 const char *zRelative, /* Possibly relative input path */
34388 int nFull, /* Size of output buffer in bytes */
34389 char *zFull /* Output buffer */
34392 #if defined(__CYGWIN__)
34393 SimulateIOError( return SQLITE_ERROR );
34394 UNUSED_PARAMETER(nFull);
34395 cygwin_conv_to_full_win32_path(zRelative, zFull);
34396 return SQLITE_OK;
34397 #endif
34399 #if SQLITE_OS_WINCE
34400 SimulateIOError( return SQLITE_ERROR );
34401 UNUSED_PARAMETER(nFull);
34402 /* WinCE has no concept of a relative pathname, or so I am told. */
34403 sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zRelative);
34404 return SQLITE_OK;
34405 #endif
34407 #if !SQLITE_OS_WINCE && !defined(__CYGWIN__)
34408 int nByte;
34409 void *zConverted;
34410 char *zOut;
34412 /* If this path name begins with "/X:", where "X" is any alphabetic
34413 ** character, discard the initial "/" from the pathname.
34415 if( zRelative[0]=='/' && sqlite3Isalpha(zRelative[1]) && zRelative[2]==':' ){
34416 zRelative++;
34419 /* It's odd to simulate an io-error here, but really this is just
34420 ** using the io-error infrastructure to test that SQLite handles this
34421 ** function failing. This function could fail if, for example, the
34422 ** current working directory has been unlinked.
34424 SimulateIOError( return SQLITE_ERROR );
34425 UNUSED_PARAMETER(nFull);
34426 zConverted = convertUtf8Filename(zRelative);
34427 if( isNT() ){
34428 WCHAR *zTemp;
34429 nByte = GetFullPathNameW((WCHAR*)zConverted, 0, 0, 0) + 3;
34430 zTemp = malloc( nByte*sizeof(zTemp[0]) );
34431 if( zTemp==0 ){
34432 free(zConverted);
34433 return SQLITE_NOMEM;
34435 GetFullPathNameW((WCHAR*)zConverted, nByte, zTemp, 0);
34436 free(zConverted);
34437 zOut = unicodeToUtf8(zTemp);
34438 free(zTemp);
34439 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
34440 ** Since the ASCII version of these Windows API do not exist for WINCE,
34441 ** it's important to not reference them for WINCE builds.
34443 #if SQLITE_OS_WINCE==0
34444 }else{
34445 char *zTemp;
34446 nByte = GetFullPathNameA((char*)zConverted, 0, 0, 0) + 3;
34447 zTemp = malloc( nByte*sizeof(zTemp[0]) );
34448 if( zTemp==0 ){
34449 free(zConverted);
34450 return SQLITE_NOMEM;
34452 GetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
34453 free(zConverted);
34454 zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
34455 free(zTemp);
34456 #endif
34458 if( zOut ){
34459 sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zOut);
34460 free(zOut);
34461 return SQLITE_OK;
34462 }else{
34463 return SQLITE_NOMEM;
34465 #endif
34469 ** Get the sector size of the device used to store
34470 ** file.
34472 static int getSectorSize(
34473 sqlite3_vfs *pVfs,
34474 const char *zRelative /* UTF-8 file name */
34476 DWORD bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
34477 /* GetDiskFreeSpace is not supported under WINCE */
34478 #if SQLITE_OS_WINCE
34479 UNUSED_PARAMETER(pVfs);
34480 UNUSED_PARAMETER(zRelative);
34481 #else
34482 char zFullpath[MAX_PATH+1];
34483 int rc;
34484 DWORD dwRet = 0;
34485 DWORD dwDummy;
34488 ** We need to get the full path name of the file
34489 ** to get the drive letter to look up the sector
34490 ** size.
34492 SimulateIOErrorBenign(1);
34493 rc = winFullPathname(pVfs, zRelative, MAX_PATH, zFullpath);
34494 SimulateIOErrorBenign(0);
34495 if( rc == SQLITE_OK )
34497 void *zConverted = convertUtf8Filename(zFullpath);
34498 if( zConverted ){
34499 if( isNT() ){
34500 /* trim path to just drive reference */
34501 WCHAR *p = zConverted;
34502 for(;*p;p++){
34503 if( *p == '\\' ){
34504 *p = '\0';
34505 break;
34508 dwRet = GetDiskFreeSpaceW((WCHAR*)zConverted,
34509 &dwDummy,
34510 &bytesPerSector,
34511 &dwDummy,
34512 &dwDummy);
34513 }else{
34514 /* trim path to just drive reference */
34515 char *p = (char *)zConverted;
34516 for(;*p;p++){
34517 if( *p == '\\' ){
34518 *p = '\0';
34519 break;
34522 dwRet = GetDiskFreeSpaceA((char*)zConverted,
34523 &dwDummy,
34524 &bytesPerSector,
34525 &dwDummy,
34526 &dwDummy);
34528 free(zConverted);
34530 if( !dwRet ){
34531 bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
34534 #endif
34535 return (int) bytesPerSector;
34538 #ifndef SQLITE_OMIT_LOAD_EXTENSION
34540 ** Interfaces for opening a shared library, finding entry points
34541 ** within the shared library, and closing the shared library.
34544 ** Interfaces for opening a shared library, finding entry points
34545 ** within the shared library, and closing the shared library.
34547 static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
34548 HANDLE h;
34549 void *zConverted = convertUtf8Filename(zFilename);
34550 UNUSED_PARAMETER(pVfs);
34551 if( zConverted==0 ){
34552 return 0;
34554 if( isNT() ){
34555 h = LoadLibraryW((WCHAR*)zConverted);
34556 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
34557 ** Since the ASCII version of these Windows API do not exist for WINCE,
34558 ** it's important to not reference them for WINCE builds.
34560 #if SQLITE_OS_WINCE==0
34561 }else{
34562 h = LoadLibraryA((char*)zConverted);
34563 #endif
34565 free(zConverted);
34566 return (void*)h;
34568 static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
34569 UNUSED_PARAMETER(pVfs);
34570 getLastErrorMsg(nBuf, zBufOut);
34572 static void (*winDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
34573 UNUSED_PARAMETER(pVfs);
34574 #if SQLITE_OS_WINCE
34575 /* The GetProcAddressA() routine is only available on wince. */
34576 return (void(*)(void))GetProcAddressA((HANDLE)pHandle, zSymbol);
34577 #else
34578 /* All other windows platforms expect GetProcAddress() to take
34579 ** an Ansi string regardless of the _UNICODE setting */
34580 return (void(*)(void))GetProcAddress((HANDLE)pHandle, zSymbol);
34581 #endif
34583 static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
34584 UNUSED_PARAMETER(pVfs);
34585 FreeLibrary((HANDLE)pHandle);
34587 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
34588 #define winDlOpen 0
34589 #define winDlError 0
34590 #define winDlSym 0
34591 #define winDlClose 0
34592 #endif
34596 ** Write up to nBuf bytes of randomness into zBuf.
34598 static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
34599 int n = 0;
34600 UNUSED_PARAMETER(pVfs);
34601 #if defined(SQLITE_TEST)
34602 n = nBuf;
34603 memset(zBuf, 0, nBuf);
34604 #else
34605 if( sizeof(SYSTEMTIME)<=nBuf-n ){
34606 SYSTEMTIME x;
34607 GetSystemTime(&x);
34608 memcpy(&zBuf[n], &x, sizeof(x));
34609 n += sizeof(x);
34611 if( sizeof(DWORD)<=nBuf-n ){
34612 DWORD pid = GetCurrentProcessId();
34613 memcpy(&zBuf[n], &pid, sizeof(pid));
34614 n += sizeof(pid);
34616 if( sizeof(DWORD)<=nBuf-n ){
34617 DWORD cnt = GetTickCount();
34618 memcpy(&zBuf[n], &cnt, sizeof(cnt));
34619 n += sizeof(cnt);
34621 if( sizeof(LARGE_INTEGER)<=nBuf-n ){
34622 LARGE_INTEGER i;
34623 QueryPerformanceCounter(&i);
34624 memcpy(&zBuf[n], &i, sizeof(i));
34625 n += sizeof(i);
34627 #endif
34628 return n;
34633 ** Sleep for a little while. Return the amount of time slept.
34635 static int winSleep(sqlite3_vfs *pVfs, int microsec){
34636 Sleep((microsec+999)/1000);
34637 UNUSED_PARAMETER(pVfs);
34638 return ((microsec+999)/1000)*1000;
34642 ** The following variable, if set to a non-zero value, is interpreted as
34643 ** the number of seconds since 1970 and is used to set the result of
34644 ** sqlite3OsCurrentTime() during testing.
34646 #ifdef SQLITE_TEST
34647 SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
34648 #endif
34651 ** Find the current time (in Universal Coordinated Time). Write into *piNow
34652 ** the current time and date as a Julian Day number times 86_400_000. In
34653 ** other words, write into *piNow the number of milliseconds since the Julian
34654 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
34655 ** proleptic Gregorian calendar.
34657 ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
34658 ** cannot be found.
34660 static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
34661 /* FILETIME structure is a 64-bit value representing the number of
34662 100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
34664 FILETIME ft;
34665 static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
34666 #ifdef SQLITE_TEST
34667 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
34668 #endif
34669 /* 2^32 - to avoid use of LL and warnings in gcc */
34670 static const sqlite3_int64 max32BitValue =
34671 (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 + (sqlite3_int64)294967296;
34673 #if SQLITE_OS_WINCE
34674 SYSTEMTIME time;
34675 GetSystemTime(&time);
34676 /* if SystemTimeToFileTime() fails, it returns zero. */
34677 if (!SystemTimeToFileTime(&time,&ft)){
34678 return SQLITE_ERROR;
34680 #else
34681 GetSystemTimeAsFileTime( &ft );
34682 #endif
34684 *piNow = winFiletimeEpoch +
34685 ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
34686 (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
34688 #ifdef SQLITE_TEST
34689 if( sqlite3_current_time ){
34690 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
34692 #endif
34693 UNUSED_PARAMETER(pVfs);
34694 return SQLITE_OK;
34698 ** Find the current time (in Universal Coordinated Time). Write the
34699 ** current time and date as a Julian Day number into *prNow and
34700 ** return 0. Return 1 if the time and date cannot be found.
34702 static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
34703 int rc;
34704 sqlite3_int64 i;
34705 rc = winCurrentTimeInt64(pVfs, &i);
34706 if( !rc ){
34707 *prNow = i/86400000.0;
34709 return rc;
34713 ** The idea is that this function works like a combination of
34714 ** GetLastError() and FormatMessage() on windows (or errno and
34715 ** strerror_r() on unix). After an error is returned by an OS
34716 ** function, SQLite calls this function with zBuf pointing to
34717 ** a buffer of nBuf bytes. The OS layer should populate the
34718 ** buffer with a nul-terminated UTF-8 encoded error message
34719 ** describing the last IO error to have occurred within the calling
34720 ** thread.
34722 ** If the error message is too large for the supplied buffer,
34723 ** it should be truncated. The return value of xGetLastError
34724 ** is zero if the error message fits in the buffer, or non-zero
34725 ** otherwise (if the message was truncated). If non-zero is returned,
34726 ** then it is not necessary to include the nul-terminator character
34727 ** in the output buffer.
34729 ** Not supplying an error message will have no adverse effect
34730 ** on SQLite. It is fine to have an implementation that never
34731 ** returns an error message:
34733 ** int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
34734 ** assert(zBuf[0]=='\0');
34735 ** return 0;
34736 ** }
34738 ** However if an error message is supplied, it will be incorporated
34739 ** by sqlite into the error message available to the user using
34740 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
34742 static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
34743 UNUSED_PARAMETER(pVfs);
34744 return getLastErrorMsg(nBuf, zBuf);
34750 ** Initialize and deinitialize the operating system interface.
34752 SQLITE_API int sqlite3_os_init(void){
34753 static sqlite3_vfs winVfs = {
34754 3, /* iVersion */
34755 sizeof(winFile), /* szOsFile */
34756 MAX_PATH, /* mxPathname */
34757 0, /* pNext */
34758 "win32", /* zName */
34759 0, /* pAppData */
34760 winOpen, /* xOpen */
34761 winDelete, /* xDelete */
34762 winAccess, /* xAccess */
34763 winFullPathname, /* xFullPathname */
34764 winDlOpen, /* xDlOpen */
34765 winDlError, /* xDlError */
34766 winDlSym, /* xDlSym */
34767 winDlClose, /* xDlClose */
34768 winRandomness, /* xRandomness */
34769 winSleep, /* xSleep */
34770 winCurrentTime, /* xCurrentTime */
34771 winGetLastError, /* xGetLastError */
34772 winCurrentTimeInt64, /* xCurrentTimeInt64 */
34773 0, /* xSetSystemCall */
34774 0, /* xGetSystemCall */
34775 0, /* xNextSystemCall */
34778 #ifndef SQLITE_OMIT_WAL
34779 /* get memory map allocation granularity */
34780 memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
34781 GetSystemInfo(&winSysInfo);
34782 assert(winSysInfo.dwAllocationGranularity > 0);
34783 #endif
34785 sqlite3_vfs_register(&winVfs, 1);
34786 return SQLITE_OK;
34788 SQLITE_API int sqlite3_os_end(void){
34789 return SQLITE_OK;
34792 #endif /* SQLITE_OS_WIN */
34794 /************** End of os_win.c **********************************************/
34795 /************** Begin file bitvec.c ******************************************/
34797 ** 2008 February 16
34799 ** The author disclaims copyright to this source code. In place of
34800 ** a legal notice, here is a blessing:
34802 ** May you do good and not evil.
34803 ** May you find forgiveness for yourself and forgive others.
34804 ** May you share freely, never taking more than you give.
34806 *************************************************************************
34807 ** This file implements an object that represents a fixed-length
34808 ** bitmap. Bits are numbered starting with 1.
34810 ** A bitmap is used to record which pages of a database file have been
34811 ** journalled during a transaction, or which pages have the "dont-write"
34812 ** property. Usually only a few pages are meet either condition.
34813 ** So the bitmap is usually sparse and has low cardinality.
34814 ** But sometimes (for example when during a DROP of a large table) most
34815 ** or all of the pages in a database can get journalled. In those cases,
34816 ** the bitmap becomes dense with high cardinality. The algorithm needs
34817 ** to handle both cases well.
34819 ** The size of the bitmap is fixed when the object is created.
34821 ** All bits are clear when the bitmap is created. Individual bits
34822 ** may be set or cleared one at a time.
34824 ** Test operations are about 100 times more common that set operations.
34825 ** Clear operations are exceedingly rare. There are usually between
34826 ** 5 and 500 set operations per Bitvec object, though the number of sets can
34827 ** sometimes grow into tens of thousands or larger. The size of the
34828 ** Bitvec object is the number of pages in the database file at the
34829 ** start of a transaction, and is thus usually less than a few thousand,
34830 ** but can be as large as 2 billion for a really big database.
34833 /* Size of the Bitvec structure in bytes. */
34834 #define BITVEC_SZ 512
34836 /* Round the union size down to the nearest pointer boundary, since that's how
34837 ** it will be aligned within the Bitvec struct. */
34838 #define BITVEC_USIZE (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
34840 /* Type of the array "element" for the bitmap representation.
34841 ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
34842 ** Setting this to the "natural word" size of your CPU may improve
34843 ** performance. */
34844 #define BITVEC_TELEM u8
34845 /* Size, in bits, of the bitmap element. */
34846 #define BITVEC_SZELEM 8
34847 /* Number of elements in a bitmap array. */
34848 #define BITVEC_NELEM (BITVEC_USIZE/sizeof(BITVEC_TELEM))
34849 /* Number of bits in the bitmap array. */
34850 #define BITVEC_NBIT (BITVEC_NELEM*BITVEC_SZELEM)
34852 /* Number of u32 values in hash table. */
34853 #define BITVEC_NINT (BITVEC_USIZE/sizeof(u32))
34854 /* Maximum number of entries in hash table before
34855 ** sub-dividing and re-hashing. */
34856 #define BITVEC_MXHASH (BITVEC_NINT/2)
34857 /* Hashing function for the aHash representation.
34858 ** Empirical testing showed that the *37 multiplier
34859 ** (an arbitrary prime)in the hash function provided
34860 ** no fewer collisions than the no-op *1. */
34861 #define BITVEC_HASH(X) (((X)*1)%BITVEC_NINT)
34863 #define BITVEC_NPTR (BITVEC_USIZE/sizeof(Bitvec *))
34867 ** A bitmap is an instance of the following structure.
34869 ** This bitmap records the existance of zero or more bits
34870 ** with values between 1 and iSize, inclusive.
34872 ** There are three possible representations of the bitmap.
34873 ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
34874 ** bitmap. The least significant bit is bit 1.
34876 ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
34877 ** a hash table that will hold up to BITVEC_MXHASH distinct values.
34879 ** Otherwise, the value i is redirected into one of BITVEC_NPTR
34880 ** sub-bitmaps pointed to by Bitvec.u.apSub[]. Each subbitmap
34881 ** handles up to iDivisor separate values of i. apSub[0] holds
34882 ** values between 1 and iDivisor. apSub[1] holds values between
34883 ** iDivisor+1 and 2*iDivisor. apSub[N] holds values between
34884 ** N*iDivisor+1 and (N+1)*iDivisor. Each subbitmap is normalized
34885 ** to hold deal with values between 1 and iDivisor.
34887 struct Bitvec {
34888 u32 iSize; /* Maximum bit index. Max iSize is 4,294,967,296. */
34889 u32 nSet; /* Number of bits that are set - only valid for aHash
34890 ** element. Max is BITVEC_NINT. For BITVEC_SZ of 512,
34891 ** this would be 125. */
34892 u32 iDivisor; /* Number of bits handled by each apSub[] entry. */
34893 /* Should >=0 for apSub element. */
34894 /* Max iDivisor is max(u32) / BITVEC_NPTR + 1. */
34895 /* For a BITVEC_SZ of 512, this would be 34,359,739. */
34896 union {
34897 BITVEC_TELEM aBitmap[BITVEC_NELEM]; /* Bitmap representation */
34898 u32 aHash[BITVEC_NINT]; /* Hash table representation */
34899 Bitvec *apSub[BITVEC_NPTR]; /* Recursive representation */
34900 } u;
34904 ** Create a new bitmap object able to handle bits between 0 and iSize,
34905 ** inclusive. Return a pointer to the new object. Return NULL if
34906 ** malloc fails.
34908 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
34909 Bitvec *p;
34910 assert( sizeof(*p)==BITVEC_SZ );
34911 p = sqlite3MallocZero( sizeof(*p) );
34912 if( p ){
34913 p->iSize = iSize;
34915 return p;
34919 ** Check to see if the i-th bit is set. Return true or false.
34920 ** If p is NULL (if the bitmap has not been created) or if
34921 ** i is out of range, then return false.
34923 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
34924 if( p==0 ) return 0;
34925 if( i>p->iSize || i==0 ) return 0;
34926 i--;
34927 while( p->iDivisor ){
34928 u32 bin = i/p->iDivisor;
34929 i = i%p->iDivisor;
34930 p = p->u.apSub[bin];
34931 if (!p) {
34932 return 0;
34935 if( p->iSize<=BITVEC_NBIT ){
34936 return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
34937 } else{
34938 u32 h = BITVEC_HASH(i++);
34939 while( p->u.aHash[h] ){
34940 if( p->u.aHash[h]==i ) return 1;
34941 h = (h+1) % BITVEC_NINT;
34943 return 0;
34948 ** Set the i-th bit. Return 0 on success and an error code if
34949 ** anything goes wrong.
34951 ** This routine might cause sub-bitmaps to be allocated. Failing
34952 ** to get the memory needed to hold the sub-bitmap is the only
34953 ** that can go wrong with an insert, assuming p and i are valid.
34955 ** The calling function must ensure that p is a valid Bitvec object
34956 ** and that the value for "i" is within range of the Bitvec object.
34957 ** Otherwise the behavior is undefined.
34959 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
34960 u32 h;
34961 if( p==0 ) return SQLITE_OK;
34962 assert( i>0 );
34963 assert( i<=p->iSize );
34964 i--;
34965 while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
34966 u32 bin = i/p->iDivisor;
34967 i = i%p->iDivisor;
34968 if( p->u.apSub[bin]==0 ){
34969 p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
34970 if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
34972 p = p->u.apSub[bin];
34974 if( p->iSize<=BITVEC_NBIT ){
34975 p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
34976 return SQLITE_OK;
34978 h = BITVEC_HASH(i++);
34979 /* if there wasn't a hash collision, and this doesn't */
34980 /* completely fill the hash, then just add it without */
34981 /* worring about sub-dividing and re-hashing. */
34982 if( !p->u.aHash[h] ){
34983 if (p->nSet<(BITVEC_NINT-1)) {
34984 goto bitvec_set_end;
34985 } else {
34986 goto bitvec_set_rehash;
34989 /* there was a collision, check to see if it's already */
34990 /* in hash, if not, try to find a spot for it */
34991 do {
34992 if( p->u.aHash[h]==i ) return SQLITE_OK;
34993 h++;
34994 if( h>=BITVEC_NINT ) h = 0;
34995 } while( p->u.aHash[h] );
34996 /* we didn't find it in the hash. h points to the first */
34997 /* available free spot. check to see if this is going to */
34998 /* make our hash too "full". */
34999 bitvec_set_rehash:
35000 if( p->nSet>=BITVEC_MXHASH ){
35001 unsigned int j;
35002 int rc;
35003 u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
35004 if( aiValues==0 ){
35005 return SQLITE_NOMEM;
35006 }else{
35007 memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
35008 memset(p->u.apSub, 0, sizeof(p->u.apSub));
35009 p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
35010 rc = sqlite3BitvecSet(p, i);
35011 for(j=0; j<BITVEC_NINT; j++){
35012 if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
35014 sqlite3StackFree(0, aiValues);
35015 return rc;
35018 bitvec_set_end:
35019 p->nSet++;
35020 p->u.aHash[h] = i;
35021 return SQLITE_OK;
35025 ** Clear the i-th bit.
35027 ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
35028 ** that BitvecClear can use to rebuilt its hash table.
35030 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
35031 if( p==0 ) return;
35032 assert( i>0 );
35033 i--;
35034 while( p->iDivisor ){
35035 u32 bin = i/p->iDivisor;
35036 i = i%p->iDivisor;
35037 p = p->u.apSub[bin];
35038 if (!p) {
35039 return;
35042 if( p->iSize<=BITVEC_NBIT ){
35043 p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
35044 }else{
35045 unsigned int j;
35046 u32 *aiValues = pBuf;
35047 memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
35048 memset(p->u.aHash, 0, sizeof(p->u.aHash));
35049 p->nSet = 0;
35050 for(j=0; j<BITVEC_NINT; j++){
35051 if( aiValues[j] && aiValues[j]!=(i+1) ){
35052 u32 h = BITVEC_HASH(aiValues[j]-1);
35053 p->nSet++;
35054 while( p->u.aHash[h] ){
35055 h++;
35056 if( h>=BITVEC_NINT ) h = 0;
35058 p->u.aHash[h] = aiValues[j];
35065 ** Destroy a bitmap object. Reclaim all memory used.
35067 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
35068 if( p==0 ) return;
35069 if( p->iDivisor ){
35070 unsigned int i;
35071 for(i=0; i<BITVEC_NPTR; i++){
35072 sqlite3BitvecDestroy(p->u.apSub[i]);
35075 sqlite3_free(p);
35079 ** Return the value of the iSize parameter specified when Bitvec *p
35080 ** was created.
35082 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
35083 return p->iSize;
35086 #ifndef SQLITE_OMIT_BUILTIN_TEST
35088 ** Let V[] be an array of unsigned characters sufficient to hold
35089 ** up to N bits. Let I be an integer between 0 and N. 0<=I<N.
35090 ** Then the following macros can be used to set, clear, or test
35091 ** individual bits within V.
35093 #define SETBIT(V,I) V[I>>3] |= (1<<(I&7))
35094 #define CLEARBIT(V,I) V[I>>3] &= ~(1<<(I&7))
35095 #define TESTBIT(V,I) (V[I>>3]&(1<<(I&7)))!=0
35098 ** This routine runs an extensive test of the Bitvec code.
35100 ** The input is an array of integers that acts as a program
35101 ** to test the Bitvec. The integers are opcodes followed
35102 ** by 0, 1, or 3 operands, depending on the opcode. Another
35103 ** opcode follows immediately after the last operand.
35105 ** There are 6 opcodes numbered from 0 through 5. 0 is the
35106 ** "halt" opcode and causes the test to end.
35108 ** 0 Halt and return the number of errors
35109 ** 1 N S X Set N bits beginning with S and incrementing by X
35110 ** 2 N S X Clear N bits beginning with S and incrementing by X
35111 ** 3 N Set N randomly chosen bits
35112 ** 4 N Clear N randomly chosen bits
35113 ** 5 N S X Set N bits from S increment X in array only, not in bitvec
35115 ** The opcodes 1 through 4 perform set and clear operations are performed
35116 ** on both a Bitvec object and on a linear array of bits obtained from malloc.
35117 ** Opcode 5 works on the linear array only, not on the Bitvec.
35118 ** Opcode 5 is used to deliberately induce a fault in order to
35119 ** confirm that error detection works.
35121 ** At the conclusion of the test the linear array is compared
35122 ** against the Bitvec object. If there are any differences,
35123 ** an error is returned. If they are the same, zero is returned.
35125 ** If a memory allocation error occurs, return -1.
35127 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
35128 Bitvec *pBitvec = 0;
35129 unsigned char *pV = 0;
35130 int rc = -1;
35131 int i, nx, pc, op;
35132 void *pTmpSpace;
35134 /* Allocate the Bitvec to be tested and a linear array of
35135 ** bits to act as the reference */
35136 pBitvec = sqlite3BitvecCreate( sz );
35137 pV = sqlite3_malloc( (sz+7)/8 + 1 );
35138 pTmpSpace = sqlite3_malloc(BITVEC_SZ);
35139 if( pBitvec==0 || pV==0 || pTmpSpace==0 ) goto bitvec_end;
35140 memset(pV, 0, (sz+7)/8 + 1);
35142 /* NULL pBitvec tests */
35143 sqlite3BitvecSet(0, 1);
35144 sqlite3BitvecClear(0, 1, pTmpSpace);
35146 /* Run the program */
35147 pc = 0;
35148 while( (op = aOp[pc])!=0 ){
35149 switch( op ){
35150 case 1:
35151 case 2:
35152 case 5: {
35153 nx = 4;
35154 i = aOp[pc+2] - 1;
35155 aOp[pc+2] += aOp[pc+3];
35156 break;
35158 case 3:
35159 case 4:
35160 default: {
35161 nx = 2;
35162 sqlite3_randomness(sizeof(i), &i);
35163 break;
35166 if( (--aOp[pc+1]) > 0 ) nx = 0;
35167 pc += nx;
35168 i = (i & 0x7fffffff)%sz;
35169 if( (op & 1)!=0 ){
35170 SETBIT(pV, (i+1));
35171 if( op!=5 ){
35172 if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
35174 }else{
35175 CLEARBIT(pV, (i+1));
35176 sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
35180 /* Test to make sure the linear array exactly matches the
35181 ** Bitvec object. Start with the assumption that they do
35182 ** match (rc==0). Change rc to non-zero if a discrepancy
35183 ** is found.
35185 rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
35186 + sqlite3BitvecTest(pBitvec, 0)
35187 + (sqlite3BitvecSize(pBitvec) - sz);
35188 for(i=1; i<=sz; i++){
35189 if( (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
35190 rc = i;
35191 break;
35195 /* Free allocated structure */
35196 bitvec_end:
35197 sqlite3_free(pTmpSpace);
35198 sqlite3_free(pV);
35199 sqlite3BitvecDestroy(pBitvec);
35200 return rc;
35202 #endif /* SQLITE_OMIT_BUILTIN_TEST */
35204 /************** End of bitvec.c **********************************************/
35205 /************** Begin file pcache.c ******************************************/
35207 ** 2008 August 05
35209 ** The author disclaims copyright to this source code. In place of
35210 ** a legal notice, here is a blessing:
35212 ** May you do good and not evil.
35213 ** May you find forgiveness for yourself and forgive others.
35214 ** May you share freely, never taking more than you give.
35216 *************************************************************************
35217 ** This file implements that page cache.
35221 ** A complete page cache is an instance of this structure.
35223 struct PCache {
35224 PgHdr *pDirty, *pDirtyTail; /* List of dirty pages in LRU order */
35225 PgHdr *pSynced; /* Last synced page in dirty page list */
35226 int nRef; /* Number of referenced pages */
35227 int nMax; /* Configured cache size */
35228 int szPage; /* Size of every page in this cache */
35229 int szExtra; /* Size of extra space for each page */
35230 int bPurgeable; /* True if pages are on backing store */
35231 int (*xStress)(void*,PgHdr*); /* Call to try make a page clean */
35232 void *pStress; /* Argument to xStress */
35233 sqlite3_pcache *pCache; /* Pluggable cache module */
35234 PgHdr *pPage1; /* Reference to page 1 */
35238 ** Some of the assert() macros in this code are too expensive to run
35239 ** even during normal debugging. Use them only rarely on long-running
35240 ** tests. Enable the expensive asserts using the
35241 ** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
35243 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
35244 # define expensive_assert(X) assert(X)
35245 #else
35246 # define expensive_assert(X)
35247 #endif
35249 /********************************** Linked List Management ********************/
35251 #if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
35253 ** Check that the pCache->pSynced variable is set correctly. If it
35254 ** is not, either fail an assert or return zero. Otherwise, return
35255 ** non-zero. This is only used in debugging builds, as follows:
35257 ** expensive_assert( pcacheCheckSynced(pCache) );
35259 static int pcacheCheckSynced(PCache *pCache){
35260 PgHdr *p;
35261 for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){
35262 assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
35264 return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
35266 #endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
35269 ** Remove page pPage from the list of dirty pages.
35271 static void pcacheRemoveFromDirtyList(PgHdr *pPage){
35272 PCache *p = pPage->pCache;
35274 assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
35275 assert( pPage->pDirtyPrev || pPage==p->pDirty );
35277 /* Update the PCache1.pSynced variable if necessary. */
35278 if( p->pSynced==pPage ){
35279 PgHdr *pSynced = pPage->pDirtyPrev;
35280 while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
35281 pSynced = pSynced->pDirtyPrev;
35283 p->pSynced = pSynced;
35286 if( pPage->pDirtyNext ){
35287 pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
35288 }else{
35289 assert( pPage==p->pDirtyTail );
35290 p->pDirtyTail = pPage->pDirtyPrev;
35292 if( pPage->pDirtyPrev ){
35293 pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
35294 }else{
35295 assert( pPage==p->pDirty );
35296 p->pDirty = pPage->pDirtyNext;
35298 pPage->pDirtyNext = 0;
35299 pPage->pDirtyPrev = 0;
35301 expensive_assert( pcacheCheckSynced(p) );
35305 ** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
35306 ** pPage).
35308 static void pcacheAddToDirtyList(PgHdr *pPage){
35309 PCache *p = pPage->pCache;
35311 assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
35313 pPage->pDirtyNext = p->pDirty;
35314 if( pPage->pDirtyNext ){
35315 assert( pPage->pDirtyNext->pDirtyPrev==0 );
35316 pPage->pDirtyNext->pDirtyPrev = pPage;
35318 p->pDirty = pPage;
35319 if( !p->pDirtyTail ){
35320 p->pDirtyTail = pPage;
35322 if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
35323 p->pSynced = pPage;
35325 expensive_assert( pcacheCheckSynced(p) );
35329 ** Wrapper around the pluggable caches xUnpin method. If the cache is
35330 ** being used for an in-memory database, this function is a no-op.
35332 static void pcacheUnpin(PgHdr *p){
35333 PCache *pCache = p->pCache;
35334 if( pCache->bPurgeable ){
35335 if( p->pgno==1 ){
35336 pCache->pPage1 = 0;
35338 sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 0);
35342 /*************************************************** General Interfaces ******
35344 ** Initialize and shutdown the page cache subsystem. Neither of these
35345 ** functions are threadsafe.
35347 SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
35348 if( sqlite3GlobalConfig.pcache.xInit==0 ){
35349 /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
35350 ** built-in default page cache is used instead of the application defined
35351 ** page cache. */
35352 sqlite3PCacheSetDefault();
35354 return sqlite3GlobalConfig.pcache.xInit(sqlite3GlobalConfig.pcache.pArg);
35356 SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
35357 if( sqlite3GlobalConfig.pcache.xShutdown ){
35358 /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
35359 sqlite3GlobalConfig.pcache.xShutdown(sqlite3GlobalConfig.pcache.pArg);
35364 ** Return the size in bytes of a PCache object.
35366 SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
35369 ** Create a new PCache object. Storage space to hold the object
35370 ** has already been allocated and is passed in as the p pointer.
35371 ** The caller discovers how much space needs to be allocated by
35372 ** calling sqlite3PcacheSize().
35374 SQLITE_PRIVATE void sqlite3PcacheOpen(
35375 int szPage, /* Size of every page */
35376 int szExtra, /* Extra space associated with each page */
35377 int bPurgeable, /* True if pages are on backing store */
35378 int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
35379 void *pStress, /* Argument to xStress */
35380 PCache *p /* Preallocated space for the PCache */
35382 memset(p, 0, sizeof(PCache));
35383 p->szPage = szPage;
35384 p->szExtra = szExtra;
35385 p->bPurgeable = bPurgeable;
35386 p->xStress = xStress;
35387 p->pStress = pStress;
35388 p->nMax = 100;
35392 ** Change the page size for PCache object. The caller must ensure that there
35393 ** are no outstanding page references when this function is called.
35395 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
35396 assert( pCache->nRef==0 && pCache->pDirty==0 );
35397 if( pCache->pCache ){
35398 sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
35399 pCache->pCache = 0;
35400 pCache->pPage1 = 0;
35402 pCache->szPage = szPage;
35406 ** Try to obtain a page from the cache.
35408 SQLITE_PRIVATE int sqlite3PcacheFetch(
35409 PCache *pCache, /* Obtain the page from this cache */
35410 Pgno pgno, /* Page number to obtain */
35411 int createFlag, /* If true, create page if it does not exist already */
35412 PgHdr **ppPage /* Write the page here */
35414 PgHdr *pPage = 0;
35415 int eCreate;
35417 assert( pCache!=0 );
35418 assert( createFlag==1 || createFlag==0 );
35419 assert( pgno>0 );
35421 /* If the pluggable cache (sqlite3_pcache*) has not been allocated,
35422 ** allocate it now.
35424 if( !pCache->pCache && createFlag ){
35425 sqlite3_pcache *p;
35426 int nByte;
35427 nByte = pCache->szPage + pCache->szExtra + sizeof(PgHdr);
35428 p = sqlite3GlobalConfig.pcache.xCreate(nByte, pCache->bPurgeable);
35429 if( !p ){
35430 return SQLITE_NOMEM;
35432 sqlite3GlobalConfig.pcache.xCachesize(p, pCache->nMax);
35433 pCache->pCache = p;
35436 eCreate = createFlag * (1 + (!pCache->bPurgeable || !pCache->pDirty));
35437 if( pCache->pCache ){
35438 pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, eCreate);
35441 if( !pPage && eCreate==1 ){
35442 PgHdr *pPg;
35444 /* Find a dirty page to write-out and recycle. First try to find a
35445 ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
35446 ** cleared), but if that is not possible settle for any other
35447 ** unreferenced dirty page.
35449 expensive_assert( pcacheCheckSynced(pCache) );
35450 for(pPg=pCache->pSynced;
35451 pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
35452 pPg=pPg->pDirtyPrev
35454 pCache->pSynced = pPg;
35455 if( !pPg ){
35456 for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
35458 if( pPg ){
35459 int rc;
35460 #ifdef SQLITE_LOG_CACHE_SPILL
35461 sqlite3_log(SQLITE_FULL,
35462 "spill page %d making room for %d - cache used: %d/%d",
35463 pPg->pgno, pgno,
35464 sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
35465 pCache->nMax);
35466 #endif
35467 rc = pCache->xStress(pCache->pStress, pPg);
35468 if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
35469 return rc;
35473 pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, 2);
35476 if( pPage ){
35477 if( !pPage->pData ){
35478 memset(pPage, 0, sizeof(PgHdr));
35479 pPage->pData = (void *)&pPage[1];
35480 pPage->pExtra = (void*)&((char *)pPage->pData)[pCache->szPage];
35481 memset(pPage->pExtra, 0, pCache->szExtra);
35482 pPage->pCache = pCache;
35483 pPage->pgno = pgno;
35485 assert( pPage->pCache==pCache );
35486 assert( pPage->pgno==pgno );
35487 assert( pPage->pData==(void *)&pPage[1] );
35488 assert( pPage->pExtra==(void *)&((char *)&pPage[1])[pCache->szPage] );
35490 if( 0==pPage->nRef ){
35491 pCache->nRef++;
35493 pPage->nRef++;
35494 if( pgno==1 ){
35495 pCache->pPage1 = pPage;
35498 *ppPage = pPage;
35499 return (pPage==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;
35503 ** Decrement the reference count on a page. If the page is clean and the
35504 ** reference count drops to 0, then it is made elible for recycling.
35506 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *p){
35507 assert( p->nRef>0 );
35508 p->nRef--;
35509 if( p->nRef==0 ){
35510 PCache *pCache = p->pCache;
35511 pCache->nRef--;
35512 if( (p->flags&PGHDR_DIRTY)==0 ){
35513 pcacheUnpin(p);
35514 }else{
35515 /* Move the page to the head of the dirty list. */
35516 pcacheRemoveFromDirtyList(p);
35517 pcacheAddToDirtyList(p);
35523 ** Increase the reference count of a supplied page by 1.
35525 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
35526 assert(p->nRef>0);
35527 p->nRef++;
35531 ** Drop a page from the cache. There must be exactly one reference to the
35532 ** page. This function deletes that reference, so after it returns the
35533 ** page pointed to by p is invalid.
35535 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
35536 PCache *pCache;
35537 assert( p->nRef==1 );
35538 if( p->flags&PGHDR_DIRTY ){
35539 pcacheRemoveFromDirtyList(p);
35541 pCache = p->pCache;
35542 pCache->nRef--;
35543 if( p->pgno==1 ){
35544 pCache->pPage1 = 0;
35546 sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 1);
35550 ** Make sure the page is marked as dirty. If it isn't dirty already,
35551 ** make it so.
35553 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
35554 p->flags &= ~PGHDR_DONT_WRITE;
35555 assert( p->nRef>0 );
35556 if( 0==(p->flags & PGHDR_DIRTY) ){
35557 p->flags |= PGHDR_DIRTY;
35558 pcacheAddToDirtyList( p);
35563 ** Make sure the page is marked as clean. If it isn't clean already,
35564 ** make it so.
35566 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
35567 if( (p->flags & PGHDR_DIRTY) ){
35568 pcacheRemoveFromDirtyList(p);
35569 p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
35570 if( p->nRef==0 ){
35571 pcacheUnpin(p);
35577 ** Make every page in the cache clean.
35579 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
35580 PgHdr *p;
35581 while( (p = pCache->pDirty)!=0 ){
35582 sqlite3PcacheMakeClean(p);
35587 ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
35589 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
35590 PgHdr *p;
35591 for(p=pCache->pDirty; p; p=p->pDirtyNext){
35592 p->flags &= ~PGHDR_NEED_SYNC;
35594 pCache->pSynced = pCache->pDirtyTail;
35598 ** Change the page number of page p to newPgno.
35600 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
35601 PCache *pCache = p->pCache;
35602 assert( p->nRef>0 );
35603 assert( newPgno>0 );
35604 sqlite3GlobalConfig.pcache.xRekey(pCache->pCache, p, p->pgno, newPgno);
35605 p->pgno = newPgno;
35606 if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
35607 pcacheRemoveFromDirtyList(p);
35608 pcacheAddToDirtyList(p);
35613 ** Drop every cache entry whose page number is greater than "pgno". The
35614 ** caller must ensure that there are no outstanding references to any pages
35615 ** other than page 1 with a page number greater than pgno.
35617 ** If there is a reference to page 1 and the pgno parameter passed to this
35618 ** function is 0, then the data area associated with page 1 is zeroed, but
35619 ** the page object is not dropped.
35621 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
35622 if( pCache->pCache ){
35623 PgHdr *p;
35624 PgHdr *pNext;
35625 for(p=pCache->pDirty; p; p=pNext){
35626 pNext = p->pDirtyNext;
35627 /* This routine never gets call with a positive pgno except right
35628 ** after sqlite3PcacheCleanAll(). So if there are dirty pages,
35629 ** it must be that pgno==0.
35631 assert( p->pgno>0 );
35632 if( ALWAYS(p->pgno>pgno) ){
35633 assert( p->flags&PGHDR_DIRTY );
35634 sqlite3PcacheMakeClean(p);
35637 if( pgno==0 && pCache->pPage1 ){
35638 memset(pCache->pPage1->pData, 0, pCache->szPage);
35639 pgno = 1;
35641 sqlite3GlobalConfig.pcache.xTruncate(pCache->pCache, pgno+1);
35646 ** Close a cache.
35648 SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
35649 if( pCache->pCache ){
35650 sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
35655 ** Discard the contents of the cache.
35657 SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
35658 sqlite3PcacheTruncate(pCache, 0);
35662 ** Merge two lists of pages connected by pDirty and in pgno order.
35663 ** Do not both fixing the pDirtyPrev pointers.
35665 static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
35666 PgHdr result, *pTail;
35667 pTail = &result;
35668 while( pA && pB ){
35669 if( pA->pgno<pB->pgno ){
35670 pTail->pDirty = pA;
35671 pTail = pA;
35672 pA = pA->pDirty;
35673 }else{
35674 pTail->pDirty = pB;
35675 pTail = pB;
35676 pB = pB->pDirty;
35679 if( pA ){
35680 pTail->pDirty = pA;
35681 }else if( pB ){
35682 pTail->pDirty = pB;
35683 }else{
35684 pTail->pDirty = 0;
35686 return result.pDirty;
35690 ** Sort the list of pages in accending order by pgno. Pages are
35691 ** connected by pDirty pointers. The pDirtyPrev pointers are
35692 ** corrupted by this sort.
35694 ** Since there cannot be more than 2^31 distinct pages in a database,
35695 ** there cannot be more than 31 buckets required by the merge sorter.
35696 ** One extra bucket is added to catch overflow in case something
35697 ** ever changes to make the previous sentence incorrect.
35699 #define N_SORT_BUCKET 32
35700 static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
35701 PgHdr *a[N_SORT_BUCKET], *p;
35702 int i;
35703 memset(a, 0, sizeof(a));
35704 while( pIn ){
35705 p = pIn;
35706 pIn = p->pDirty;
35707 p->pDirty = 0;
35708 for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
35709 if( a[i]==0 ){
35710 a[i] = p;
35711 break;
35712 }else{
35713 p = pcacheMergeDirtyList(a[i], p);
35714 a[i] = 0;
35717 if( NEVER(i==N_SORT_BUCKET-1) ){
35718 /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
35719 ** the input list. But that is impossible.
35721 a[i] = pcacheMergeDirtyList(a[i], p);
35724 p = a[0];
35725 for(i=1; i<N_SORT_BUCKET; i++){
35726 p = pcacheMergeDirtyList(p, a[i]);
35728 return p;
35732 ** Return a list of all dirty pages in the cache, sorted by page number.
35734 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
35735 PgHdr *p;
35736 for(p=pCache->pDirty; p; p=p->pDirtyNext){
35737 p->pDirty = p->pDirtyNext;
35739 return pcacheSortDirtyList(pCache->pDirty);
35743 ** Return the total number of referenced pages held by the cache.
35745 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
35746 return pCache->nRef;
35750 ** Return the number of references to the page supplied as an argument.
35752 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
35753 return p->nRef;
35757 ** Return the total number of pages in the cache.
35759 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
35760 int nPage = 0;
35761 if( pCache->pCache ){
35762 nPage = sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache);
35764 return nPage;
35767 #ifdef SQLITE_TEST
35769 ** Get the suggested cache-size value.
35771 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
35772 return pCache->nMax;
35774 #endif
35777 ** Set the suggested cache-size value.
35779 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
35780 pCache->nMax = mxPage;
35781 if( pCache->pCache ){
35782 sqlite3GlobalConfig.pcache.xCachesize(pCache->pCache, mxPage);
35786 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
35788 ** For all dirty pages currently in the cache, invoke the specified
35789 ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
35790 ** defined.
35792 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
35793 PgHdr *pDirty;
35794 for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
35795 xIter(pDirty);
35798 #endif
35800 /************** End of pcache.c **********************************************/
35801 /************** Begin file pcache1.c *****************************************/
35803 ** 2008 November 05
35805 ** The author disclaims copyright to this source code. In place of
35806 ** a legal notice, here is a blessing:
35808 ** May you do good and not evil.
35809 ** May you find forgiveness for yourself and forgive others.
35810 ** May you share freely, never taking more than you give.
35812 *************************************************************************
35814 ** This file implements the default page cache implementation (the
35815 ** sqlite3_pcache interface). It also contains part of the implementation
35816 ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
35817 ** If the default page cache implementation is overriden, then neither of
35818 ** these two features are available.
35822 typedef struct PCache1 PCache1;
35823 typedef struct PgHdr1 PgHdr1;
35824 typedef struct PgFreeslot PgFreeslot;
35825 typedef struct PGroup PGroup;
35828 /* Each page cache (or PCache) belongs to a PGroup. A PGroup is a set
35829 ** of one or more PCaches that are able to recycle each others unpinned
35830 ** pages when they are under memory pressure. A PGroup is an instance of
35831 ** the following object.
35833 ** This page cache implementation works in one of two modes:
35835 ** (1) Every PCache is the sole member of its own PGroup. There is
35836 ** one PGroup per PCache.
35838 ** (2) There is a single global PGroup that all PCaches are a member
35839 ** of.
35841 ** Mode 1 uses more memory (since PCache instances are not able to rob
35842 ** unused pages from other PCaches) but it also operates without a mutex,
35843 ** and is therefore often faster. Mode 2 requires a mutex in order to be
35844 ** threadsafe, but is able recycle pages more efficient.
35846 ** For mode (1), PGroup.mutex is NULL. For mode (2) there is only a single
35847 ** PGroup which is the pcache1.grp global variable and its mutex is
35848 ** SQLITE_MUTEX_STATIC_LRU.
35850 struct PGroup {
35851 sqlite3_mutex *mutex; /* MUTEX_STATIC_LRU or NULL */
35852 int nMaxPage; /* Sum of nMax for purgeable caches */
35853 int nMinPage; /* Sum of nMin for purgeable caches */
35854 int mxPinned; /* nMaxpage + 10 - nMinPage */
35855 int nCurrentPage; /* Number of purgeable pages allocated */
35856 PgHdr1 *pLruHead, *pLruTail; /* LRU list of unpinned pages */
35859 /* Each page cache is an instance of the following object. Every
35860 ** open database file (including each in-memory database and each
35861 ** temporary or transient database) has a single page cache which
35862 ** is an instance of this object.
35864 ** Pointers to structures of this type are cast and returned as
35865 ** opaque sqlite3_pcache* handles.
35867 struct PCache1 {
35868 /* Cache configuration parameters. Page size (szPage) and the purgeable
35869 ** flag (bPurgeable) are set when the cache is created. nMax may be
35870 ** modified at any time by a call to the pcache1CacheSize() method.
35871 ** The PGroup mutex must be held when accessing nMax.
35873 PGroup *pGroup; /* PGroup this cache belongs to */
35874 int szPage; /* Size of allocated pages in bytes */
35875 int bPurgeable; /* True if cache is purgeable */
35876 unsigned int nMin; /* Minimum number of pages reserved */
35877 unsigned int nMax; /* Configured "cache_size" value */
35878 unsigned int n90pct; /* nMax*9/10 */
35880 /* Hash table of all pages. The following variables may only be accessed
35881 ** when the accessor is holding the PGroup mutex.
35883 unsigned int nRecyclable; /* Number of pages in the LRU list */
35884 unsigned int nPage; /* Total number of pages in apHash */
35885 unsigned int nHash; /* Number of slots in apHash[] */
35886 PgHdr1 **apHash; /* Hash table for fast lookup by key */
35888 unsigned int iMaxKey; /* Largest key seen since xTruncate() */
35892 ** Each cache entry is represented by an instance of the following
35893 ** structure. A buffer of PgHdr1.pCache->szPage bytes is allocated
35894 ** directly before this structure in memory (see the PGHDR1_TO_PAGE()
35895 ** macro below).
35897 struct PgHdr1 {
35898 unsigned int iKey; /* Key value (page number) */
35899 PgHdr1 *pNext; /* Next in hash table chain */
35900 PCache1 *pCache; /* Cache that currently owns this page */
35901 PgHdr1 *pLruNext; /* Next in LRU list of unpinned pages */
35902 PgHdr1 *pLruPrev; /* Previous in LRU list of unpinned pages */
35906 ** Free slots in the allocator used to divide up the buffer provided using
35907 ** the SQLITE_CONFIG_PAGECACHE mechanism.
35909 struct PgFreeslot {
35910 PgFreeslot *pNext; /* Next free slot */
35914 ** Global data used by this cache.
35916 static SQLITE_WSD struct PCacheGlobal {
35917 PGroup grp; /* The global PGroup for mode (2) */
35919 /* Variables related to SQLITE_CONFIG_PAGECACHE settings. The
35920 ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
35921 ** fixed at sqlite3_initialize() time and do not require mutex protection.
35922 ** The nFreeSlot and pFree values do require mutex protection.
35924 int isInit; /* True if initialized */
35925 int szSlot; /* Size of each free slot */
35926 int nSlot; /* The number of pcache slots */
35927 int nReserve; /* Try to keep nFreeSlot above this */
35928 void *pStart, *pEnd; /* Bounds of pagecache malloc range */
35929 /* Above requires no mutex. Use mutex below for variable that follow. */
35930 sqlite3_mutex *mutex; /* Mutex for accessing the following: */
35931 int nFreeSlot; /* Number of unused pcache slots */
35932 PgFreeslot *pFree; /* Free page blocks */
35933 /* The following value requires a mutex to change. We skip the mutex on
35934 ** reading because (1) most platforms read a 32-bit integer atomically and
35935 ** (2) even if an incorrect value is read, no great harm is done since this
35936 ** is really just an optimization. */
35937 int bUnderPressure; /* True if low on PAGECACHE memory */
35938 } pcache1_g;
35941 ** All code in this file should access the global structure above via the
35942 ** alias "pcache1". This ensures that the WSD emulation is used when
35943 ** compiling for systems that do not support real WSD.
35945 #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
35948 ** When a PgHdr1 structure is allocated, the associated PCache1.szPage
35949 ** bytes of data are located directly before it in memory (i.e. the total
35950 ** size of the allocation is sizeof(PgHdr1)+PCache1.szPage byte). The
35951 ** PGHDR1_TO_PAGE() macro takes a pointer to a PgHdr1 structure as
35952 ** an argument and returns a pointer to the associated block of szPage
35953 ** bytes. The PAGE_TO_PGHDR1() macro does the opposite: its argument is
35954 ** a pointer to a block of szPage bytes of data and the return value is
35955 ** a pointer to the associated PgHdr1 structure.
35957 ** assert( PGHDR1_TO_PAGE(PAGE_TO_PGHDR1(pCache, X))==X );
35959 #define PGHDR1_TO_PAGE(p) (void*)(((char*)p) - p->pCache->szPage)
35960 #define PAGE_TO_PGHDR1(c, p) (PgHdr1*)(((char*)p) + c->szPage)
35963 ** Macros to enter and leave the PCache LRU mutex.
35965 #define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
35966 #define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
35968 /******************************************************************************/
35969 /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
35972 ** This function is called during initialization if a static buffer is
35973 ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
35974 ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
35975 ** enough to contain 'n' buffers of 'sz' bytes each.
35977 ** This routine is called from sqlite3_initialize() and so it is guaranteed
35978 ** to be serialized already. There is no need for further mutexing.
35980 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
35981 if( pcache1.isInit ){
35982 PgFreeslot *p;
35983 sz = ROUNDDOWN8(sz);
35984 pcache1.szSlot = sz;
35985 pcache1.nSlot = pcache1.nFreeSlot = n;
35986 pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
35987 pcache1.pStart = pBuf;
35988 pcache1.pFree = 0;
35989 pcache1.bUnderPressure = 0;
35990 while( n-- ){
35991 p = (PgFreeslot*)pBuf;
35992 p->pNext = pcache1.pFree;
35993 pcache1.pFree = p;
35994 pBuf = (void*)&((char*)pBuf)[sz];
35996 pcache1.pEnd = pBuf;
36001 ** Malloc function used within this file to allocate space from the buffer
36002 ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
36003 ** such buffer exists or there is no space left in it, this function falls
36004 ** back to sqlite3Malloc().
36006 ** Multiple threads can run this routine at the same time. Global variables
36007 ** in pcache1 need to be protected via mutex.
36009 static void *pcache1Alloc(int nByte){
36010 void *p = 0;
36011 assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
36012 sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
36013 if( nByte<=pcache1.szSlot ){
36014 sqlite3_mutex_enter(pcache1.mutex);
36015 p = (PgHdr1 *)pcache1.pFree;
36016 if( p ){
36017 pcache1.pFree = pcache1.pFree->pNext;
36018 pcache1.nFreeSlot--;
36019 pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
36020 assert( pcache1.nFreeSlot>=0 );
36021 sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
36023 sqlite3_mutex_leave(pcache1.mutex);
36025 if( p==0 ){
36026 /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool. Get
36027 ** it from sqlite3Malloc instead.
36029 p = sqlite3Malloc(nByte);
36030 if( p ){
36031 int sz = sqlite3MallocSize(p);
36032 sqlite3_mutex_enter(pcache1.mutex);
36033 sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
36034 sqlite3_mutex_leave(pcache1.mutex);
36036 sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
36038 return p;
36042 ** Free an allocated buffer obtained from pcache1Alloc().
36044 static void pcache1Free(void *p){
36045 if( p==0 ) return;
36046 if( p>=pcache1.pStart && p<pcache1.pEnd ){
36047 PgFreeslot *pSlot;
36048 sqlite3_mutex_enter(pcache1.mutex);
36049 sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
36050 pSlot = (PgFreeslot*)p;
36051 pSlot->pNext = pcache1.pFree;
36052 pcache1.pFree = pSlot;
36053 pcache1.nFreeSlot++;
36054 pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
36055 assert( pcache1.nFreeSlot<=pcache1.nSlot );
36056 sqlite3_mutex_leave(pcache1.mutex);
36057 }else{
36058 int iSize;
36059 assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
36060 sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
36061 iSize = sqlite3MallocSize(p);
36062 sqlite3_mutex_enter(pcache1.mutex);
36063 sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -iSize);
36064 sqlite3_mutex_leave(pcache1.mutex);
36065 sqlite3_free(p);
36069 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
36071 ** Return the size of a pcache allocation
36073 static int pcache1MemSize(void *p){
36074 if( p>=pcache1.pStart && p<pcache1.pEnd ){
36075 return pcache1.szSlot;
36076 }else{
36077 int iSize;
36078 assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
36079 sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
36080 iSize = sqlite3MallocSize(p);
36081 sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
36082 return iSize;
36085 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
36088 ** Allocate a new page object initially associated with cache pCache.
36090 static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
36091 int nByte = sizeof(PgHdr1) + pCache->szPage;
36092 PgHdr1 *p = 0;
36093 void *pPg;
36095 /* The group mutex must be released before pcache1Alloc() is called. This
36096 ** is because it may call sqlite3_release_memory(), which assumes that
36097 ** this mutex is not held. */
36098 assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
36099 pcache1LeaveMutex(pCache->pGroup);
36100 pPg = pcache1Alloc(nByte);
36101 pcache1EnterMutex(pCache->pGroup);
36103 if( pPg ){
36104 p = PAGE_TO_PGHDR1(pCache, pPg);
36105 if( pCache->bPurgeable ){
36106 pCache->pGroup->nCurrentPage++;
36109 return p;
36113 ** Free a page object allocated by pcache1AllocPage().
36115 ** The pointer is allowed to be NULL, which is prudent. But it turns out
36116 ** that the current implementation happens to never call this routine
36117 ** with a NULL pointer, so we mark the NULL test with ALWAYS().
36119 static void pcache1FreePage(PgHdr1 *p){
36120 if( ALWAYS(p) ){
36121 PCache1 *pCache = p->pCache;
36122 assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
36123 pcache1Free(PGHDR1_TO_PAGE(p));
36124 if( pCache->bPurgeable ){
36125 pCache->pGroup->nCurrentPage--;
36131 ** Malloc function used by SQLite to obtain space from the buffer configured
36132 ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
36133 ** exists, this function falls back to sqlite3Malloc().
36135 SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
36136 return pcache1Alloc(sz);
36140 ** Free an allocated buffer obtained from sqlite3PageMalloc().
36142 SQLITE_PRIVATE void sqlite3PageFree(void *p){
36143 pcache1Free(p);
36148 ** Return true if it desirable to avoid allocating a new page cache
36149 ** entry.
36151 ** If memory was allocated specifically to the page cache using
36152 ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
36153 ** it is desirable to avoid allocating a new page cache entry because
36154 ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
36155 ** for all page cache needs and we should not need to spill the
36156 ** allocation onto the heap.
36158 ** Or, the heap is used for all page cache memory put the heap is
36159 ** under memory pressure, then again it is desirable to avoid
36160 ** allocating a new page cache entry in order to avoid stressing
36161 ** the heap even further.
36163 static int pcache1UnderMemoryPressure(PCache1 *pCache){
36164 if( pcache1.nSlot && pCache->szPage<=pcache1.szSlot ){
36165 return pcache1.bUnderPressure;
36166 }else{
36167 return sqlite3HeapNearlyFull();
36171 /******************************************************************************/
36172 /******** General Implementation Functions ************************************/
36175 ** This function is used to resize the hash table used by the cache passed
36176 ** as the first argument.
36178 ** The PCache mutex must be held when this function is called.
36180 static int pcache1ResizeHash(PCache1 *p){
36181 PgHdr1 **apNew;
36182 unsigned int nNew;
36183 unsigned int i;
36185 assert( sqlite3_mutex_held(p->pGroup->mutex) );
36187 nNew = p->nHash*2;
36188 if( nNew<256 ){
36189 nNew = 256;
36192 pcache1LeaveMutex(p->pGroup);
36193 if( p->nHash ){ sqlite3BeginBenignMalloc(); }
36194 apNew = (PgHdr1 **)sqlite3_malloc(sizeof(PgHdr1 *)*nNew);
36195 if( p->nHash ){ sqlite3EndBenignMalloc(); }
36196 pcache1EnterMutex(p->pGroup);
36197 if( apNew ){
36198 memset(apNew, 0, sizeof(PgHdr1 *)*nNew);
36199 for(i=0; i<p->nHash; i++){
36200 PgHdr1 *pPage;
36201 PgHdr1 *pNext = p->apHash[i];
36202 while( (pPage = pNext)!=0 ){
36203 unsigned int h = pPage->iKey % nNew;
36204 pNext = pPage->pNext;
36205 pPage->pNext = apNew[h];
36206 apNew[h] = pPage;
36209 sqlite3_free(p->apHash);
36210 p->apHash = apNew;
36211 p->nHash = nNew;
36214 return (p->apHash ? SQLITE_OK : SQLITE_NOMEM);
36218 ** This function is used internally to remove the page pPage from the
36219 ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
36220 ** LRU list, then this function is a no-op.
36222 ** The PGroup mutex must be held when this function is called.
36224 ** If pPage is NULL then this routine is a no-op.
36226 static void pcache1PinPage(PgHdr1 *pPage){
36227 PCache1 *pCache;
36228 PGroup *pGroup;
36230 if( pPage==0 ) return;
36231 pCache = pPage->pCache;
36232 pGroup = pCache->pGroup;
36233 assert( sqlite3_mutex_held(pGroup->mutex) );
36234 if( pPage->pLruNext || pPage==pGroup->pLruTail ){
36235 if( pPage->pLruPrev ){
36236 pPage->pLruPrev->pLruNext = pPage->pLruNext;
36238 if( pPage->pLruNext ){
36239 pPage->pLruNext->pLruPrev = pPage->pLruPrev;
36241 if( pGroup->pLruHead==pPage ){
36242 pGroup->pLruHead = pPage->pLruNext;
36244 if( pGroup->pLruTail==pPage ){
36245 pGroup->pLruTail = pPage->pLruPrev;
36247 pPage->pLruNext = 0;
36248 pPage->pLruPrev = 0;
36249 pPage->pCache->nRecyclable--;
36255 ** Remove the page supplied as an argument from the hash table
36256 ** (PCache1.apHash structure) that it is currently stored in.
36258 ** The PGroup mutex must be held when this function is called.
36260 static void pcache1RemoveFromHash(PgHdr1 *pPage){
36261 unsigned int h;
36262 PCache1 *pCache = pPage->pCache;
36263 PgHdr1 **pp;
36265 assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
36266 h = pPage->iKey % pCache->nHash;
36267 for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
36268 *pp = (*pp)->pNext;
36270 pCache->nPage--;
36274 ** If there are currently more than nMaxPage pages allocated, try
36275 ** to recycle pages to reduce the number allocated to nMaxPage.
36277 static void pcache1EnforceMaxPage(PGroup *pGroup){
36278 assert( sqlite3_mutex_held(pGroup->mutex) );
36279 while( pGroup->nCurrentPage>pGroup->nMaxPage && pGroup->pLruTail ){
36280 PgHdr1 *p = pGroup->pLruTail;
36281 assert( p->pCache->pGroup==pGroup );
36282 pcache1PinPage(p);
36283 pcache1RemoveFromHash(p);
36284 pcache1FreePage(p);
36289 ** Discard all pages from cache pCache with a page number (key value)
36290 ** greater than or equal to iLimit. Any pinned pages that meet this
36291 ** criteria are unpinned before they are discarded.
36293 ** The PCache mutex must be held when this function is called.
36295 static void pcache1TruncateUnsafe(
36296 PCache1 *pCache, /* The cache to truncate */
36297 unsigned int iLimit /* Drop pages with this pgno or larger */
36299 TESTONLY( unsigned int nPage = 0; ) /* To assert pCache->nPage is correct */
36300 unsigned int h;
36301 assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
36302 for(h=0; h<pCache->nHash; h++){
36303 PgHdr1 **pp = &pCache->apHash[h];
36304 PgHdr1 *pPage;
36305 while( (pPage = *pp)!=0 ){
36306 if( pPage->iKey>=iLimit ){
36307 pCache->nPage--;
36308 *pp = pPage->pNext;
36309 pcache1PinPage(pPage);
36310 pcache1FreePage(pPage);
36311 }else{
36312 pp = &pPage->pNext;
36313 TESTONLY( nPage++; )
36317 assert( pCache->nPage==nPage );
36320 /******************************************************************************/
36321 /******** sqlite3_pcache Methods **********************************************/
36324 ** Implementation of the sqlite3_pcache.xInit method.
36326 static int pcache1Init(void *NotUsed){
36327 UNUSED_PARAMETER(NotUsed);
36328 assert( pcache1.isInit==0 );
36329 memset(&pcache1, 0, sizeof(pcache1));
36330 if( sqlite3GlobalConfig.bCoreMutex ){
36331 pcache1.grp.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
36332 pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PMEM);
36334 pcache1.grp.mxPinned = 10;
36335 pcache1.isInit = 1;
36336 return SQLITE_OK;
36340 ** Implementation of the sqlite3_pcache.xShutdown method.
36341 ** Note that the static mutex allocated in xInit does
36342 ** not need to be freed.
36344 static void pcache1Shutdown(void *NotUsed){
36345 UNUSED_PARAMETER(NotUsed);
36346 assert( pcache1.isInit!=0 );
36347 memset(&pcache1, 0, sizeof(pcache1));
36351 ** Implementation of the sqlite3_pcache.xCreate method.
36353 ** Allocate a new cache.
36355 static sqlite3_pcache *pcache1Create(int szPage, int bPurgeable){
36356 PCache1 *pCache; /* The newly created page cache */
36357 PGroup *pGroup; /* The group the new page cache will belong to */
36358 int sz; /* Bytes of memory required to allocate the new cache */
36361 ** The seperateCache variable is true if each PCache has its own private
36362 ** PGroup. In other words, separateCache is true for mode (1) where no
36363 ** mutexing is required.
36365 ** * Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
36367 ** * Always use a unified cache in single-threaded applications
36369 ** * Otherwise (if multi-threaded and ENABLE_MEMORY_MANAGEMENT is off)
36370 ** use separate caches (mode-1)
36372 #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
36373 const int separateCache = 0;
36374 #else
36375 int separateCache = sqlite3GlobalConfig.bCoreMutex>0;
36376 #endif
36378 sz = sizeof(PCache1) + sizeof(PGroup)*separateCache;
36379 pCache = (PCache1 *)sqlite3_malloc(sz);
36380 if( pCache ){
36381 memset(pCache, 0, sz);
36382 if( separateCache ){
36383 pGroup = (PGroup*)&pCache[1];
36384 pGroup->mxPinned = 10;
36385 }else{
36386 pGroup = &pcache1.grp;
36388 pCache->pGroup = pGroup;
36389 pCache->szPage = szPage;
36390 pCache->bPurgeable = (bPurgeable ? 1 : 0);
36391 if( bPurgeable ){
36392 pCache->nMin = 10;
36393 pcache1EnterMutex(pGroup);
36394 pGroup->nMinPage += pCache->nMin;
36395 pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
36396 pcache1LeaveMutex(pGroup);
36399 return (sqlite3_pcache *)pCache;
36403 ** Implementation of the sqlite3_pcache.xCachesize method.
36405 ** Configure the cache_size limit for a cache.
36407 static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
36408 PCache1 *pCache = (PCache1 *)p;
36409 if( pCache->bPurgeable ){
36410 PGroup *pGroup = pCache->pGroup;
36411 pcache1EnterMutex(pGroup);
36412 pGroup->nMaxPage += (nMax - pCache->nMax);
36413 pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
36414 pCache->nMax = nMax;
36415 pCache->n90pct = pCache->nMax*9/10;
36416 pcache1EnforceMaxPage(pGroup);
36417 pcache1LeaveMutex(pGroup);
36422 ** Implementation of the sqlite3_pcache.xPagecount method.
36424 static int pcache1Pagecount(sqlite3_pcache *p){
36425 int n;
36426 PCache1 *pCache = (PCache1*)p;
36427 pcache1EnterMutex(pCache->pGroup);
36428 n = pCache->nPage;
36429 pcache1LeaveMutex(pCache->pGroup);
36430 return n;
36434 ** Implementation of the sqlite3_pcache.xFetch method.
36436 ** Fetch a page by key value.
36438 ** Whether or not a new page may be allocated by this function depends on
36439 ** the value of the createFlag argument. 0 means do not allocate a new
36440 ** page. 1 means allocate a new page if space is easily available. 2
36441 ** means to try really hard to allocate a new page.
36443 ** For a non-purgeable cache (a cache used as the storage for an in-memory
36444 ** database) there is really no difference between createFlag 1 and 2. So
36445 ** the calling function (pcache.c) will never have a createFlag of 1 on
36446 ** a non-purgable cache.
36448 ** There are three different approaches to obtaining space for a page,
36449 ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
36451 ** 1. Regardless of the value of createFlag, the cache is searched for a
36452 ** copy of the requested page. If one is found, it is returned.
36454 ** 2. If createFlag==0 and the page is not already in the cache, NULL is
36455 ** returned.
36457 ** 3. If createFlag is 1, and the page is not already in the cache, then
36458 ** return NULL (do not allocate a new page) if any of the following
36459 ** conditions are true:
36461 ** (a) the number of pages pinned by the cache is greater than
36462 ** PCache1.nMax, or
36464 ** (b) the number of pages pinned by the cache is greater than
36465 ** the sum of nMax for all purgeable caches, less the sum of
36466 ** nMin for all other purgeable caches, or
36468 ** 4. If none of the first three conditions apply and the cache is marked
36469 ** as purgeable, and if one of the following is true:
36471 ** (a) The number of pages allocated for the cache is already
36472 ** PCache1.nMax, or
36474 ** (b) The number of pages allocated for all purgeable caches is
36475 ** already equal to or greater than the sum of nMax for all
36476 ** purgeable caches,
36478 ** (c) The system is under memory pressure and wants to avoid
36479 ** unnecessary pages cache entry allocations
36481 ** then attempt to recycle a page from the LRU list. If it is the right
36482 ** size, return the recycled buffer. Otherwise, free the buffer and
36483 ** proceed to step 5.
36485 ** 5. Otherwise, allocate and return a new page buffer.
36487 static void *pcache1Fetch(sqlite3_pcache *p, unsigned int iKey, int createFlag){
36488 int nPinned;
36489 PCache1 *pCache = (PCache1 *)p;
36490 PGroup *pGroup;
36491 PgHdr1 *pPage = 0;
36493 assert( pCache->bPurgeable || createFlag!=1 );
36494 assert( pCache->bPurgeable || pCache->nMin==0 );
36495 assert( pCache->bPurgeable==0 || pCache->nMin==10 );
36496 assert( pCache->nMin==0 || pCache->bPurgeable );
36497 pcache1EnterMutex(pGroup = pCache->pGroup);
36499 /* Step 1: Search the hash table for an existing entry. */
36500 if( pCache->nHash>0 ){
36501 unsigned int h = iKey % pCache->nHash;
36502 for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);
36505 /* Step 2: Abort if no existing page is found and createFlag is 0 */
36506 if( pPage || createFlag==0 ){
36507 pcache1PinPage(pPage);
36508 goto fetch_out;
36511 /* The pGroup local variable will normally be initialized by the
36512 ** pcache1EnterMutex() macro above. But if SQLITE_MUTEX_OMIT is defined,
36513 ** then pcache1EnterMutex() is a no-op, so we have to initialize the
36514 ** local variable here. Delaying the initialization of pGroup is an
36515 ** optimization: The common case is to exit the module before reaching
36516 ** this point.
36518 #ifdef SQLITE_MUTEX_OMIT
36519 pGroup = pCache->pGroup;
36520 #endif
36523 /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
36524 nPinned = pCache->nPage - pCache->nRecyclable;
36525 assert( nPinned>=0 );
36526 assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
36527 assert( pCache->n90pct == pCache->nMax*9/10 );
36528 if( createFlag==1 && (
36529 nPinned>=pGroup->mxPinned
36530 || nPinned>=(int)pCache->n90pct
36531 || pcache1UnderMemoryPressure(pCache)
36533 goto fetch_out;
36536 if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
36537 goto fetch_out;
36540 /* Step 4. Try to recycle a page. */
36541 if( pCache->bPurgeable && pGroup->pLruTail && (
36542 (pCache->nPage+1>=pCache->nMax)
36543 || pGroup->nCurrentPage>=pGroup->nMaxPage
36544 || pcache1UnderMemoryPressure(pCache)
36546 PCache1 *pOtherCache;
36547 pPage = pGroup->pLruTail;
36548 pcache1RemoveFromHash(pPage);
36549 pcache1PinPage(pPage);
36550 if( (pOtherCache = pPage->pCache)->szPage!=pCache->szPage ){
36551 pcache1FreePage(pPage);
36552 pPage = 0;
36553 }else{
36554 pGroup->nCurrentPage -=
36555 (pOtherCache->bPurgeable - pCache->bPurgeable);
36559 /* Step 5. If a usable page buffer has still not been found,
36560 ** attempt to allocate a new one.
36562 if( !pPage ){
36563 if( createFlag==1 ) sqlite3BeginBenignMalloc();
36564 pPage = pcache1AllocPage(pCache);
36565 if( createFlag==1 ) sqlite3EndBenignMalloc();
36568 if( pPage ){
36569 unsigned int h = iKey % pCache->nHash;
36570 pCache->nPage++;
36571 pPage->iKey = iKey;
36572 pPage->pNext = pCache->apHash[h];
36573 pPage->pCache = pCache;
36574 pPage->pLruPrev = 0;
36575 pPage->pLruNext = 0;
36576 *(void **)(PGHDR1_TO_PAGE(pPage)) = 0;
36577 pCache->apHash[h] = pPage;
36580 fetch_out:
36581 if( pPage && iKey>pCache->iMaxKey ){
36582 pCache->iMaxKey = iKey;
36584 pcache1LeaveMutex(pGroup);
36585 return (pPage ? PGHDR1_TO_PAGE(pPage) : 0);
36590 ** Implementation of the sqlite3_pcache.xUnpin method.
36592 ** Mark a page as unpinned (eligible for asynchronous recycling).
36594 static void pcache1Unpin(sqlite3_pcache *p, void *pPg, int reuseUnlikely){
36595 PCache1 *pCache = (PCache1 *)p;
36596 PgHdr1 *pPage = PAGE_TO_PGHDR1(pCache, pPg);
36597 PGroup *pGroup = pCache->pGroup;
36599 assert( pPage->pCache==pCache );
36600 pcache1EnterMutex(pGroup);
36602 /* It is an error to call this function if the page is already
36603 ** part of the PGroup LRU list.
36605 assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
36606 assert( pGroup->pLruHead!=pPage && pGroup->pLruTail!=pPage );
36608 if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
36609 pcache1RemoveFromHash(pPage);
36610 pcache1FreePage(pPage);
36611 }else{
36612 /* Add the page to the PGroup LRU list. */
36613 if( pGroup->pLruHead ){
36614 pGroup->pLruHead->pLruPrev = pPage;
36615 pPage->pLruNext = pGroup->pLruHead;
36616 pGroup->pLruHead = pPage;
36617 }else{
36618 pGroup->pLruTail = pPage;
36619 pGroup->pLruHead = pPage;
36621 pCache->nRecyclable++;
36624 pcache1LeaveMutex(pCache->pGroup);
36628 ** Implementation of the sqlite3_pcache.xRekey method.
36630 static void pcache1Rekey(
36631 sqlite3_pcache *p,
36632 void *pPg,
36633 unsigned int iOld,
36634 unsigned int iNew
36636 PCache1 *pCache = (PCache1 *)p;
36637 PgHdr1 *pPage = PAGE_TO_PGHDR1(pCache, pPg);
36638 PgHdr1 **pp;
36639 unsigned int h;
36640 assert( pPage->iKey==iOld );
36641 assert( pPage->pCache==pCache );
36643 pcache1EnterMutex(pCache->pGroup);
36645 h = iOld%pCache->nHash;
36646 pp = &pCache->apHash[h];
36647 while( (*pp)!=pPage ){
36648 pp = &(*pp)->pNext;
36650 *pp = pPage->pNext;
36652 h = iNew%pCache->nHash;
36653 pPage->iKey = iNew;
36654 pPage->pNext = pCache->apHash[h];
36655 pCache->apHash[h] = pPage;
36656 if( iNew>pCache->iMaxKey ){
36657 pCache->iMaxKey = iNew;
36660 pcache1LeaveMutex(pCache->pGroup);
36664 ** Implementation of the sqlite3_pcache.xTruncate method.
36666 ** Discard all unpinned pages in the cache with a page number equal to
36667 ** or greater than parameter iLimit. Any pinned pages with a page number
36668 ** equal to or greater than iLimit are implicitly unpinned.
36670 static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
36671 PCache1 *pCache = (PCache1 *)p;
36672 pcache1EnterMutex(pCache->pGroup);
36673 if( iLimit<=pCache->iMaxKey ){
36674 pcache1TruncateUnsafe(pCache, iLimit);
36675 pCache->iMaxKey = iLimit-1;
36677 pcache1LeaveMutex(pCache->pGroup);
36681 ** Implementation of the sqlite3_pcache.xDestroy method.
36683 ** Destroy a cache allocated using pcache1Create().
36685 static void pcache1Destroy(sqlite3_pcache *p){
36686 PCache1 *pCache = (PCache1 *)p;
36687 PGroup *pGroup = pCache->pGroup;
36688 assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
36689 pcache1EnterMutex(pGroup);
36690 pcache1TruncateUnsafe(pCache, 0);
36691 pGroup->nMaxPage -= pCache->nMax;
36692 pGroup->nMinPage -= pCache->nMin;
36693 pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
36694 pcache1EnforceMaxPage(pGroup);
36695 pcache1LeaveMutex(pGroup);
36696 sqlite3_free(pCache->apHash);
36697 sqlite3_free(pCache);
36701 ** This function is called during initialization (sqlite3_initialize()) to
36702 ** install the default pluggable cache module, assuming the user has not
36703 ** already provided an alternative.
36705 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
36706 static const sqlite3_pcache_methods defaultMethods = {
36707 0, /* pArg */
36708 pcache1Init, /* xInit */
36709 pcache1Shutdown, /* xShutdown */
36710 pcache1Create, /* xCreate */
36711 pcache1Cachesize, /* xCachesize */
36712 pcache1Pagecount, /* xPagecount */
36713 pcache1Fetch, /* xFetch */
36714 pcache1Unpin, /* xUnpin */
36715 pcache1Rekey, /* xRekey */
36716 pcache1Truncate, /* xTruncate */
36717 pcache1Destroy /* xDestroy */
36719 sqlite3_config(SQLITE_CONFIG_PCACHE, &defaultMethods);
36722 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
36724 ** This function is called to free superfluous dynamically allocated memory
36725 ** held by the pager system. Memory in use by any SQLite pager allocated
36726 ** by the current thread may be sqlite3_free()ed.
36728 ** nReq is the number of bytes of memory required. Once this much has
36729 ** been released, the function returns. The return value is the total number
36730 ** of bytes of memory released.
36732 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
36733 int nFree = 0;
36734 assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
36735 assert( sqlite3_mutex_notheld(pcache1.mutex) );
36736 if( pcache1.pStart==0 ){
36737 PgHdr1 *p;
36738 pcache1EnterMutex(&pcache1.grp);
36739 while( (nReq<0 || nFree<nReq) && ((p=pcache1.grp.pLruTail)!=0) ){
36740 nFree += pcache1MemSize(PGHDR1_TO_PAGE(p));
36741 pcache1PinPage(p);
36742 pcache1RemoveFromHash(p);
36743 pcache1FreePage(p);
36745 pcache1LeaveMutex(&pcache1.grp);
36747 return nFree;
36749 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
36751 #ifdef SQLITE_TEST
36753 ** This function is used by test procedures to inspect the internal state
36754 ** of the global cache.
36756 SQLITE_PRIVATE void sqlite3PcacheStats(
36757 int *pnCurrent, /* OUT: Total number of pages cached */
36758 int *pnMax, /* OUT: Global maximum cache size */
36759 int *pnMin, /* OUT: Sum of PCache1.nMin for purgeable caches */
36760 int *pnRecyclable /* OUT: Total number of pages available for recycling */
36762 PgHdr1 *p;
36763 int nRecyclable = 0;
36764 for(p=pcache1.grp.pLruHead; p; p=p->pLruNext){
36765 nRecyclable++;
36767 *pnCurrent = pcache1.grp.nCurrentPage;
36768 *pnMax = pcache1.grp.nMaxPage;
36769 *pnMin = pcache1.grp.nMinPage;
36770 *pnRecyclable = nRecyclable;
36772 #endif
36774 /************** End of pcache1.c *********************************************/
36775 /************** Begin file rowset.c ******************************************/
36777 ** 2008 December 3
36779 ** The author disclaims copyright to this source code. In place of
36780 ** a legal notice, here is a blessing:
36782 ** May you do good and not evil.
36783 ** May you find forgiveness for yourself and forgive others.
36784 ** May you share freely, never taking more than you give.
36786 *************************************************************************
36788 ** This module implements an object we call a "RowSet".
36790 ** The RowSet object is a collection of rowids. Rowids
36791 ** are inserted into the RowSet in an arbitrary order. Inserts
36792 ** can be intermixed with tests to see if a given rowid has been
36793 ** previously inserted into the RowSet.
36795 ** After all inserts are finished, it is possible to extract the
36796 ** elements of the RowSet in sorted order. Once this extraction
36797 ** process has started, no new elements may be inserted.
36799 ** Hence, the primitive operations for a RowSet are:
36801 ** CREATE
36802 ** INSERT
36803 ** TEST
36804 ** SMALLEST
36805 ** DESTROY
36807 ** The CREATE and DESTROY primitives are the constructor and destructor,
36808 ** obviously. The INSERT primitive adds a new element to the RowSet.
36809 ** TEST checks to see if an element is already in the RowSet. SMALLEST
36810 ** extracts the least value from the RowSet.
36812 ** The INSERT primitive might allocate additional memory. Memory is
36813 ** allocated in chunks so most INSERTs do no allocation. There is an
36814 ** upper bound on the size of allocated memory. No memory is freed
36815 ** until DESTROY.
36817 ** The TEST primitive includes a "batch" number. The TEST primitive
36818 ** will only see elements that were inserted before the last change
36819 ** in the batch number. In other words, if an INSERT occurs between
36820 ** two TESTs where the TESTs have the same batch nubmer, then the
36821 ** value added by the INSERT will not be visible to the second TEST.
36822 ** The initial batch number is zero, so if the very first TEST contains
36823 ** a non-zero batch number, it will see all prior INSERTs.
36825 ** No INSERTs may occurs after a SMALLEST. An assertion will fail if
36826 ** that is attempted.
36828 ** The cost of an INSERT is roughly constant. (Sometime new memory
36829 ** has to be allocated on an INSERT.) The cost of a TEST with a new
36830 ** batch number is O(NlogN) where N is the number of elements in the RowSet.
36831 ** The cost of a TEST using the same batch number is O(logN). The cost
36832 ** of the first SMALLEST is O(NlogN). Second and subsequent SMALLEST
36833 ** primitives are constant time. The cost of DESTROY is O(N).
36835 ** There is an added cost of O(N) when switching between TEST and
36836 ** SMALLEST primitives.
36841 ** Target size for allocation chunks.
36843 #define ROWSET_ALLOCATION_SIZE 1024
36846 ** The number of rowset entries per allocation chunk.
36848 #define ROWSET_ENTRY_PER_CHUNK \
36849 ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
36852 ** Each entry in a RowSet is an instance of the following object.
36854 struct RowSetEntry {
36855 i64 v; /* ROWID value for this entry */
36856 struct RowSetEntry *pRight; /* Right subtree (larger entries) or list */
36857 struct RowSetEntry *pLeft; /* Left subtree (smaller entries) */
36861 ** RowSetEntry objects are allocated in large chunks (instances of the
36862 ** following structure) to reduce memory allocation overhead. The
36863 ** chunks are kept on a linked list so that they can be deallocated
36864 ** when the RowSet is destroyed.
36866 struct RowSetChunk {
36867 struct RowSetChunk *pNextChunk; /* Next chunk on list of them all */
36868 struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
36872 ** A RowSet in an instance of the following structure.
36874 ** A typedef of this structure if found in sqliteInt.h.
36876 struct RowSet {
36877 struct RowSetChunk *pChunk; /* List of all chunk allocations */
36878 sqlite3 *db; /* The database connection */
36879 struct RowSetEntry *pEntry; /* List of entries using pRight */
36880 struct RowSetEntry *pLast; /* Last entry on the pEntry list */
36881 struct RowSetEntry *pFresh; /* Source of new entry objects */
36882 struct RowSetEntry *pTree; /* Binary tree of entries */
36883 u16 nFresh; /* Number of objects on pFresh */
36884 u8 isSorted; /* True if pEntry is sorted */
36885 u8 iBatch; /* Current insert batch */
36889 ** Turn bulk memory into a RowSet object. N bytes of memory
36890 ** are available at pSpace. The db pointer is used as a memory context
36891 ** for any subsequent allocations that need to occur.
36892 ** Return a pointer to the new RowSet object.
36894 ** It must be the case that N is sufficient to make a Rowset. If not
36895 ** an assertion fault occurs.
36897 ** If N is larger than the minimum, use the surplus as an initial
36898 ** allocation of entries available to be filled.
36900 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
36901 RowSet *p;
36902 assert( N >= ROUND8(sizeof(*p)) );
36903 p = pSpace;
36904 p->pChunk = 0;
36905 p->db = db;
36906 p->pEntry = 0;
36907 p->pLast = 0;
36908 p->pTree = 0;
36909 p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
36910 p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
36911 p->isSorted = 1;
36912 p->iBatch = 0;
36913 return p;
36917 ** Deallocate all chunks from a RowSet. This frees all memory that
36918 ** the RowSet has allocated over its lifetime. This routine is
36919 ** the destructor for the RowSet.
36921 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
36922 struct RowSetChunk *pChunk, *pNextChunk;
36923 for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
36924 pNextChunk = pChunk->pNextChunk;
36925 sqlite3DbFree(p->db, pChunk);
36927 p->pChunk = 0;
36928 p->nFresh = 0;
36929 p->pEntry = 0;
36930 p->pLast = 0;
36931 p->pTree = 0;
36932 p->isSorted = 1;
36936 ** Insert a new value into a RowSet.
36938 ** The mallocFailed flag of the database connection is set if a
36939 ** memory allocation fails.
36941 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
36942 struct RowSetEntry *pEntry; /* The new entry */
36943 struct RowSetEntry *pLast; /* The last prior entry */
36944 assert( p!=0 );
36945 if( p->nFresh==0 ){
36946 struct RowSetChunk *pNew;
36947 pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
36948 if( pNew==0 ){
36949 return;
36951 pNew->pNextChunk = p->pChunk;
36952 p->pChunk = pNew;
36953 p->pFresh = pNew->aEntry;
36954 p->nFresh = ROWSET_ENTRY_PER_CHUNK;
36956 pEntry = p->pFresh++;
36957 p->nFresh--;
36958 pEntry->v = rowid;
36959 pEntry->pRight = 0;
36960 pLast = p->pLast;
36961 if( pLast ){
36962 if( p->isSorted && rowid<=pLast->v ){
36963 p->isSorted = 0;
36965 pLast->pRight = pEntry;
36966 }else{
36967 assert( p->pEntry==0 ); /* Fires if INSERT after SMALLEST */
36968 p->pEntry = pEntry;
36970 p->pLast = pEntry;
36974 ** Merge two lists of RowSetEntry objects. Remove duplicates.
36976 ** The input lists are connected via pRight pointers and are
36977 ** assumed to each already be in sorted order.
36979 static struct RowSetEntry *rowSetMerge(
36980 struct RowSetEntry *pA, /* First sorted list to be merged */
36981 struct RowSetEntry *pB /* Second sorted list to be merged */
36983 struct RowSetEntry head;
36984 struct RowSetEntry *pTail;
36986 pTail = &head;
36987 while( pA && pB ){
36988 assert( pA->pRight==0 || pA->v<=pA->pRight->v );
36989 assert( pB->pRight==0 || pB->v<=pB->pRight->v );
36990 if( pA->v<pB->v ){
36991 pTail->pRight = pA;
36992 pA = pA->pRight;
36993 pTail = pTail->pRight;
36994 }else if( pB->v<pA->v ){
36995 pTail->pRight = pB;
36996 pB = pB->pRight;
36997 pTail = pTail->pRight;
36998 }else{
36999 pA = pA->pRight;
37002 if( pA ){
37003 assert( pA->pRight==0 || pA->v<=pA->pRight->v );
37004 pTail->pRight = pA;
37005 }else{
37006 assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
37007 pTail->pRight = pB;
37009 return head.pRight;
37013 ** Sort all elements on the pEntry list of the RowSet into ascending order.
37015 static void rowSetSort(RowSet *p){
37016 unsigned int i;
37017 struct RowSetEntry *pEntry;
37018 struct RowSetEntry *aBucket[40];
37020 assert( p->isSorted==0 );
37021 memset(aBucket, 0, sizeof(aBucket));
37022 while( p->pEntry ){
37023 pEntry = p->pEntry;
37024 p->pEntry = pEntry->pRight;
37025 pEntry->pRight = 0;
37026 for(i=0; aBucket[i]; i++){
37027 pEntry = rowSetMerge(aBucket[i], pEntry);
37028 aBucket[i] = 0;
37030 aBucket[i] = pEntry;
37032 pEntry = 0;
37033 for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
37034 pEntry = rowSetMerge(pEntry, aBucket[i]);
37036 p->pEntry = pEntry;
37037 p->pLast = 0;
37038 p->isSorted = 1;
37043 ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
37044 ** Convert this tree into a linked list connected by the pRight pointers
37045 ** and return pointers to the first and last elements of the new list.
37047 static void rowSetTreeToList(
37048 struct RowSetEntry *pIn, /* Root of the input tree */
37049 struct RowSetEntry **ppFirst, /* Write head of the output list here */
37050 struct RowSetEntry **ppLast /* Write tail of the output list here */
37052 assert( pIn!=0 );
37053 if( pIn->pLeft ){
37054 struct RowSetEntry *p;
37055 rowSetTreeToList(pIn->pLeft, ppFirst, &p);
37056 p->pRight = pIn;
37057 }else{
37058 *ppFirst = pIn;
37060 if( pIn->pRight ){
37061 rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
37062 }else{
37063 *ppLast = pIn;
37065 assert( (*ppLast)->pRight==0 );
37070 ** Convert a sorted list of elements (connected by pRight) into a binary
37071 ** tree with depth of iDepth. A depth of 1 means the tree contains a single
37072 ** node taken from the head of *ppList. A depth of 2 means a tree with
37073 ** three nodes. And so forth.
37075 ** Use as many entries from the input list as required and update the
37076 ** *ppList to point to the unused elements of the list. If the input
37077 ** list contains too few elements, then construct an incomplete tree
37078 ** and leave *ppList set to NULL.
37080 ** Return a pointer to the root of the constructed binary tree.
37082 static struct RowSetEntry *rowSetNDeepTree(
37083 struct RowSetEntry **ppList,
37084 int iDepth
37086 struct RowSetEntry *p; /* Root of the new tree */
37087 struct RowSetEntry *pLeft; /* Left subtree */
37088 if( *ppList==0 ){
37089 return 0;
37091 if( iDepth==1 ){
37092 p = *ppList;
37093 *ppList = p->pRight;
37094 p->pLeft = p->pRight = 0;
37095 return p;
37097 pLeft = rowSetNDeepTree(ppList, iDepth-1);
37098 p = *ppList;
37099 if( p==0 ){
37100 return pLeft;
37102 p->pLeft = pLeft;
37103 *ppList = p->pRight;
37104 p->pRight = rowSetNDeepTree(ppList, iDepth-1);
37105 return p;
37109 ** Convert a sorted list of elements into a binary tree. Make the tree
37110 ** as deep as it needs to be in order to contain the entire list.
37112 static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
37113 int iDepth; /* Depth of the tree so far */
37114 struct RowSetEntry *p; /* Current tree root */
37115 struct RowSetEntry *pLeft; /* Left subtree */
37117 assert( pList!=0 );
37118 p = pList;
37119 pList = p->pRight;
37120 p->pLeft = p->pRight = 0;
37121 for(iDepth=1; pList; iDepth++){
37122 pLeft = p;
37123 p = pList;
37124 pList = p->pRight;
37125 p->pLeft = pLeft;
37126 p->pRight = rowSetNDeepTree(&pList, iDepth);
37128 return p;
37132 ** Convert the list in p->pEntry into a sorted list if it is not
37133 ** sorted already. If there is a binary tree on p->pTree, then
37134 ** convert it into a list too and merge it into the p->pEntry list.
37136 static void rowSetToList(RowSet *p){
37137 if( !p->isSorted ){
37138 rowSetSort(p);
37140 if( p->pTree ){
37141 struct RowSetEntry *pHead, *pTail;
37142 rowSetTreeToList(p->pTree, &pHead, &pTail);
37143 p->pTree = 0;
37144 p->pEntry = rowSetMerge(p->pEntry, pHead);
37149 ** Extract the smallest element from the RowSet.
37150 ** Write the element into *pRowid. Return 1 on success. Return
37151 ** 0 if the RowSet is already empty.
37153 ** After this routine has been called, the sqlite3RowSetInsert()
37154 ** routine may not be called again.
37156 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
37157 rowSetToList(p);
37158 if( p->pEntry ){
37159 *pRowid = p->pEntry->v;
37160 p->pEntry = p->pEntry->pRight;
37161 if( p->pEntry==0 ){
37162 sqlite3RowSetClear(p);
37164 return 1;
37165 }else{
37166 return 0;
37171 ** Check to see if element iRowid was inserted into the the rowset as
37172 ** part of any insert batch prior to iBatch. Return 1 or 0.
37174 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, u8 iBatch, sqlite3_int64 iRowid){
37175 struct RowSetEntry *p;
37176 if( iBatch!=pRowSet->iBatch ){
37177 if( pRowSet->pEntry ){
37178 rowSetToList(pRowSet);
37179 pRowSet->pTree = rowSetListToTree(pRowSet->pEntry);
37180 pRowSet->pEntry = 0;
37181 pRowSet->pLast = 0;
37183 pRowSet->iBatch = iBatch;
37185 p = pRowSet->pTree;
37186 while( p ){
37187 if( p->v<iRowid ){
37188 p = p->pRight;
37189 }else if( p->v>iRowid ){
37190 p = p->pLeft;
37191 }else{
37192 return 1;
37195 return 0;
37198 /************** End of rowset.c **********************************************/
37199 /************** Begin file pager.c *******************************************/
37201 ** 2001 September 15
37203 ** The author disclaims copyright to this source code. In place of
37204 ** a legal notice, here is a blessing:
37206 ** May you do good and not evil.
37207 ** May you find forgiveness for yourself and forgive others.
37208 ** May you share freely, never taking more than you give.
37210 *************************************************************************
37211 ** This is the implementation of the page cache subsystem or "pager".
37213 ** The pager is used to access a database disk file. It implements
37214 ** atomic commit and rollback through the use of a journal file that
37215 ** is separate from the database file. The pager also implements file
37216 ** locking to prevent two processes from writing the same database
37217 ** file simultaneously, or one process from reading the database while
37218 ** another is writing.
37220 #ifndef SQLITE_OMIT_DISKIO
37221 /************** Include wal.h in the middle of pager.c ***********************/
37222 /************** Begin file wal.h *********************************************/
37224 ** 2010 February 1
37226 ** The author disclaims copyright to this source code. In place of
37227 ** a legal notice, here is a blessing:
37229 ** May you do good and not evil.
37230 ** May you find forgiveness for yourself and forgive others.
37231 ** May you share freely, never taking more than you give.
37233 *************************************************************************
37234 ** This header file defines the interface to the write-ahead logging
37235 ** system. Refer to the comments below and the header comment attached to
37236 ** the implementation of each function in log.c for further details.
37239 #ifndef _WAL_H_
37240 #define _WAL_H_
37243 #ifdef SQLITE_OMIT_WAL
37244 # define sqlite3WalOpen(x,y,z) 0
37245 # define sqlite3WalLimit(x,y)
37246 # define sqlite3WalClose(w,x,y,z) 0
37247 # define sqlite3WalBeginReadTransaction(y,z) 0
37248 # define sqlite3WalEndReadTransaction(z)
37249 # define sqlite3WalRead(v,w,x,y,z) 0
37250 # define sqlite3WalDbsize(y) 0
37251 # define sqlite3WalBeginWriteTransaction(y) 0
37252 # define sqlite3WalEndWriteTransaction(x) 0
37253 # define sqlite3WalUndo(x,y,z) 0
37254 # define sqlite3WalSavepoint(y,z)
37255 # define sqlite3WalSavepointUndo(y,z) 0
37256 # define sqlite3WalFrames(u,v,w,x,y,z) 0
37257 # define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0
37258 # define sqlite3WalCallback(z) 0
37259 # define sqlite3WalExclusiveMode(y,z) 0
37260 # define sqlite3WalHeapMemory(z) 0
37261 #else
37263 #define WAL_SAVEPOINT_NDATA 4
37265 /* Connection to a write-ahead log (WAL) file.
37266 ** There is one object of this type for each pager.
37268 typedef struct Wal Wal;
37270 /* Open and close a connection to a write-ahead log. */
37271 SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
37272 SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
37274 /* Set the limiting size of a WAL file. */
37275 SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
37277 /* Used by readers to open (lock) and close (unlock) a snapshot. A
37278 ** snapshot is like a read-transaction. It is the state of the database
37279 ** at an instant in time. sqlite3WalOpenSnapshot gets a read lock and
37280 ** preserves the current state even if the other threads or processes
37281 ** write to or checkpoint the WAL. sqlite3WalCloseSnapshot() closes the
37282 ** transaction and releases the lock.
37284 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
37285 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
37287 /* Read a page from the write-ahead log, if it is present. */
37288 SQLITE_PRIVATE int sqlite3WalRead(Wal *pWal, Pgno pgno, int *pInWal, int nOut, u8 *pOut);
37290 /* If the WAL is not empty, return the size of the database. */
37291 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
37293 /* Obtain or release the WRITER lock. */
37294 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
37295 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
37297 /* Undo any frames written (but not committed) to the log */
37298 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
37300 /* Return an integer that records the current (uncommitted) write
37301 ** position in the WAL */
37302 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
37304 /* Move the write position of the WAL back to iFrame. Called in
37305 ** response to a ROLLBACK TO command. */
37306 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
37308 /* Write a frame or frames to the log. */
37309 SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
37311 /* Copy pages from the log to the database file */
37312 SQLITE_PRIVATE int sqlite3WalCheckpoint(
37313 Wal *pWal, /* Write-ahead log connection */
37314 int eMode, /* One of PASSIVE, FULL and RESTART */
37315 int (*xBusy)(void*), /* Function to call when busy */
37316 void *pBusyArg, /* Context argument for xBusyHandler */
37317 int sync_flags, /* Flags to sync db file with (or 0) */
37318 int nBuf, /* Size of buffer nBuf */
37319 u8 *zBuf, /* Temporary buffer to use */
37320 int *pnLog, /* OUT: Number of frames in WAL */
37321 int *pnCkpt /* OUT: Number of backfilled frames in WAL */
37324 /* Return the value to pass to a sqlite3_wal_hook callback, the
37325 ** number of frames in the WAL at the point of the last commit since
37326 ** sqlite3WalCallback() was called. If no commits have occurred since
37327 ** the last call, then return 0.
37329 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
37331 /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
37332 ** by the pager layer on the database file.
37334 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
37336 /* Return true if the argument is non-NULL and the WAL module is using
37337 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
37338 ** WAL module is using shared-memory, return false.
37340 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
37342 #endif /* ifndef SQLITE_OMIT_WAL */
37343 #endif /* _WAL_H_ */
37345 /************** End of wal.h *************************************************/
37346 /************** Continuing where we left off in pager.c **********************/
37349 /******************* NOTES ON THE DESIGN OF THE PAGER ************************
37351 ** This comment block describes invariants that hold when using a rollback
37352 ** journal. These invariants do not apply for journal_mode=WAL,
37353 ** journal_mode=MEMORY, or journal_mode=OFF.
37355 ** Within this comment block, a page is deemed to have been synced
37356 ** automatically as soon as it is written when PRAGMA synchronous=OFF.
37357 ** Otherwise, the page is not synced until the xSync method of the VFS
37358 ** is called successfully on the file containing the page.
37360 ** Definition: A page of the database file is said to be "overwriteable" if
37361 ** one or more of the following are true about the page:
37363 ** (a) The original content of the page as it was at the beginning of
37364 ** the transaction has been written into the rollback journal and
37365 ** synced.
37367 ** (b) The page was a freelist leaf page at the start of the transaction.
37369 ** (c) The page number is greater than the largest page that existed in
37370 ** the database file at the start of the transaction.
37372 ** (1) A page of the database file is never overwritten unless one of the
37373 ** following are true:
37375 ** (a) The page and all other pages on the same sector are overwriteable.
37377 ** (b) The atomic page write optimization is enabled, and the entire
37378 ** transaction other than the update of the transaction sequence
37379 ** number consists of a single page change.
37381 ** (2) The content of a page written into the rollback journal exactly matches
37382 ** both the content in the database when the rollback journal was written
37383 ** and the content in the database at the beginning of the current
37384 ** transaction.
37386 ** (3) Writes to the database file are an integer multiple of the page size
37387 ** in length and are aligned on a page boundary.
37389 ** (4) Reads from the database file are either aligned on a page boundary and
37390 ** an integer multiple of the page size in length or are taken from the
37391 ** first 100 bytes of the database file.
37393 ** (5) All writes to the database file are synced prior to the rollback journal
37394 ** being deleted, truncated, or zeroed.
37396 ** (6) If a master journal file is used, then all writes to the database file
37397 ** are synced prior to the master journal being deleted.
37399 ** Definition: Two databases (or the same database at two points it time)
37400 ** are said to be "logically equivalent" if they give the same answer to
37401 ** all queries. Note in particular the the content of freelist leaf
37402 ** pages can be changed arbitarily without effecting the logical equivalence
37403 ** of the database.
37405 ** (7) At any time, if any subset, including the empty set and the total set,
37406 ** of the unsynced changes to a rollback journal are removed and the
37407 ** journal is rolled back, the resulting database file will be logical
37408 ** equivalent to the database file at the beginning of the transaction.
37410 ** (8) When a transaction is rolled back, the xTruncate method of the VFS
37411 ** is called to restore the database file to the same size it was at
37412 ** the beginning of the transaction. (In some VFSes, the xTruncate
37413 ** method is a no-op, but that does not change the fact the SQLite will
37414 ** invoke it.)
37416 ** (9) Whenever the database file is modified, at least one bit in the range
37417 ** of bytes from 24 through 39 inclusive will be changed prior to releasing
37418 ** the EXCLUSIVE lock, thus signaling other connections on the same
37419 ** database to flush their caches.
37421 ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
37422 ** than one billion transactions.
37424 ** (11) A database file is well-formed at the beginning and at the conclusion
37425 ** of every transaction.
37427 ** (12) An EXCLUSIVE lock is held on the database file when writing to
37428 ** the database file.
37430 ** (13) A SHARED lock is held on the database file while reading any
37431 ** content out of the database file.
37433 ******************************************************************************/
37436 ** Macros for troubleshooting. Normally turned off
37438 #if 0
37439 int sqlite3PagerTrace=1; /* True to enable tracing */
37440 #define sqlite3DebugPrintf printf
37441 #define PAGERTRACE(X) if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
37442 #else
37443 #define PAGERTRACE(X)
37444 #endif
37447 ** The following two macros are used within the PAGERTRACE() macros above
37448 ** to print out file-descriptors.
37450 ** PAGERID() takes a pointer to a Pager struct as its argument. The
37451 ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
37452 ** struct as its argument.
37454 #define PAGERID(p) ((int)(p->fd))
37455 #define FILEHANDLEID(fd) ((int)fd)
37458 ** The Pager.eState variable stores the current 'state' of a pager. A
37459 ** pager may be in any one of the seven states shown in the following
37460 ** state diagram.
37462 ** OPEN <------+------+
37463 ** | | |
37464 ** V | |
37465 ** +---------> READER-------+ |
37466 ** | | |
37467 ** | V |
37468 ** |<-------WRITER_LOCKED------> ERROR
37469 ** | | ^
37470 ** | V |
37471 ** |<------WRITER_CACHEMOD-------->|
37472 ** | | |
37473 ** | V |
37474 ** |<-------WRITER_DBMOD---------->|
37475 ** | | |
37476 ** | V |
37477 ** +<------WRITER_FINISHED-------->+
37480 ** List of state transitions and the C [function] that performs each:
37482 ** OPEN -> READER [sqlite3PagerSharedLock]
37483 ** READER -> OPEN [pager_unlock]
37485 ** READER -> WRITER_LOCKED [sqlite3PagerBegin]
37486 ** WRITER_LOCKED -> WRITER_CACHEMOD [pager_open_journal]
37487 ** WRITER_CACHEMOD -> WRITER_DBMOD [syncJournal]
37488 ** WRITER_DBMOD -> WRITER_FINISHED [sqlite3PagerCommitPhaseOne]
37489 ** WRITER_*** -> READER [pager_end_transaction]
37491 ** WRITER_*** -> ERROR [pager_error]
37492 ** ERROR -> OPEN [pager_unlock]
37495 ** OPEN:
37497 ** The pager starts up in this state. Nothing is guaranteed in this
37498 ** state - the file may or may not be locked and the database size is
37499 ** unknown. The database may not be read or written.
37501 ** * No read or write transaction is active.
37502 ** * Any lock, or no lock at all, may be held on the database file.
37503 ** * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
37505 ** READER:
37507 ** In this state all the requirements for reading the database in
37508 ** rollback (non-WAL) mode are met. Unless the pager is (or recently
37509 ** was) in exclusive-locking mode, a user-level read transaction is
37510 ** open. The database size is known in this state.
37512 ** A connection running with locking_mode=normal enters this state when
37513 ** it opens a read-transaction on the database and returns to state
37514 ** OPEN after the read-transaction is completed. However a connection
37515 ** running in locking_mode=exclusive (including temp databases) remains in
37516 ** this state even after the read-transaction is closed. The only way
37517 ** a locking_mode=exclusive connection can transition from READER to OPEN
37518 ** is via the ERROR state (see below).
37520 ** * A read transaction may be active (but a write-transaction cannot).
37521 ** * A SHARED or greater lock is held on the database file.
37522 ** * The dbSize variable may be trusted (even if a user-level read
37523 ** transaction is not active). The dbOrigSize and dbFileSize variables
37524 ** may not be trusted at this point.
37525 ** * If the database is a WAL database, then the WAL connection is open.
37526 ** * Even if a read-transaction is not open, it is guaranteed that
37527 ** there is no hot-journal in the file-system.
37529 ** WRITER_LOCKED:
37531 ** The pager moves to this state from READER when a write-transaction
37532 ** is first opened on the database. In WRITER_LOCKED state, all locks
37533 ** required to start a write-transaction are held, but no actual
37534 ** modifications to the cache or database have taken place.
37536 ** In rollback mode, a RESERVED or (if the transaction was opened with
37537 ** BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
37538 ** moving to this state, but the journal file is not written to or opened
37539 ** to in this state. If the transaction is committed or rolled back while
37540 ** in WRITER_LOCKED state, all that is required is to unlock the database
37541 ** file.
37543 ** IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
37544 ** If the connection is running with locking_mode=exclusive, an attempt
37545 ** is made to obtain an EXCLUSIVE lock on the database file.
37547 ** * A write transaction is active.
37548 ** * If the connection is open in rollback-mode, a RESERVED or greater
37549 ** lock is held on the database file.
37550 ** * If the connection is open in WAL-mode, a WAL write transaction
37551 ** is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
37552 ** called).
37553 ** * The dbSize, dbOrigSize and dbFileSize variables are all valid.
37554 ** * The contents of the pager cache have not been modified.
37555 ** * The journal file may or may not be open.
37556 ** * Nothing (not even the first header) has been written to the journal.
37558 ** WRITER_CACHEMOD:
37560 ** A pager moves from WRITER_LOCKED state to this state when a page is
37561 ** first modified by the upper layer. In rollback mode the journal file
37562 ** is opened (if it is not already open) and a header written to the
37563 ** start of it. The database file on disk has not been modified.
37565 ** * A write transaction is active.
37566 ** * A RESERVED or greater lock is held on the database file.
37567 ** * The journal file is open and the first header has been written
37568 ** to it, but the header has not been synced to disk.
37569 ** * The contents of the page cache have been modified.
37571 ** WRITER_DBMOD:
37573 ** The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
37574 ** when it modifies the contents of the database file. WAL connections
37575 ** never enter this state (since they do not modify the database file,
37576 ** just the log file).
37578 ** * A write transaction is active.
37579 ** * An EXCLUSIVE or greater lock is held on the database file.
37580 ** * The journal file is open and the first header has been written
37581 ** and synced to disk.
37582 ** * The contents of the page cache have been modified (and possibly
37583 ** written to disk).
37585 ** WRITER_FINISHED:
37587 ** It is not possible for a WAL connection to enter this state.
37589 ** A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
37590 ** state after the entire transaction has been successfully written into the
37591 ** database file. In this state the transaction may be committed simply
37592 ** by finalizing the journal file. Once in WRITER_FINISHED state, it is
37593 ** not possible to modify the database further. At this point, the upper
37594 ** layer must either commit or rollback the transaction.
37596 ** * A write transaction is active.
37597 ** * An EXCLUSIVE or greater lock is held on the database file.
37598 ** * All writing and syncing of journal and database data has finished.
37599 ** If no error occured, all that remains is to finalize the journal to
37600 ** commit the transaction. If an error did occur, the caller will need
37601 ** to rollback the transaction.
37603 ** ERROR:
37605 ** The ERROR state is entered when an IO or disk-full error (including
37606 ** SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
37607 ** difficult to be sure that the in-memory pager state (cache contents,
37608 ** db size etc.) are consistent with the contents of the file-system.
37610 ** Temporary pager files may enter the ERROR state, but in-memory pagers
37611 ** cannot.
37613 ** For example, if an IO error occurs while performing a rollback,
37614 ** the contents of the page-cache may be left in an inconsistent state.
37615 ** At this point it would be dangerous to change back to READER state
37616 ** (as usually happens after a rollback). Any subsequent readers might
37617 ** report database corruption (due to the inconsistent cache), and if
37618 ** they upgrade to writers, they may inadvertently corrupt the database
37619 ** file. To avoid this hazard, the pager switches into the ERROR state
37620 ** instead of READER following such an error.
37622 ** Once it has entered the ERROR state, any attempt to use the pager
37623 ** to read or write data returns an error. Eventually, once all
37624 ** outstanding transactions have been abandoned, the pager is able to
37625 ** transition back to OPEN state, discarding the contents of the
37626 ** page-cache and any other in-memory state at the same time. Everything
37627 ** is reloaded from disk (and, if necessary, hot-journal rollback peformed)
37628 ** when a read-transaction is next opened on the pager (transitioning
37629 ** the pager into READER state). At that point the system has recovered
37630 ** from the error.
37632 ** Specifically, the pager jumps into the ERROR state if:
37634 ** 1. An error occurs while attempting a rollback. This happens in
37635 ** function sqlite3PagerRollback().
37637 ** 2. An error occurs while attempting to finalize a journal file
37638 ** following a commit in function sqlite3PagerCommitPhaseTwo().
37640 ** 3. An error occurs while attempting to write to the journal or
37641 ** database file in function pagerStress() in order to free up
37642 ** memory.
37644 ** In other cases, the error is returned to the b-tree layer. The b-tree
37645 ** layer then attempts a rollback operation. If the error condition
37646 ** persists, the pager enters the ERROR state via condition (1) above.
37648 ** Condition (3) is necessary because it can be triggered by a read-only
37649 ** statement executed within a transaction. In this case, if the error
37650 ** code were simply returned to the user, the b-tree layer would not
37651 ** automatically attempt a rollback, as it assumes that an error in a
37652 ** read-only statement cannot leave the pager in an internally inconsistent
37653 ** state.
37655 ** * The Pager.errCode variable is set to something other than SQLITE_OK.
37656 ** * There are one or more outstanding references to pages (after the
37657 ** last reference is dropped the pager should move back to OPEN state).
37658 ** * The pager is not an in-memory pager.
37661 ** Notes:
37663 ** * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
37664 ** connection is open in WAL mode. A WAL connection is always in one
37665 ** of the first four states.
37667 ** * Normally, a connection open in exclusive mode is never in PAGER_OPEN
37668 ** state. There are two exceptions: immediately after exclusive-mode has
37669 ** been turned on (and before any read or write transactions are
37670 ** executed), and when the pager is leaving the "error state".
37672 ** * See also: assert_pager_state().
37674 #define PAGER_OPEN 0
37675 #define PAGER_READER 1
37676 #define PAGER_WRITER_LOCKED 2
37677 #define PAGER_WRITER_CACHEMOD 3
37678 #define PAGER_WRITER_DBMOD 4
37679 #define PAGER_WRITER_FINISHED 5
37680 #define PAGER_ERROR 6
37683 ** The Pager.eLock variable is almost always set to one of the
37684 ** following locking-states, according to the lock currently held on
37685 ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
37686 ** This variable is kept up to date as locks are taken and released by
37687 ** the pagerLockDb() and pagerUnlockDb() wrappers.
37689 ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
37690 ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
37691 ** the operation was successful. In these circumstances pagerLockDb() and
37692 ** pagerUnlockDb() take a conservative approach - eLock is always updated
37693 ** when unlocking the file, and only updated when locking the file if the
37694 ** VFS call is successful. This way, the Pager.eLock variable may be set
37695 ** to a less exclusive (lower) value than the lock that is actually held
37696 ** at the system level, but it is never set to a more exclusive value.
37698 ** This is usually safe. If an xUnlock fails or appears to fail, there may
37699 ** be a few redundant xLock() calls or a lock may be held for longer than
37700 ** required, but nothing really goes wrong.
37702 ** The exception is when the database file is unlocked as the pager moves
37703 ** from ERROR to OPEN state. At this point there may be a hot-journal file
37704 ** in the file-system that needs to be rolled back (as part of a OPEN->SHARED
37705 ** transition, by the same pager or any other). If the call to xUnlock()
37706 ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
37707 ** can confuse the call to xCheckReservedLock() call made later as part
37708 ** of hot-journal detection.
37710 ** xCheckReservedLock() is defined as returning true "if there is a RESERVED
37711 ** lock held by this process or any others". So xCheckReservedLock may
37712 ** return true because the caller itself is holding an EXCLUSIVE lock (but
37713 ** doesn't know it because of a previous error in xUnlock). If this happens
37714 ** a hot-journal may be mistaken for a journal being created by an active
37715 ** transaction in another process, causing SQLite to read from the database
37716 ** without rolling it back.
37718 ** To work around this, if a call to xUnlock() fails when unlocking the
37719 ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
37720 ** is only changed back to a real locking state after a successful call
37721 ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
37722 ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
37723 ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
37724 ** lock on the database file before attempting to roll it back. See function
37725 ** PagerSharedLock() for more detail.
37727 ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
37728 ** PAGER_OPEN state.
37730 #define UNKNOWN_LOCK (EXCLUSIVE_LOCK+1)
37733 ** A macro used for invoking the codec if there is one
37735 #ifdef SQLITE_HAS_CODEC
37736 # define CODEC1(P,D,N,X,E) \
37737 if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
37738 # define CODEC2(P,D,N,X,E,O) \
37739 if( P->xCodec==0 ){ O=(char*)D; }else \
37740 if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
37741 #else
37742 # define CODEC1(P,D,N,X,E) /* NO-OP */
37743 # define CODEC2(P,D,N,X,E,O) O=(char*)D
37744 #endif
37747 ** The maximum allowed sector size. 64KiB. If the xSectorsize() method
37748 ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
37749 ** This could conceivably cause corruption following a power failure on
37750 ** such a system. This is currently an undocumented limit.
37752 #define MAX_SECTOR_SIZE 0x10000
37755 ** An instance of the following structure is allocated for each active
37756 ** savepoint and statement transaction in the system. All such structures
37757 ** are stored in the Pager.aSavepoint[] array, which is allocated and
37758 ** resized using sqlite3Realloc().
37760 ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
37761 ** set to 0. If a journal-header is written into the main journal while
37762 ** the savepoint is active, then iHdrOffset is set to the byte offset
37763 ** immediately following the last journal record written into the main
37764 ** journal before the journal-header. This is required during savepoint
37765 ** rollback (see pagerPlaybackSavepoint()).
37767 typedef struct PagerSavepoint PagerSavepoint;
37768 struct PagerSavepoint {
37769 i64 iOffset; /* Starting offset in main journal */
37770 i64 iHdrOffset; /* See above */
37771 Bitvec *pInSavepoint; /* Set of pages in this savepoint */
37772 Pgno nOrig; /* Original number of pages in file */
37773 Pgno iSubRec; /* Index of first record in sub-journal */
37774 #ifndef SQLITE_OMIT_WAL
37775 u32 aWalData[WAL_SAVEPOINT_NDATA]; /* WAL savepoint context */
37776 #endif
37780 ** A open page cache is an instance of struct Pager. A description of
37781 ** some of the more important member variables follows:
37783 ** eState
37785 ** The current 'state' of the pager object. See the comment and state
37786 ** diagram above for a description of the pager state.
37788 ** eLock
37790 ** For a real on-disk database, the current lock held on the database file -
37791 ** NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
37793 ** For a temporary or in-memory database (neither of which require any
37794 ** locks), this variable is always set to EXCLUSIVE_LOCK. Since such
37795 ** databases always have Pager.exclusiveMode==1, this tricks the pager
37796 ** logic into thinking that it already has all the locks it will ever
37797 ** need (and no reason to release them).
37799 ** In some (obscure) circumstances, this variable may also be set to
37800 ** UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
37801 ** details.
37803 ** changeCountDone
37805 ** This boolean variable is used to make sure that the change-counter
37806 ** (the 4-byte header field at byte offset 24 of the database file) is
37807 ** not updated more often than necessary.
37809 ** It is set to true when the change-counter field is updated, which
37810 ** can only happen if an exclusive lock is held on the database file.
37811 ** It is cleared (set to false) whenever an exclusive lock is
37812 ** relinquished on the database file. Each time a transaction is committed,
37813 ** The changeCountDone flag is inspected. If it is true, the work of
37814 ** updating the change-counter is omitted for the current transaction.
37816 ** This mechanism means that when running in exclusive mode, a connection
37817 ** need only update the change-counter once, for the first transaction
37818 ** committed.
37820 ** setMaster
37822 ** When PagerCommitPhaseOne() is called to commit a transaction, it may
37823 ** (or may not) specify a master-journal name to be written into the
37824 ** journal file before it is synced to disk.
37826 ** Whether or not a journal file contains a master-journal pointer affects
37827 ** the way in which the journal file is finalized after the transaction is
37828 ** committed or rolled back when running in "journal_mode=PERSIST" mode.
37829 ** If a journal file does not contain a master-journal pointer, it is
37830 ** finalized by overwriting the first journal header with zeroes. If
37831 ** it does contain a master-journal pointer the journal file is finalized
37832 ** by truncating it to zero bytes, just as if the connection were
37833 ** running in "journal_mode=truncate" mode.
37835 ** Journal files that contain master journal pointers cannot be finalized
37836 ** simply by overwriting the first journal-header with zeroes, as the
37837 ** master journal pointer could interfere with hot-journal rollback of any
37838 ** subsequently interrupted transaction that reuses the journal file.
37840 ** The flag is cleared as soon as the journal file is finalized (either
37841 ** by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
37842 ** journal file from being successfully finalized, the setMaster flag
37843 ** is cleared anyway (and the pager will move to ERROR state).
37845 ** doNotSpill, doNotSyncSpill
37847 ** These two boolean variables control the behaviour of cache-spills
37848 ** (calls made by the pcache module to the pagerStress() routine to
37849 ** write cached data to the file-system in order to free up memory).
37851 ** When doNotSpill is non-zero, writing to the database from pagerStress()
37852 ** is disabled altogether. This is done in a very obscure case that
37853 ** comes up during savepoint rollback that requires the pcache module
37854 ** to allocate a new page to prevent the journal file from being written
37855 ** while it is being traversed by code in pager_playback().
37857 ** If doNotSyncSpill is non-zero, writing to the database from pagerStress()
37858 ** is permitted, but syncing the journal file is not. This flag is set
37859 ** by sqlite3PagerWrite() when the file-system sector-size is larger than
37860 ** the database page-size in order to prevent a journal sync from happening
37861 ** in between the journalling of two pages on the same sector.
37863 ** subjInMemory
37865 ** This is a boolean variable. If true, then any required sub-journal
37866 ** is opened as an in-memory journal file. If false, then in-memory
37867 ** sub-journals are only used for in-memory pager files.
37869 ** This variable is updated by the upper layer each time a new
37870 ** write-transaction is opened.
37872 ** dbSize, dbOrigSize, dbFileSize
37874 ** Variable dbSize is set to the number of pages in the database file.
37875 ** It is valid in PAGER_READER and higher states (all states except for
37876 ** OPEN and ERROR).
37878 ** dbSize is set based on the size of the database file, which may be
37879 ** larger than the size of the database (the value stored at offset
37880 ** 28 of the database header by the btree). If the size of the file
37881 ** is not an integer multiple of the page-size, the value stored in
37882 ** dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
37883 ** Except, any file that is greater than 0 bytes in size is considered
37884 ** to have at least one page. (i.e. a 1KB file with 2K page-size leads
37885 ** to dbSize==1).
37887 ** During a write-transaction, if pages with page-numbers greater than
37888 ** dbSize are modified in the cache, dbSize is updated accordingly.
37889 ** Similarly, if the database is truncated using PagerTruncateImage(),
37890 ** dbSize is updated.
37892 ** Variables dbOrigSize and dbFileSize are valid in states
37893 ** PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
37894 ** variable at the start of the transaction. It is used during rollback,
37895 ** and to determine whether or not pages need to be journalled before
37896 ** being modified.
37898 ** Throughout a write-transaction, dbFileSize contains the size of
37899 ** the file on disk in pages. It is set to a copy of dbSize when the
37900 ** write-transaction is first opened, and updated when VFS calls are made
37901 ** to write or truncate the database file on disk.
37903 ** The only reason the dbFileSize variable is required is to suppress
37904 ** unnecessary calls to xTruncate() after committing a transaction. If,
37905 ** when a transaction is committed, the dbFileSize variable indicates
37906 ** that the database file is larger than the database image (Pager.dbSize),
37907 ** pager_truncate() is called. The pager_truncate() call uses xFilesize()
37908 ** to measure the database file on disk, and then truncates it if required.
37909 ** dbFileSize is not used when rolling back a transaction. In this case
37910 ** pager_truncate() is called unconditionally (which means there may be
37911 ** a call to xFilesize() that is not strictly required). In either case,
37912 ** pager_truncate() may cause the file to become smaller or larger.
37914 ** dbHintSize
37916 ** The dbHintSize variable is used to limit the number of calls made to
37917 ** the VFS xFileControl(FCNTL_SIZE_HINT) method.
37919 ** dbHintSize is set to a copy of the dbSize variable when a
37920 ** write-transaction is opened (at the same time as dbFileSize and
37921 ** dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
37922 ** dbHintSize is increased to the number of pages that correspond to the
37923 ** size-hint passed to the method call. See pager_write_pagelist() for
37924 ** details.
37926 ** errCode
37928 ** The Pager.errCode variable is only ever used in PAGER_ERROR state. It
37929 ** is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
37930 ** is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
37931 ** sub-codes.
37933 struct Pager {
37934 sqlite3_vfs *pVfs; /* OS functions to use for IO */
37935 u8 exclusiveMode; /* Boolean. True if locking_mode==EXCLUSIVE */
37936 u8 journalMode; /* One of the PAGER_JOURNALMODE_* values */
37937 u8 useJournal; /* Use a rollback journal on this file */
37938 u8 noReadlock; /* Do not bother to obtain readlocks */
37939 u8 noSync; /* Do not sync the journal if true */
37940 u8 fullSync; /* Do extra syncs of the journal for robustness */
37941 u8 ckptSyncFlags; /* SYNC_NORMAL or SYNC_FULL for checkpoint */
37942 u8 syncFlags; /* SYNC_NORMAL or SYNC_FULL otherwise */
37943 u8 tempFile; /* zFilename is a temporary file */
37944 u8 readOnly; /* True for a read-only database */
37945 u8 memDb; /* True to inhibit all file I/O */
37947 /**************************************************************************
37948 ** The following block contains those class members that change during
37949 ** routine opertion. Class members not in this block are either fixed
37950 ** when the pager is first created or else only change when there is a
37951 ** significant mode change (such as changing the page_size, locking_mode,
37952 ** or the journal_mode). From another view, these class members describe
37953 ** the "state" of the pager, while other class members describe the
37954 ** "configuration" of the pager.
37956 u8 eState; /* Pager state (OPEN, READER, WRITER_LOCKED..) */
37957 u8 eLock; /* Current lock held on database file */
37958 u8 changeCountDone; /* Set after incrementing the change-counter */
37959 u8 setMaster; /* True if a m-j name has been written to jrnl */
37960 u8 doNotSpill; /* Do not spill the cache when non-zero */
37961 u8 doNotSyncSpill; /* Do not do a spill that requires jrnl sync */
37962 u8 subjInMemory; /* True to use in-memory sub-journals */
37963 Pgno dbSize; /* Number of pages in the database */
37964 Pgno dbOrigSize; /* dbSize before the current transaction */
37965 Pgno dbFileSize; /* Number of pages in the database file */
37966 Pgno dbHintSize; /* Value passed to FCNTL_SIZE_HINT call */
37967 int errCode; /* One of several kinds of errors */
37968 int nRec; /* Pages journalled since last j-header written */
37969 u32 cksumInit; /* Quasi-random value added to every checksum */
37970 u32 nSubRec; /* Number of records written to sub-journal */
37971 Bitvec *pInJournal; /* One bit for each page in the database file */
37972 sqlite3_file *fd; /* File descriptor for database */
37973 sqlite3_file *jfd; /* File descriptor for main journal */
37974 sqlite3_file *sjfd; /* File descriptor for sub-journal */
37975 i64 journalOff; /* Current write offset in the journal file */
37976 i64 journalHdr; /* Byte offset to previous journal header */
37977 sqlite3_backup *pBackup; /* Pointer to list of ongoing backup processes */
37978 PagerSavepoint *aSavepoint; /* Array of active savepoints */
37979 int nSavepoint; /* Number of elements in aSavepoint[] */
37980 char dbFileVers[16]; /* Changes whenever database file changes */
37982 ** End of the routinely-changing class members
37983 ***************************************************************************/
37985 u16 nExtra; /* Add this many bytes to each in-memory page */
37986 i16 nReserve; /* Number of unused bytes at end of each page */
37987 u32 vfsFlags; /* Flags for sqlite3_vfs.xOpen() */
37988 u32 sectorSize; /* Assumed sector size during rollback */
37989 int pageSize; /* Number of bytes in a page */
37990 Pgno mxPgno; /* Maximum allowed size of the database */
37991 i64 journalSizeLimit; /* Size limit for persistent journal files */
37992 char *zFilename; /* Name of the database file */
37993 char *zJournal; /* Name of the journal file */
37994 int (*xBusyHandler)(void*); /* Function to call when busy */
37995 void *pBusyHandlerArg; /* Context argument for xBusyHandler */
37996 int nHit, nMiss; /* Total cache hits and misses */
37997 #ifdef SQLITE_TEST
37998 int nRead, nWrite; /* Database pages read/written */
37999 #endif
38000 void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
38001 #ifdef SQLITE_HAS_CODEC
38002 void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
38003 void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
38004 void (*xCodecFree)(void*); /* Destructor for the codec */
38005 void *pCodec; /* First argument to xCodec... methods */
38006 #endif
38007 char *pTmpSpace; /* Pager.pageSize bytes of space for tmp use */
38008 PCache *pPCache; /* Pointer to page cache object */
38009 #ifndef SQLITE_OMIT_WAL
38010 Wal *pWal; /* Write-ahead log used by "journal_mode=wal" */
38011 char *zWal; /* File name for write-ahead log */
38012 #endif
38016 ** The following global variables hold counters used for
38017 ** testing purposes only. These variables do not exist in
38018 ** a non-testing build. These variables are not thread-safe.
38020 #ifdef SQLITE_TEST
38021 SQLITE_API int sqlite3_pager_readdb_count = 0; /* Number of full pages read from DB */
38022 SQLITE_API int sqlite3_pager_writedb_count = 0; /* Number of full pages written to DB */
38023 SQLITE_API int sqlite3_pager_writej_count = 0; /* Number of pages written to journal */
38024 # define PAGER_INCR(v) v++
38025 #else
38026 # define PAGER_INCR(v)
38027 #endif
38032 ** Journal files begin with the following magic string. The data
38033 ** was obtained from /dev/random. It is used only as a sanity check.
38035 ** Since version 2.8.0, the journal format contains additional sanity
38036 ** checking information. If the power fails while the journal is being
38037 ** written, semi-random garbage data might appear in the journal
38038 ** file after power is restored. If an attempt is then made
38039 ** to roll the journal back, the database could be corrupted. The additional
38040 ** sanity checking data is an attempt to discover the garbage in the
38041 ** journal and ignore it.
38043 ** The sanity checking information for the new journal format consists
38044 ** of a 32-bit checksum on each page of data. The checksum covers both
38045 ** the page number and the pPager->pageSize bytes of data for the page.
38046 ** This cksum is initialized to a 32-bit random value that appears in the
38047 ** journal file right after the header. The random initializer is important,
38048 ** because garbage data that appears at the end of a journal is likely
38049 ** data that was once in other files that have now been deleted. If the
38050 ** garbage data came from an obsolete journal file, the checksums might
38051 ** be correct. But by initializing the checksum to random value which
38052 ** is different for every journal, we minimize that risk.
38054 static const unsigned char aJournalMagic[] = {
38055 0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
38059 ** The size of the of each page record in the journal is given by
38060 ** the following macro.
38062 #define JOURNAL_PG_SZ(pPager) ((pPager->pageSize) + 8)
38065 ** The journal header size for this pager. This is usually the same
38066 ** size as a single disk sector. See also setSectorSize().
38068 #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
38071 ** The macro MEMDB is true if we are dealing with an in-memory database.
38072 ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
38073 ** the value of MEMDB will be a constant and the compiler will optimize
38074 ** out code that would never execute.
38076 #ifdef SQLITE_OMIT_MEMORYDB
38077 # define MEMDB 0
38078 #else
38079 # define MEMDB pPager->memDb
38080 #endif
38083 ** The maximum legal page number is (2^31 - 1).
38085 #define PAGER_MAX_PGNO 2147483647
38088 ** The argument to this macro is a file descriptor (type sqlite3_file*).
38089 ** Return 0 if it is not open, or non-zero (but not 1) if it is.
38091 ** This is so that expressions can be written as:
38093 ** if( isOpen(pPager->jfd) ){ ...
38095 ** instead of
38097 ** if( pPager->jfd->pMethods ){ ...
38099 #define isOpen(pFd) ((pFd)->pMethods)
38102 ** Return true if this pager uses a write-ahead log instead of the usual
38103 ** rollback journal. Otherwise false.
38105 #ifndef SQLITE_OMIT_WAL
38106 static int pagerUseWal(Pager *pPager){
38107 return (pPager->pWal!=0);
38109 #else
38110 # define pagerUseWal(x) 0
38111 # define pagerRollbackWal(x) 0
38112 # define pagerWalFrames(v,w,x,y,z) 0
38113 # define pagerOpenWalIfPresent(z) SQLITE_OK
38114 # define pagerBeginReadTransaction(z) SQLITE_OK
38115 #endif
38117 #ifndef NDEBUG
38119 ** Usage:
38121 ** assert( assert_pager_state(pPager) );
38123 ** This function runs many asserts to try to find inconsistencies in
38124 ** the internal state of the Pager object.
38126 static int assert_pager_state(Pager *p){
38127 Pager *pPager = p;
38129 /* State must be valid. */
38130 assert( p->eState==PAGER_OPEN
38131 || p->eState==PAGER_READER
38132 || p->eState==PAGER_WRITER_LOCKED
38133 || p->eState==PAGER_WRITER_CACHEMOD
38134 || p->eState==PAGER_WRITER_DBMOD
38135 || p->eState==PAGER_WRITER_FINISHED
38136 || p->eState==PAGER_ERROR
38139 /* Regardless of the current state, a temp-file connection always behaves
38140 ** as if it has an exclusive lock on the database file. It never updates
38141 ** the change-counter field, so the changeCountDone flag is always set.
38143 assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
38144 assert( p->tempFile==0 || pPager->changeCountDone );
38146 /* If the useJournal flag is clear, the journal-mode must be "OFF".
38147 ** And if the journal-mode is "OFF", the journal file must not be open.
38149 assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
38150 assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
38152 /* Check that MEMDB implies noSync. And an in-memory journal. Since
38153 ** this means an in-memory pager performs no IO at all, it cannot encounter
38154 ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
38155 ** a journal file. (although the in-memory journal implementation may
38156 ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
38157 ** is therefore not possible for an in-memory pager to enter the ERROR
38158 ** state.
38160 if( MEMDB ){
38161 assert( p->noSync );
38162 assert( p->journalMode==PAGER_JOURNALMODE_OFF
38163 || p->journalMode==PAGER_JOURNALMODE_MEMORY
38165 assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
38166 assert( pagerUseWal(p)==0 );
38169 /* If changeCountDone is set, a RESERVED lock or greater must be held
38170 ** on the file.
38172 assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
38173 assert( p->eLock!=PENDING_LOCK );
38175 switch( p->eState ){
38176 case PAGER_OPEN:
38177 assert( !MEMDB );
38178 assert( pPager->errCode==SQLITE_OK );
38179 assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
38180 break;
38182 case PAGER_READER:
38183 assert( pPager->errCode==SQLITE_OK );
38184 assert( p->eLock!=UNKNOWN_LOCK );
38185 assert( p->eLock>=SHARED_LOCK || p->noReadlock );
38186 break;
38188 case PAGER_WRITER_LOCKED:
38189 assert( p->eLock!=UNKNOWN_LOCK );
38190 assert( pPager->errCode==SQLITE_OK );
38191 if( !pagerUseWal(pPager) ){
38192 assert( p->eLock>=RESERVED_LOCK );
38194 assert( pPager->dbSize==pPager->dbOrigSize );
38195 assert( pPager->dbOrigSize==pPager->dbFileSize );
38196 assert( pPager->dbOrigSize==pPager->dbHintSize );
38197 assert( pPager->setMaster==0 );
38198 break;
38200 case PAGER_WRITER_CACHEMOD:
38201 assert( p->eLock!=UNKNOWN_LOCK );
38202 assert( pPager->errCode==SQLITE_OK );
38203 if( !pagerUseWal(pPager) ){
38204 /* It is possible that if journal_mode=wal here that neither the
38205 ** journal file nor the WAL file are open. This happens during
38206 ** a rollback transaction that switches from journal_mode=off
38207 ** to journal_mode=wal.
38209 assert( p->eLock>=RESERVED_LOCK );
38210 assert( isOpen(p->jfd)
38211 || p->journalMode==PAGER_JOURNALMODE_OFF
38212 || p->journalMode==PAGER_JOURNALMODE_WAL
38215 assert( pPager->dbOrigSize==pPager->dbFileSize );
38216 assert( pPager->dbOrigSize==pPager->dbHintSize );
38217 break;
38219 case PAGER_WRITER_DBMOD:
38220 assert( p->eLock==EXCLUSIVE_LOCK );
38221 assert( pPager->errCode==SQLITE_OK );
38222 assert( !pagerUseWal(pPager) );
38223 assert( p->eLock>=EXCLUSIVE_LOCK );
38224 assert( isOpen(p->jfd)
38225 || p->journalMode==PAGER_JOURNALMODE_OFF
38226 || p->journalMode==PAGER_JOURNALMODE_WAL
38228 assert( pPager->dbOrigSize<=pPager->dbHintSize );
38229 break;
38231 case PAGER_WRITER_FINISHED:
38232 assert( p->eLock==EXCLUSIVE_LOCK );
38233 assert( pPager->errCode==SQLITE_OK );
38234 assert( !pagerUseWal(pPager) );
38235 assert( isOpen(p->jfd)
38236 || p->journalMode==PAGER_JOURNALMODE_OFF
38237 || p->journalMode==PAGER_JOURNALMODE_WAL
38239 break;
38241 case PAGER_ERROR:
38242 /* There must be at least one outstanding reference to the pager if
38243 ** in ERROR state. Otherwise the pager should have already dropped
38244 ** back to OPEN state.
38246 assert( pPager->errCode!=SQLITE_OK );
38247 assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
38248 break;
38251 return 1;
38253 #endif /* ifndef NDEBUG */
38255 #ifdef SQLITE_DEBUG
38257 ** Return a pointer to a human readable string in a static buffer
38258 ** containing the state of the Pager object passed as an argument. This
38259 ** is intended to be used within debuggers. For example, as an alternative
38260 ** to "print *pPager" in gdb:
38262 ** (gdb) printf "%s", print_pager_state(pPager)
38264 static char *print_pager_state(Pager *p){
38265 static char zRet[1024];
38267 sqlite3_snprintf(1024, zRet,
38268 "Filename: %s\n"
38269 "State: %s errCode=%d\n"
38270 "Lock: %s\n"
38271 "Locking mode: locking_mode=%s\n"
38272 "Journal mode: journal_mode=%s\n"
38273 "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
38274 "Journal: journalOff=%lld journalHdr=%lld\n"
38275 "Size: dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
38276 , p->zFilename
38277 , p->eState==PAGER_OPEN ? "OPEN" :
38278 p->eState==PAGER_READER ? "READER" :
38279 p->eState==PAGER_WRITER_LOCKED ? "WRITER_LOCKED" :
38280 p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
38281 p->eState==PAGER_WRITER_DBMOD ? "WRITER_DBMOD" :
38282 p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
38283 p->eState==PAGER_ERROR ? "ERROR" : "?error?"
38284 , (int)p->errCode
38285 , p->eLock==NO_LOCK ? "NO_LOCK" :
38286 p->eLock==RESERVED_LOCK ? "RESERVED" :
38287 p->eLock==EXCLUSIVE_LOCK ? "EXCLUSIVE" :
38288 p->eLock==SHARED_LOCK ? "SHARED" :
38289 p->eLock==UNKNOWN_LOCK ? "UNKNOWN" : "?error?"
38290 , p->exclusiveMode ? "exclusive" : "normal"
38291 , p->journalMode==PAGER_JOURNALMODE_MEMORY ? "memory" :
38292 p->journalMode==PAGER_JOURNALMODE_OFF ? "off" :
38293 p->journalMode==PAGER_JOURNALMODE_DELETE ? "delete" :
38294 p->journalMode==PAGER_JOURNALMODE_PERSIST ? "persist" :
38295 p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
38296 p->journalMode==PAGER_JOURNALMODE_WAL ? "wal" : "?error?"
38297 , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
38298 , p->journalOff, p->journalHdr
38299 , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
38302 return zRet;
38304 #endif
38307 ** Return true if it is necessary to write page *pPg into the sub-journal.
38308 ** A page needs to be written into the sub-journal if there exists one
38309 ** or more open savepoints for which:
38311 ** * The page-number is less than or equal to PagerSavepoint.nOrig, and
38312 ** * The bit corresponding to the page-number is not set in
38313 ** PagerSavepoint.pInSavepoint.
38315 static int subjRequiresPage(PgHdr *pPg){
38316 Pgno pgno = pPg->pgno;
38317 Pager *pPager = pPg->pPager;
38318 int i;
38319 for(i=0; i<pPager->nSavepoint; i++){
38320 PagerSavepoint *p = &pPager->aSavepoint[i];
38321 if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
38322 return 1;
38325 return 0;
38329 ** Return true if the page is already in the journal file.
38331 static int pageInJournal(PgHdr *pPg){
38332 return sqlite3BitvecTest(pPg->pPager->pInJournal, pPg->pgno);
38336 ** Read a 32-bit integer from the given file descriptor. Store the integer
38337 ** that is read in *pRes. Return SQLITE_OK if everything worked, or an
38338 ** error code is something goes wrong.
38340 ** All values are stored on disk as big-endian.
38342 static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
38343 unsigned char ac[4];
38344 int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
38345 if( rc==SQLITE_OK ){
38346 *pRes = sqlite3Get4byte(ac);
38348 return rc;
38352 ** Write a 32-bit integer into a string buffer in big-endian byte order.
38354 #define put32bits(A,B) sqlite3Put4byte((u8*)A,B)
38358 ** Write a 32-bit integer into the given file descriptor. Return SQLITE_OK
38359 ** on success or an error code is something goes wrong.
38361 static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
38362 char ac[4];
38363 put32bits(ac, val);
38364 return sqlite3OsWrite(fd, ac, 4, offset);
38368 ** Unlock the database file to level eLock, which must be either NO_LOCK
38369 ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
38370 ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
38372 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
38373 ** called, do not modify it. See the comment above the #define of
38374 ** UNKNOWN_LOCK for an explanation of this.
38376 static int pagerUnlockDb(Pager *pPager, int eLock){
38377 int rc = SQLITE_OK;
38379 assert( !pPager->exclusiveMode || pPager->eLock==eLock );
38380 assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
38381 assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
38382 if( isOpen(pPager->fd) ){
38383 assert( pPager->eLock>=eLock );
38384 rc = sqlite3OsUnlock(pPager->fd, eLock);
38385 if( pPager->eLock!=UNKNOWN_LOCK ){
38386 pPager->eLock = (u8)eLock;
38388 IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
38390 return rc;
38394 ** Lock the database file to level eLock, which must be either SHARED_LOCK,
38395 ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
38396 ** Pager.eLock variable to the new locking state.
38398 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
38399 ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
38400 ** See the comment above the #define of UNKNOWN_LOCK for an explanation
38401 ** of this.
38403 static int pagerLockDb(Pager *pPager, int eLock){
38404 int rc = SQLITE_OK;
38406 assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
38407 if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
38408 rc = sqlite3OsLock(pPager->fd, eLock);
38409 if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
38410 pPager->eLock = (u8)eLock;
38411 IOTRACE(("LOCK %p %d\n", pPager, eLock))
38414 return rc;
38418 ** This function determines whether or not the atomic-write optimization
38419 ** can be used with this pager. The optimization can be used if:
38421 ** (a) the value returned by OsDeviceCharacteristics() indicates that
38422 ** a database page may be written atomically, and
38423 ** (b) the value returned by OsSectorSize() is less than or equal
38424 ** to the page size.
38426 ** The optimization is also always enabled for temporary files. It is
38427 ** an error to call this function if pPager is opened on an in-memory
38428 ** database.
38430 ** If the optimization cannot be used, 0 is returned. If it can be used,
38431 ** then the value returned is the size of the journal file when it
38432 ** contains rollback data for exactly one page.
38434 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
38435 static int jrnlBufferSize(Pager *pPager){
38436 assert( !MEMDB );
38437 if( !pPager->tempFile ){
38438 int dc; /* Device characteristics */
38439 int nSector; /* Sector size */
38440 int szPage; /* Page size */
38442 assert( isOpen(pPager->fd) );
38443 dc = sqlite3OsDeviceCharacteristics(pPager->fd);
38444 nSector = pPager->sectorSize;
38445 szPage = pPager->pageSize;
38447 assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
38448 assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
38449 if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
38450 return 0;
38454 return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
38456 #endif
38459 ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
38460 ** on the cache using a hash function. This is used for testing
38461 ** and debugging only.
38463 #ifdef SQLITE_CHECK_PAGES
38465 ** Return a 32-bit hash of the page data for pPage.
38467 static u32 pager_datahash(int nByte, unsigned char *pData){
38468 u32 hash = 0;
38469 int i;
38470 for(i=0; i<nByte; i++){
38471 hash = (hash*1039) + pData[i];
38473 return hash;
38475 static u32 pager_pagehash(PgHdr *pPage){
38476 return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
38478 static void pager_set_pagehash(PgHdr *pPage){
38479 pPage->pageHash = pager_pagehash(pPage);
38483 ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
38484 ** is defined, and NDEBUG is not defined, an assert() statement checks
38485 ** that the page is either dirty or still matches the calculated page-hash.
38487 #define CHECK_PAGE(x) checkPage(x)
38488 static void checkPage(PgHdr *pPg){
38489 Pager *pPager = pPg->pPager;
38490 assert( pPager->eState!=PAGER_ERROR );
38491 assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
38494 #else
38495 #define pager_datahash(X,Y) 0
38496 #define pager_pagehash(X) 0
38497 #define pager_set_pagehash(X)
38498 #define CHECK_PAGE(x)
38499 #endif /* SQLITE_CHECK_PAGES */
38502 ** When this is called the journal file for pager pPager must be open.
38503 ** This function attempts to read a master journal file name from the
38504 ** end of the file and, if successful, copies it into memory supplied
38505 ** by the caller. See comments above writeMasterJournal() for the format
38506 ** used to store a master journal file name at the end of a journal file.
38508 ** zMaster must point to a buffer of at least nMaster bytes allocated by
38509 ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
38510 ** enough space to write the master journal name). If the master journal
38511 ** name in the journal is longer than nMaster bytes (including a
38512 ** nul-terminator), then this is handled as if no master journal name
38513 ** were present in the journal.
38515 ** If a master journal file name is present at the end of the journal
38516 ** file, then it is copied into the buffer pointed to by zMaster. A
38517 ** nul-terminator byte is appended to the buffer following the master
38518 ** journal file name.
38520 ** If it is determined that no master journal file name is present
38521 ** zMaster[0] is set to 0 and SQLITE_OK returned.
38523 ** If an error occurs while reading from the journal file, an SQLite
38524 ** error code is returned.
38526 static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
38527 int rc; /* Return code */
38528 u32 len; /* Length in bytes of master journal name */
38529 i64 szJ; /* Total size in bytes of journal file pJrnl */
38530 u32 cksum; /* MJ checksum value read from journal */
38531 u32 u; /* Unsigned loop counter */
38532 unsigned char aMagic[8]; /* A buffer to hold the magic header */
38533 zMaster[0] = '\0';
38535 if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
38536 || szJ<16
38537 || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
38538 || len>=nMaster
38539 || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
38540 || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
38541 || memcmp(aMagic, aJournalMagic, 8)
38542 || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
38544 return rc;
38547 /* See if the checksum matches the master journal name */
38548 for(u=0; u<len; u++){
38549 cksum -= zMaster[u];
38551 if( cksum ){
38552 /* If the checksum doesn't add up, then one or more of the disk sectors
38553 ** containing the master journal filename is corrupted. This means
38554 ** definitely roll back, so just return SQLITE_OK and report a (nul)
38555 ** master-journal filename.
38557 len = 0;
38559 zMaster[len] = '\0';
38561 return SQLITE_OK;
38565 ** Return the offset of the sector boundary at or immediately
38566 ** following the value in pPager->journalOff, assuming a sector
38567 ** size of pPager->sectorSize bytes.
38569 ** i.e for a sector size of 512:
38571 ** Pager.journalOff Return value
38572 ** ---------------------------------------
38573 ** 0 0
38574 ** 512 512
38575 ** 100 512
38576 ** 2000 2048
38579 static i64 journalHdrOffset(Pager *pPager){
38580 i64 offset = 0;
38581 i64 c = pPager->journalOff;
38582 if( c ){
38583 offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
38585 assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
38586 assert( offset>=c );
38587 assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
38588 return offset;
38592 ** The journal file must be open when this function is called.
38594 ** This function is a no-op if the journal file has not been written to
38595 ** within the current transaction (i.e. if Pager.journalOff==0).
38597 ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
38598 ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
38599 ** zero the 28-byte header at the start of the journal file. In either case,
38600 ** if the pager is not in no-sync mode, sync the journal file immediately
38601 ** after writing or truncating it.
38603 ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
38604 ** following the truncation or zeroing described above the size of the
38605 ** journal file in bytes is larger than this value, then truncate the
38606 ** journal file to Pager.journalSizeLimit bytes. The journal file does
38607 ** not need to be synced following this operation.
38609 ** If an IO error occurs, abandon processing and return the IO error code.
38610 ** Otherwise, return SQLITE_OK.
38612 static int zeroJournalHdr(Pager *pPager, int doTruncate){
38613 int rc = SQLITE_OK; /* Return code */
38614 assert( isOpen(pPager->jfd) );
38615 if( pPager->journalOff ){
38616 const i64 iLimit = pPager->journalSizeLimit; /* Local cache of jsl */
38618 IOTRACE(("JZEROHDR %p\n", pPager))
38619 if( doTruncate || iLimit==0 ){
38620 rc = sqlite3OsTruncate(pPager->jfd, 0);
38621 }else{
38622 static const char zeroHdr[28] = {0};
38623 rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
38625 if( rc==SQLITE_OK && !pPager->noSync ){
38626 rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
38629 /* At this point the transaction is committed but the write lock
38630 ** is still held on the file. If there is a size limit configured for
38631 ** the persistent journal and the journal file currently consumes more
38632 ** space than that limit allows for, truncate it now. There is no need
38633 ** to sync the file following this operation.
38635 if( rc==SQLITE_OK && iLimit>0 ){
38636 i64 sz;
38637 rc = sqlite3OsFileSize(pPager->jfd, &sz);
38638 if( rc==SQLITE_OK && sz>iLimit ){
38639 rc = sqlite3OsTruncate(pPager->jfd, iLimit);
38643 return rc;
38647 ** The journal file must be open when this routine is called. A journal
38648 ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
38649 ** current location.
38651 ** The format for the journal header is as follows:
38652 ** - 8 bytes: Magic identifying journal format.
38653 ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
38654 ** - 4 bytes: Random number used for page hash.
38655 ** - 4 bytes: Initial database page count.
38656 ** - 4 bytes: Sector size used by the process that wrote this journal.
38657 ** - 4 bytes: Database page size.
38659 ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
38661 static int writeJournalHdr(Pager *pPager){
38662 int rc = SQLITE_OK; /* Return code */
38663 char *zHeader = pPager->pTmpSpace; /* Temporary space used to build header */
38664 u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
38665 u32 nWrite; /* Bytes of header sector written */
38666 int ii; /* Loop counter */
38668 assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
38670 if( nHeader>JOURNAL_HDR_SZ(pPager) ){
38671 nHeader = JOURNAL_HDR_SZ(pPager);
38674 /* If there are active savepoints and any of them were created
38675 ** since the most recent journal header was written, update the
38676 ** PagerSavepoint.iHdrOffset fields now.
38678 for(ii=0; ii<pPager->nSavepoint; ii++){
38679 if( pPager->aSavepoint[ii].iHdrOffset==0 ){
38680 pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
38684 pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
38687 ** Write the nRec Field - the number of page records that follow this
38688 ** journal header. Normally, zero is written to this value at this time.
38689 ** After the records are added to the journal (and the journal synced,
38690 ** if in full-sync mode), the zero is overwritten with the true number
38691 ** of records (see syncJournal()).
38693 ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
38694 ** reading the journal this value tells SQLite to assume that the
38695 ** rest of the journal file contains valid page records. This assumption
38696 ** is dangerous, as if a failure occurred whilst writing to the journal
38697 ** file it may contain some garbage data. There are two scenarios
38698 ** where this risk can be ignored:
38700 ** * When the pager is in no-sync mode. Corruption can follow a
38701 ** power failure in this case anyway.
38703 ** * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
38704 ** that garbage data is never appended to the journal file.
38706 assert( isOpen(pPager->fd) || pPager->noSync );
38707 if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
38708 || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
38710 memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
38711 put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
38712 }else{
38713 memset(zHeader, 0, sizeof(aJournalMagic)+4);
38716 /* The random check-hash initialiser */
38717 sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
38718 put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
38719 /* The initial database size */
38720 put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
38721 /* The assumed sector size for this process */
38722 put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
38724 /* The page size */
38725 put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
38727 /* Initializing the tail of the buffer is not necessary. Everything
38728 ** works find if the following memset() is omitted. But initializing
38729 ** the memory prevents valgrind from complaining, so we are willing to
38730 ** take the performance hit.
38732 memset(&zHeader[sizeof(aJournalMagic)+20], 0,
38733 nHeader-(sizeof(aJournalMagic)+20));
38735 /* In theory, it is only necessary to write the 28 bytes that the
38736 ** journal header consumes to the journal file here. Then increment the
38737 ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
38738 ** record is written to the following sector (leaving a gap in the file
38739 ** that will be implicitly filled in by the OS).
38741 ** However it has been discovered that on some systems this pattern can
38742 ** be significantly slower than contiguously writing data to the file,
38743 ** even if that means explicitly writing data to the block of
38744 ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
38745 ** is done.
38747 ** The loop is required here in case the sector-size is larger than the
38748 ** database page size. Since the zHeader buffer is only Pager.pageSize
38749 ** bytes in size, more than one call to sqlite3OsWrite() may be required
38750 ** to populate the entire journal header sector.
38752 for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
38753 IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
38754 rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
38755 assert( pPager->journalHdr <= pPager->journalOff );
38756 pPager->journalOff += nHeader;
38759 return rc;
38763 ** The journal file must be open when this is called. A journal header file
38764 ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
38765 ** file. The current location in the journal file is given by
38766 ** pPager->journalOff. See comments above function writeJournalHdr() for
38767 ** a description of the journal header format.
38769 ** If the header is read successfully, *pNRec is set to the number of
38770 ** page records following this header and *pDbSize is set to the size of the
38771 ** database before the transaction began, in pages. Also, pPager->cksumInit
38772 ** is set to the value read from the journal header. SQLITE_OK is returned
38773 ** in this case.
38775 ** If the journal header file appears to be corrupted, SQLITE_DONE is
38776 ** returned and *pNRec and *PDbSize are undefined. If JOURNAL_HDR_SZ bytes
38777 ** cannot be read from the journal file an error code is returned.
38779 static int readJournalHdr(
38780 Pager *pPager, /* Pager object */
38781 int isHot,
38782 i64 journalSize, /* Size of the open journal file in bytes */
38783 u32 *pNRec, /* OUT: Value read from the nRec field */
38784 u32 *pDbSize /* OUT: Value of original database size field */
38786 int rc; /* Return code */
38787 unsigned char aMagic[8]; /* A buffer to hold the magic header */
38788 i64 iHdrOff; /* Offset of journal header being read */
38790 assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
38792 /* Advance Pager.journalOff to the start of the next sector. If the
38793 ** journal file is too small for there to be a header stored at this
38794 ** point, return SQLITE_DONE.
38796 pPager->journalOff = journalHdrOffset(pPager);
38797 if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
38798 return SQLITE_DONE;
38800 iHdrOff = pPager->journalOff;
38802 /* Read in the first 8 bytes of the journal header. If they do not match
38803 ** the magic string found at the start of each journal header, return
38804 ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
38805 ** proceed.
38807 if( isHot || iHdrOff!=pPager->journalHdr ){
38808 rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
38809 if( rc ){
38810 return rc;
38812 if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
38813 return SQLITE_DONE;
38817 /* Read the first three 32-bit fields of the journal header: The nRec
38818 ** field, the checksum-initializer and the database size at the start
38819 ** of the transaction. Return an error code if anything goes wrong.
38821 if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
38822 || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
38823 || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
38825 return rc;
38828 if( pPager->journalOff==0 ){
38829 u32 iPageSize; /* Page-size field of journal header */
38830 u32 iSectorSize; /* Sector-size field of journal header */
38832 /* Read the page-size and sector-size journal header fields. */
38833 if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
38834 || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
38836 return rc;
38839 /* Versions of SQLite prior to 3.5.8 set the page-size field of the
38840 ** journal header to zero. In this case, assume that the Pager.pageSize
38841 ** variable is already set to the correct page size.
38843 if( iPageSize==0 ){
38844 iPageSize = pPager->pageSize;
38847 /* Check that the values read from the page-size and sector-size fields
38848 ** are within range. To be 'in range', both values need to be a power
38849 ** of two greater than or equal to 512 or 32, and not greater than their
38850 ** respective compile time maximum limits.
38852 if( iPageSize<512 || iSectorSize<32
38853 || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
38854 || ((iPageSize-1)&iPageSize)!=0 || ((iSectorSize-1)&iSectorSize)!=0
38856 /* If the either the page-size or sector-size in the journal-header is
38857 ** invalid, then the process that wrote the journal-header must have
38858 ** crashed before the header was synced. In this case stop reading
38859 ** the journal file here.
38861 return SQLITE_DONE;
38864 /* Update the page-size to match the value read from the journal.
38865 ** Use a testcase() macro to make sure that malloc failure within
38866 ** PagerSetPagesize() is tested.
38868 rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
38869 testcase( rc!=SQLITE_OK );
38871 /* Update the assumed sector-size to match the value used by
38872 ** the process that created this journal. If this journal was
38873 ** created by a process other than this one, then this routine
38874 ** is being called from within pager_playback(). The local value
38875 ** of Pager.sectorSize is restored at the end of that routine.
38877 pPager->sectorSize = iSectorSize;
38880 pPager->journalOff += JOURNAL_HDR_SZ(pPager);
38881 return rc;
38886 ** Write the supplied master journal name into the journal file for pager
38887 ** pPager at the current location. The master journal name must be the last
38888 ** thing written to a journal file. If the pager is in full-sync mode, the
38889 ** journal file descriptor is advanced to the next sector boundary before
38890 ** anything is written. The format is:
38892 ** + 4 bytes: PAGER_MJ_PGNO.
38893 ** + N bytes: Master journal filename in utf-8.
38894 ** + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
38895 ** + 4 bytes: Master journal name checksum.
38896 ** + 8 bytes: aJournalMagic[].
38898 ** The master journal page checksum is the sum of the bytes in the master
38899 ** journal name, where each byte is interpreted as a signed 8-bit integer.
38901 ** If zMaster is a NULL pointer (occurs for a single database transaction),
38902 ** this call is a no-op.
38904 static int writeMasterJournal(Pager *pPager, const char *zMaster){
38905 int rc; /* Return code */
38906 int nMaster; /* Length of string zMaster */
38907 i64 iHdrOff; /* Offset of header in journal file */
38908 i64 jrnlSize; /* Size of journal file on disk */
38909 u32 cksum = 0; /* Checksum of string zMaster */
38911 assert( pPager->setMaster==0 );
38912 assert( !pagerUseWal(pPager) );
38914 if( !zMaster
38915 || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
38916 || pPager->journalMode==PAGER_JOURNALMODE_OFF
38918 return SQLITE_OK;
38920 pPager->setMaster = 1;
38921 assert( isOpen(pPager->jfd) );
38922 assert( pPager->journalHdr <= pPager->journalOff );
38924 /* Calculate the length in bytes and the checksum of zMaster */
38925 for(nMaster=0; zMaster[nMaster]; nMaster++){
38926 cksum += zMaster[nMaster];
38929 /* If in full-sync mode, advance to the next disk sector before writing
38930 ** the master journal name. This is in case the previous page written to
38931 ** the journal has already been synced.
38933 if( pPager->fullSync ){
38934 pPager->journalOff = journalHdrOffset(pPager);
38936 iHdrOff = pPager->journalOff;
38938 /* Write the master journal data to the end of the journal file. If
38939 ** an error occurs, return the error code to the caller.
38941 if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
38942 || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
38943 || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
38944 || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
38945 || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
38947 return rc;
38949 pPager->journalOff += (nMaster+20);
38951 /* If the pager is in peristent-journal mode, then the physical
38952 ** journal-file may extend past the end of the master-journal name
38953 ** and 8 bytes of magic data just written to the file. This is
38954 ** dangerous because the code to rollback a hot-journal file
38955 ** will not be able to find the master-journal name to determine
38956 ** whether or not the journal is hot.
38958 ** Easiest thing to do in this scenario is to truncate the journal
38959 ** file to the required size.
38961 if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
38962 && jrnlSize>pPager->journalOff
38964 rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
38966 return rc;
38970 ** Find a page in the hash table given its page number. Return
38971 ** a pointer to the page or NULL if the requested page is not
38972 ** already in memory.
38974 static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
38975 PgHdr *p; /* Return value */
38977 /* It is not possible for a call to PcacheFetch() with createFlag==0 to
38978 ** fail, since no attempt to allocate dynamic memory will be made.
38980 (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
38981 return p;
38985 ** Discard the entire contents of the in-memory page-cache.
38987 static void pager_reset(Pager *pPager){
38988 sqlite3BackupRestart(pPager->pBackup);
38989 sqlite3PcacheClear(pPager->pPCache);
38993 ** Free all structures in the Pager.aSavepoint[] array and set both
38994 ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
38995 ** if it is open and the pager is not in exclusive mode.
38997 static void releaseAllSavepoints(Pager *pPager){
38998 int ii; /* Iterator for looping through Pager.aSavepoint */
38999 for(ii=0; ii<pPager->nSavepoint; ii++){
39000 sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
39002 if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
39003 sqlite3OsClose(pPager->sjfd);
39005 sqlite3_free(pPager->aSavepoint);
39006 pPager->aSavepoint = 0;
39007 pPager->nSavepoint = 0;
39008 pPager->nSubRec = 0;
39012 ** Set the bit number pgno in the PagerSavepoint.pInSavepoint
39013 ** bitvecs of all open savepoints. Return SQLITE_OK if successful
39014 ** or SQLITE_NOMEM if a malloc failure occurs.
39016 static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
39017 int ii; /* Loop counter */
39018 int rc = SQLITE_OK; /* Result code */
39020 for(ii=0; ii<pPager->nSavepoint; ii++){
39021 PagerSavepoint *p = &pPager->aSavepoint[ii];
39022 if( pgno<=p->nOrig ){
39023 rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
39024 testcase( rc==SQLITE_NOMEM );
39025 assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
39028 return rc;
39032 ** This function is a no-op if the pager is in exclusive mode and not
39033 ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
39034 ** state.
39036 ** If the pager is not in exclusive-access mode, the database file is
39037 ** completely unlocked. If the file is unlocked and the file-system does
39038 ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
39039 ** closed (if it is open).
39041 ** If the pager is in ERROR state when this function is called, the
39042 ** contents of the pager cache are discarded before switching back to
39043 ** the OPEN state. Regardless of whether the pager is in exclusive-mode
39044 ** or not, any journal file left in the file-system will be treated
39045 ** as a hot-journal and rolled back the next time a read-transaction
39046 ** is opened (by this or by any other connection).
39048 static void pager_unlock(Pager *pPager){
39050 assert( pPager->eState==PAGER_READER
39051 || pPager->eState==PAGER_OPEN
39052 || pPager->eState==PAGER_ERROR
39055 sqlite3BitvecDestroy(pPager->pInJournal);
39056 pPager->pInJournal = 0;
39057 releaseAllSavepoints(pPager);
39059 if( pagerUseWal(pPager) ){
39060 assert( !isOpen(pPager->jfd) );
39061 sqlite3WalEndReadTransaction(pPager->pWal);
39062 pPager->eState = PAGER_OPEN;
39063 }else if( !pPager->exclusiveMode ){
39064 int rc; /* Error code returned by pagerUnlockDb() */
39065 int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
39067 /* If the operating system support deletion of open files, then
39068 ** close the journal file when dropping the database lock. Otherwise
39069 ** another connection with journal_mode=delete might delete the file
39070 ** out from under us.
39072 assert( (PAGER_JOURNALMODE_MEMORY & 5)!=1 );
39073 assert( (PAGER_JOURNALMODE_OFF & 5)!=1 );
39074 assert( (PAGER_JOURNALMODE_WAL & 5)!=1 );
39075 assert( (PAGER_JOURNALMODE_DELETE & 5)!=1 );
39076 assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
39077 assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
39078 if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
39079 || 1!=(pPager->journalMode & 5)
39081 sqlite3OsClose(pPager->jfd);
39084 /* If the pager is in the ERROR state and the call to unlock the database
39085 ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
39086 ** above the #define for UNKNOWN_LOCK for an explanation of why this
39087 ** is necessary.
39089 rc = pagerUnlockDb(pPager, NO_LOCK);
39090 if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
39091 pPager->eLock = UNKNOWN_LOCK;
39094 /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
39095 ** without clearing the error code. This is intentional - the error
39096 ** code is cleared and the cache reset in the block below.
39098 assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
39099 pPager->changeCountDone = 0;
39100 pPager->eState = PAGER_OPEN;
39103 /* If Pager.errCode is set, the contents of the pager cache cannot be
39104 ** trusted. Now that there are no outstanding references to the pager,
39105 ** it can safely move back to PAGER_OPEN state. This happens in both
39106 ** normal and exclusive-locking mode.
39108 if( pPager->errCode ){
39109 assert( !MEMDB );
39110 pager_reset(pPager);
39111 pPager->changeCountDone = pPager->tempFile;
39112 pPager->eState = PAGER_OPEN;
39113 pPager->errCode = SQLITE_OK;
39116 pPager->journalOff = 0;
39117 pPager->journalHdr = 0;
39118 pPager->setMaster = 0;
39122 ** This function is called whenever an IOERR or FULL error that requires
39123 ** the pager to transition into the ERROR state may ahve occurred.
39124 ** The first argument is a pointer to the pager structure, the second
39125 ** the error-code about to be returned by a pager API function. The
39126 ** value returned is a copy of the second argument to this function.
39128 ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
39129 ** IOERR sub-codes, the pager enters the ERROR state and the error code
39130 ** is stored in Pager.errCode. While the pager remains in the ERROR state,
39131 ** all major API calls on the Pager will immediately return Pager.errCode.
39133 ** The ERROR state indicates that the contents of the pager-cache
39134 ** cannot be trusted. This state can be cleared by completely discarding
39135 ** the contents of the pager-cache. If a transaction was active when
39136 ** the persistent error occurred, then the rollback journal may need
39137 ** to be replayed to restore the contents of the database file (as if
39138 ** it were a hot-journal).
39140 static int pager_error(Pager *pPager, int rc){
39141 int rc2 = rc & 0xff;
39142 assert( rc==SQLITE_OK || !MEMDB );
39143 assert(
39144 pPager->errCode==SQLITE_FULL ||
39145 pPager->errCode==SQLITE_OK ||
39146 (pPager->errCode & 0xff)==SQLITE_IOERR
39148 if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
39149 pPager->errCode = rc;
39150 pPager->eState = PAGER_ERROR;
39152 return rc;
39156 ** This routine ends a transaction. A transaction is usually ended by
39157 ** either a COMMIT or a ROLLBACK operation. This routine may be called
39158 ** after rollback of a hot-journal, or if an error occurs while opening
39159 ** the journal file or writing the very first journal-header of a
39160 ** database transaction.
39162 ** This routine is never called in PAGER_ERROR state. If it is called
39163 ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
39164 ** exclusive than a RESERVED lock, it is a no-op.
39166 ** Otherwise, any active savepoints are released.
39168 ** If the journal file is open, then it is "finalized". Once a journal
39169 ** file has been finalized it is not possible to use it to roll back a
39170 ** transaction. Nor will it be considered to be a hot-journal by this
39171 ** or any other database connection. Exactly how a journal is finalized
39172 ** depends on whether or not the pager is running in exclusive mode and
39173 ** the current journal-mode (Pager.journalMode value), as follows:
39175 ** journalMode==MEMORY
39176 ** Journal file descriptor is simply closed. This destroys an
39177 ** in-memory journal.
39179 ** journalMode==TRUNCATE
39180 ** Journal file is truncated to zero bytes in size.
39182 ** journalMode==PERSIST
39183 ** The first 28 bytes of the journal file are zeroed. This invalidates
39184 ** the first journal header in the file, and hence the entire journal
39185 ** file. An invalid journal file cannot be rolled back.
39187 ** journalMode==DELETE
39188 ** The journal file is closed and deleted using sqlite3OsDelete().
39190 ** If the pager is running in exclusive mode, this method of finalizing
39191 ** the journal file is never used. Instead, if the journalMode is
39192 ** DELETE and the pager is in exclusive mode, the method described under
39193 ** journalMode==PERSIST is used instead.
39195 ** After the journal is finalized, the pager moves to PAGER_READER state.
39196 ** If running in non-exclusive rollback mode, the lock on the file is
39197 ** downgraded to a SHARED_LOCK.
39199 ** SQLITE_OK is returned if no error occurs. If an error occurs during
39200 ** any of the IO operations to finalize the journal file or unlock the
39201 ** database then the IO error code is returned to the user. If the
39202 ** operation to finalize the journal file fails, then the code still
39203 ** tries to unlock the database file if not in exclusive mode. If the
39204 ** unlock operation fails as well, then the first error code related
39205 ** to the first error encountered (the journal finalization one) is
39206 ** returned.
39208 static int pager_end_transaction(Pager *pPager, int hasMaster){
39209 int rc = SQLITE_OK; /* Error code from journal finalization operation */
39210 int rc2 = SQLITE_OK; /* Error code from db file unlock operation */
39212 /* Do nothing if the pager does not have an open write transaction
39213 ** or at least a RESERVED lock. This function may be called when there
39214 ** is no write-transaction active but a RESERVED or greater lock is
39215 ** held under two circumstances:
39217 ** 1. After a successful hot-journal rollback, it is called with
39218 ** eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
39220 ** 2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
39221 ** lock switches back to locking_mode=normal and then executes a
39222 ** read-transaction, this function is called with eState==PAGER_READER
39223 ** and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
39225 assert( assert_pager_state(pPager) );
39226 assert( pPager->eState!=PAGER_ERROR );
39227 if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
39228 return SQLITE_OK;
39231 releaseAllSavepoints(pPager);
39232 assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
39233 if( isOpen(pPager->jfd) ){
39234 assert( !pagerUseWal(pPager) );
39236 /* Finalize the journal file. */
39237 if( sqlite3IsMemJournal(pPager->jfd) ){
39238 assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
39239 sqlite3OsClose(pPager->jfd);
39240 }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
39241 if( pPager->journalOff==0 ){
39242 rc = SQLITE_OK;
39243 }else{
39244 rc = sqlite3OsTruncate(pPager->jfd, 0);
39246 pPager->journalOff = 0;
39247 }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
39248 || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
39250 rc = zeroJournalHdr(pPager, hasMaster);
39251 pPager->journalOff = 0;
39252 }else{
39253 /* This branch may be executed with Pager.journalMode==MEMORY if
39254 ** a hot-journal was just rolled back. In this case the journal
39255 ** file should be closed and deleted. If this connection writes to
39256 ** the database file, it will do so using an in-memory journal.
39258 assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
39259 || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
39260 || pPager->journalMode==PAGER_JOURNALMODE_WAL
39262 sqlite3OsClose(pPager->jfd);
39263 if( !pPager->tempFile ){
39264 rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
39269 #ifdef SQLITE_CHECK_PAGES
39270 sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
39271 if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
39272 PgHdr *p = pager_lookup(pPager, 1);
39273 if( p ){
39274 p->pageHash = 0;
39275 sqlite3PagerUnref(p);
39278 #endif
39280 sqlite3BitvecDestroy(pPager->pInJournal);
39281 pPager->pInJournal = 0;
39282 pPager->nRec = 0;
39283 sqlite3PcacheCleanAll(pPager->pPCache);
39284 sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
39286 if( pagerUseWal(pPager) ){
39287 /* Drop the WAL write-lock, if any. Also, if the connection was in
39288 ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
39289 ** lock held on the database file.
39291 rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
39292 assert( rc2==SQLITE_OK );
39294 if( !pPager->exclusiveMode
39295 && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
39297 rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
39298 pPager->changeCountDone = 0;
39300 pPager->eState = PAGER_READER;
39301 pPager->setMaster = 0;
39303 return (rc==SQLITE_OK?rc2:rc);
39307 ** Execute a rollback if a transaction is active and unlock the
39308 ** database file.
39310 ** If the pager has already entered the ERROR state, do not attempt
39311 ** the rollback at this time. Instead, pager_unlock() is called. The
39312 ** call to pager_unlock() will discard all in-memory pages, unlock
39313 ** the database file and move the pager back to OPEN state. If this
39314 ** means that there is a hot-journal left in the file-system, the next
39315 ** connection to obtain a shared lock on the pager (which may be this one)
39316 ** will roll it back.
39318 ** If the pager has not already entered the ERROR state, but an IO or
39319 ** malloc error occurs during a rollback, then this will itself cause
39320 ** the pager to enter the ERROR state. Which will be cleared by the
39321 ** call to pager_unlock(), as described above.
39323 static void pagerUnlockAndRollback(Pager *pPager){
39324 if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
39325 assert( assert_pager_state(pPager) );
39326 if( pPager->eState>=PAGER_WRITER_LOCKED ){
39327 sqlite3BeginBenignMalloc();
39328 sqlite3PagerRollback(pPager);
39329 sqlite3EndBenignMalloc();
39330 }else if( !pPager->exclusiveMode ){
39331 assert( pPager->eState==PAGER_READER );
39332 pager_end_transaction(pPager, 0);
39335 pager_unlock(pPager);
39339 ** Parameter aData must point to a buffer of pPager->pageSize bytes
39340 ** of data. Compute and return a checksum based ont the contents of the
39341 ** page of data and the current value of pPager->cksumInit.
39343 ** This is not a real checksum. It is really just the sum of the
39344 ** random initial value (pPager->cksumInit) and every 200th byte
39345 ** of the page data, starting with byte offset (pPager->pageSize%200).
39346 ** Each byte is interpreted as an 8-bit unsigned integer.
39348 ** Changing the formula used to compute this checksum results in an
39349 ** incompatible journal file format.
39351 ** If journal corruption occurs due to a power failure, the most likely
39352 ** scenario is that one end or the other of the record will be changed.
39353 ** It is much less likely that the two ends of the journal record will be
39354 ** correct and the middle be corrupt. Thus, this "checksum" scheme,
39355 ** though fast and simple, catches the mostly likely kind of corruption.
39357 static u32 pager_cksum(Pager *pPager, const u8 *aData){
39358 u32 cksum = pPager->cksumInit; /* Checksum value to return */
39359 int i = pPager->pageSize-200; /* Loop counter */
39360 while( i>0 ){
39361 cksum += aData[i];
39362 i -= 200;
39364 return cksum;
39368 ** Report the current page size and number of reserved bytes back
39369 ** to the codec.
39371 #ifdef SQLITE_HAS_CODEC
39372 static void pagerReportSize(Pager *pPager){
39373 if( pPager->xCodecSizeChng ){
39374 pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
39375 (int)pPager->nReserve);
39378 #else
39379 # define pagerReportSize(X) /* No-op if we do not support a codec */
39380 #endif
39383 ** Read a single page from either the journal file (if isMainJrnl==1) or
39384 ** from the sub-journal (if isMainJrnl==0) and playback that page.
39385 ** The page begins at offset *pOffset into the file. The *pOffset
39386 ** value is increased to the start of the next page in the journal.
39388 ** The main rollback journal uses checksums - the statement journal does
39389 ** not.
39391 ** If the page number of the page record read from the (sub-)journal file
39392 ** is greater than the current value of Pager.dbSize, then playback is
39393 ** skipped and SQLITE_OK is returned.
39395 ** If pDone is not NULL, then it is a record of pages that have already
39396 ** been played back. If the page at *pOffset has already been played back
39397 ** (if the corresponding pDone bit is set) then skip the playback.
39398 ** Make sure the pDone bit corresponding to the *pOffset page is set
39399 ** prior to returning.
39401 ** If the page record is successfully read from the (sub-)journal file
39402 ** and played back, then SQLITE_OK is returned. If an IO error occurs
39403 ** while reading the record from the (sub-)journal file or while writing
39404 ** to the database file, then the IO error code is returned. If data
39405 ** is successfully read from the (sub-)journal file but appears to be
39406 ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
39407 ** two circumstances:
39409 ** * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
39410 ** * If the record is being rolled back from the main journal file
39411 ** and the checksum field does not match the record content.
39413 ** Neither of these two scenarios are possible during a savepoint rollback.
39415 ** If this is a savepoint rollback, then memory may have to be dynamically
39416 ** allocated by this function. If this is the case and an allocation fails,
39417 ** SQLITE_NOMEM is returned.
39419 static int pager_playback_one_page(
39420 Pager *pPager, /* The pager being played back */
39421 i64 *pOffset, /* Offset of record to playback */
39422 Bitvec *pDone, /* Bitvec of pages already played back */
39423 int isMainJrnl, /* 1 -> main journal. 0 -> sub-journal. */
39424 int isSavepnt /* True for a savepoint rollback */
39426 int rc;
39427 PgHdr *pPg; /* An existing page in the cache */
39428 Pgno pgno; /* The page number of a page in journal */
39429 u32 cksum; /* Checksum used for sanity checking */
39430 char *aData; /* Temporary storage for the page */
39431 sqlite3_file *jfd; /* The file descriptor for the journal file */
39432 int isSynced; /* True if journal page is synced */
39434 assert( (isMainJrnl&~1)==0 ); /* isMainJrnl is 0 or 1 */
39435 assert( (isSavepnt&~1)==0 ); /* isSavepnt is 0 or 1 */
39436 assert( isMainJrnl || pDone ); /* pDone always used on sub-journals */
39437 assert( isSavepnt || pDone==0 ); /* pDone never used on non-savepoint */
39439 aData = pPager->pTmpSpace;
39440 assert( aData ); /* Temp storage must have already been allocated */
39441 assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
39443 /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
39444 ** or savepoint rollback done at the request of the caller) or this is
39445 ** a hot-journal rollback. If it is a hot-journal rollback, the pager
39446 ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
39447 ** only reads from the main journal, not the sub-journal.
39449 assert( pPager->eState>=PAGER_WRITER_CACHEMOD
39450 || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
39452 assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
39454 /* Read the page number and page data from the journal or sub-journal
39455 ** file. Return an error code to the caller if an IO error occurs.
39457 jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
39458 rc = read32bits(jfd, *pOffset, &pgno);
39459 if( rc!=SQLITE_OK ) return rc;
39460 rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
39461 if( rc!=SQLITE_OK ) return rc;
39462 *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
39464 /* Sanity checking on the page. This is more important that I originally
39465 ** thought. If a power failure occurs while the journal is being written,
39466 ** it could cause invalid data to be written into the journal. We need to
39467 ** detect this invalid data (with high probability) and ignore it.
39469 if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
39470 assert( !isSavepnt );
39471 return SQLITE_DONE;
39473 if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
39474 return SQLITE_OK;
39476 if( isMainJrnl ){
39477 rc = read32bits(jfd, (*pOffset)-4, &cksum);
39478 if( rc ) return rc;
39479 if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
39480 return SQLITE_DONE;
39484 /* If this page has already been played by before during the current
39485 ** rollback, then don't bother to play it back again.
39487 if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
39488 return rc;
39491 /* When playing back page 1, restore the nReserve setting
39493 if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
39494 pPager->nReserve = ((u8*)aData)[20];
39495 pagerReportSize(pPager);
39498 /* If the pager is in CACHEMOD state, then there must be a copy of this
39499 ** page in the pager cache. In this case just update the pager cache,
39500 ** not the database file. The page is left marked dirty in this case.
39502 ** An exception to the above rule: If the database is in no-sync mode
39503 ** and a page is moved during an incremental vacuum then the page may
39504 ** not be in the pager cache. Later: if a malloc() or IO error occurs
39505 ** during a Movepage() call, then the page may not be in the cache
39506 ** either. So the condition described in the above paragraph is not
39507 ** assert()able.
39509 ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
39510 ** pager cache if it exists and the main file. The page is then marked
39511 ** not dirty. Since this code is only executed in PAGER_OPEN state for
39512 ** a hot-journal rollback, it is guaranteed that the page-cache is empty
39513 ** if the pager is in OPEN state.
39515 ** Ticket #1171: The statement journal might contain page content that is
39516 ** different from the page content at the start of the transaction.
39517 ** This occurs when a page is changed prior to the start of a statement
39518 ** then changed again within the statement. When rolling back such a
39519 ** statement we must not write to the original database unless we know
39520 ** for certain that original page contents are synced into the main rollback
39521 ** journal. Otherwise, a power loss might leave modified data in the
39522 ** database file without an entry in the rollback journal that can
39523 ** restore the database to its original form. Two conditions must be
39524 ** met before writing to the database files. (1) the database must be
39525 ** locked. (2) we know that the original page content is fully synced
39526 ** in the main journal either because the page is not in cache or else
39527 ** the page is marked as needSync==0.
39529 ** 2008-04-14: When attempting to vacuum a corrupt database file, it
39530 ** is possible to fail a statement on a database that does not yet exist.
39531 ** Do not attempt to write if database file has never been opened.
39533 if( pagerUseWal(pPager) ){
39534 pPg = 0;
39535 }else{
39536 pPg = pager_lookup(pPager, pgno);
39538 assert( pPg || !MEMDB );
39539 assert( pPager->eState!=PAGER_OPEN || pPg==0 );
39540 PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
39541 PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
39542 (isMainJrnl?"main-journal":"sub-journal")
39544 if( isMainJrnl ){
39545 isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
39546 }else{
39547 isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
39549 if( isOpen(pPager->fd)
39550 && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
39551 && isSynced
39553 i64 ofst = (pgno-1)*(i64)pPager->pageSize;
39554 testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
39555 assert( !pagerUseWal(pPager) );
39556 rc = sqlite3OsWrite(pPager->fd, (u8*)aData, pPager->pageSize, ofst);
39557 if( pgno>pPager->dbFileSize ){
39558 pPager->dbFileSize = pgno;
39560 if( pPager->pBackup ){
39561 CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
39562 sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
39563 CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
39565 }else if( !isMainJrnl && pPg==0 ){
39566 /* If this is a rollback of a savepoint and data was not written to
39567 ** the database and the page is not in-memory, there is a potential
39568 ** problem. When the page is next fetched by the b-tree layer, it
39569 ** will be read from the database file, which may or may not be
39570 ** current.
39572 ** There are a couple of different ways this can happen. All are quite
39573 ** obscure. When running in synchronous mode, this can only happen
39574 ** if the page is on the free-list at the start of the transaction, then
39575 ** populated, then moved using sqlite3PagerMovepage().
39577 ** The solution is to add an in-memory page to the cache containing
39578 ** the data just read from the sub-journal. Mark the page as dirty
39579 ** and if the pager requires a journal-sync, then mark the page as
39580 ** requiring a journal-sync before it is written.
39582 assert( isSavepnt );
39583 assert( pPager->doNotSpill==0 );
39584 pPager->doNotSpill++;
39585 rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1);
39586 assert( pPager->doNotSpill==1 );
39587 pPager->doNotSpill--;
39588 if( rc!=SQLITE_OK ) return rc;
39589 pPg->flags &= ~PGHDR_NEED_READ;
39590 sqlite3PcacheMakeDirty(pPg);
39592 if( pPg ){
39593 /* No page should ever be explicitly rolled back that is in use, except
39594 ** for page 1 which is held in use in order to keep the lock on the
39595 ** database active. However such a page may be rolled back as a result
39596 ** of an internal error resulting in an automatic call to
39597 ** sqlite3PagerRollback().
39599 void *pData;
39600 pData = pPg->pData;
39601 memcpy(pData, (u8*)aData, pPager->pageSize);
39602 pPager->xReiniter(pPg);
39603 if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
39604 /* If the contents of this page were just restored from the main
39605 ** journal file, then its content must be as they were when the
39606 ** transaction was first opened. In this case we can mark the page
39607 ** as clean, since there will be no need to write it out to the
39608 ** database.
39610 ** There is one exception to this rule. If the page is being rolled
39611 ** back as part of a savepoint (or statement) rollback from an
39612 ** unsynced portion of the main journal file, then it is not safe
39613 ** to mark the page as clean. This is because marking the page as
39614 ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
39615 ** already in the journal file (recorded in Pager.pInJournal) and
39616 ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
39617 ** again within this transaction, it will be marked as dirty but
39618 ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
39619 ** be written out into the database file before its journal file
39620 ** segment is synced. If a crash occurs during or following this,
39621 ** database corruption may ensue.
39623 assert( !pagerUseWal(pPager) );
39624 sqlite3PcacheMakeClean(pPg);
39626 pager_set_pagehash(pPg);
39628 /* If this was page 1, then restore the value of Pager.dbFileVers.
39629 ** Do this before any decoding. */
39630 if( pgno==1 ){
39631 memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
39634 /* Decode the page just read from disk */
39635 CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
39636 sqlite3PcacheRelease(pPg);
39638 return rc;
39642 ** Parameter zMaster is the name of a master journal file. A single journal
39643 ** file that referred to the master journal file has just been rolled back.
39644 ** This routine checks if it is possible to delete the master journal file,
39645 ** and does so if it is.
39647 ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
39648 ** available for use within this function.
39650 ** When a master journal file is created, it is populated with the names
39651 ** of all of its child journals, one after another, formatted as utf-8
39652 ** encoded text. The end of each child journal file is marked with a
39653 ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
39654 ** file for a transaction involving two databases might be:
39656 ** "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
39658 ** A master journal file may only be deleted once all of its child
39659 ** journals have been rolled back.
39661 ** This function reads the contents of the master-journal file into
39662 ** memory and loops through each of the child journal names. For
39663 ** each child journal, it checks if:
39665 ** * if the child journal exists, and if so
39666 ** * if the child journal contains a reference to master journal
39667 ** file zMaster
39669 ** If a child journal can be found that matches both of the criteria
39670 ** above, this function returns without doing anything. Otherwise, if
39671 ** no such child journal can be found, file zMaster is deleted from
39672 ** the file-system using sqlite3OsDelete().
39674 ** If an IO error within this function, an error code is returned. This
39675 ** function allocates memory by calling sqlite3Malloc(). If an allocation
39676 ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
39677 ** occur, SQLITE_OK is returned.
39679 ** TODO: This function allocates a single block of memory to load
39680 ** the entire contents of the master journal file. This could be
39681 ** a couple of kilobytes or so - potentially larger than the page
39682 ** size.
39684 static int pager_delmaster(Pager *pPager, const char *zMaster){
39685 sqlite3_vfs *pVfs = pPager->pVfs;
39686 int rc; /* Return code */
39687 sqlite3_file *pMaster; /* Malloc'd master-journal file descriptor */
39688 sqlite3_file *pJournal; /* Malloc'd child-journal file descriptor */
39689 char *zMasterJournal = 0; /* Contents of master journal file */
39690 i64 nMasterJournal; /* Size of master journal file */
39691 char *zJournal; /* Pointer to one journal within MJ file */
39692 char *zMasterPtr; /* Space to hold MJ filename from a journal file */
39693 int nMasterPtr; /* Amount of space allocated to zMasterPtr[] */
39695 /* Allocate space for both the pJournal and pMaster file descriptors.
39696 ** If successful, open the master journal file for reading.
39698 pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
39699 pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
39700 if( !pMaster ){
39701 rc = SQLITE_NOMEM;
39702 }else{
39703 const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
39704 rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
39706 if( rc!=SQLITE_OK ) goto delmaster_out;
39708 /* Load the entire master journal file into space obtained from
39709 ** sqlite3_malloc() and pointed to by zMasterJournal. Also obtain
39710 ** sufficient space (in zMasterPtr) to hold the names of master
39711 ** journal files extracted from regular rollback-journals.
39713 rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
39714 if( rc!=SQLITE_OK ) goto delmaster_out;
39715 nMasterPtr = pVfs->mxPathname+1;
39716 zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1);
39717 if( !zMasterJournal ){
39718 rc = SQLITE_NOMEM;
39719 goto delmaster_out;
39721 zMasterPtr = &zMasterJournal[nMasterJournal+1];
39722 rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
39723 if( rc!=SQLITE_OK ) goto delmaster_out;
39724 zMasterJournal[nMasterJournal] = 0;
39726 zJournal = zMasterJournal;
39727 while( (zJournal-zMasterJournal)<nMasterJournal ){
39728 int exists;
39729 rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
39730 if( rc!=SQLITE_OK ){
39731 goto delmaster_out;
39733 if( exists ){
39734 /* One of the journals pointed to by the master journal exists.
39735 ** Open it and check if it points at the master journal. If
39736 ** so, return without deleting the master journal file.
39738 int c;
39739 int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
39740 rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
39741 if( rc!=SQLITE_OK ){
39742 goto delmaster_out;
39745 rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
39746 sqlite3OsClose(pJournal);
39747 if( rc!=SQLITE_OK ){
39748 goto delmaster_out;
39751 c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
39752 if( c ){
39753 /* We have a match. Do not delete the master journal file. */
39754 goto delmaster_out;
39757 zJournal += (sqlite3Strlen30(zJournal)+1);
39760 sqlite3OsClose(pMaster);
39761 rc = sqlite3OsDelete(pVfs, zMaster, 0);
39763 delmaster_out:
39764 sqlite3_free(zMasterJournal);
39765 if( pMaster ){
39766 sqlite3OsClose(pMaster);
39767 assert( !isOpen(pJournal) );
39768 sqlite3_free(pMaster);
39770 return rc;
39775 ** This function is used to change the actual size of the database
39776 ** file in the file-system. This only happens when committing a transaction,
39777 ** or rolling back a transaction (including rolling back a hot-journal).
39779 ** If the main database file is not open, or the pager is not in either
39780 ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
39781 ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
39782 ** If the file on disk is currently larger than nPage pages, then use the VFS
39783 ** xTruncate() method to truncate it.
39785 ** Or, it might might be the case that the file on disk is smaller than
39786 ** nPage pages. Some operating system implementations can get confused if
39787 ** you try to truncate a file to some size that is larger than it
39788 ** currently is, so detect this case and write a single zero byte to
39789 ** the end of the new file instead.
39791 ** If successful, return SQLITE_OK. If an IO error occurs while modifying
39792 ** the database file, return the error code to the caller.
39794 static int pager_truncate(Pager *pPager, Pgno nPage){
39795 int rc = SQLITE_OK;
39796 assert( pPager->eState!=PAGER_ERROR );
39797 assert( pPager->eState!=PAGER_READER );
39799 if( isOpen(pPager->fd)
39800 && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
39802 i64 currentSize, newSize;
39803 int szPage = pPager->pageSize;
39804 assert( pPager->eLock==EXCLUSIVE_LOCK );
39805 /* TODO: Is it safe to use Pager.dbFileSize here? */
39806 rc = sqlite3OsFileSize(pPager->fd, &currentSize);
39807 newSize = szPage*(i64)nPage;
39808 if( rc==SQLITE_OK && currentSize!=newSize ){
39809 if( currentSize>newSize ){
39810 rc = sqlite3OsTruncate(pPager->fd, newSize);
39811 }else{
39812 char *pTmp = pPager->pTmpSpace;
39813 memset(pTmp, 0, szPage);
39814 testcase( (newSize-szPage) < currentSize );
39815 testcase( (newSize-szPage) == currentSize );
39816 testcase( (newSize-szPage) > currentSize );
39817 rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
39819 if( rc==SQLITE_OK ){
39820 pPager->dbFileSize = nPage;
39824 return rc;
39828 ** Set the value of the Pager.sectorSize variable for the given
39829 ** pager based on the value returned by the xSectorSize method
39830 ** of the open database file. The sector size will be used used
39831 ** to determine the size and alignment of journal header and
39832 ** master journal pointers within created journal files.
39834 ** For temporary files the effective sector size is always 512 bytes.
39836 ** Otherwise, for non-temporary files, the effective sector size is
39837 ** the value returned by the xSectorSize() method rounded up to 32 if
39838 ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
39839 ** is greater than MAX_SECTOR_SIZE.
39841 static void setSectorSize(Pager *pPager){
39842 assert( isOpen(pPager->fd) || pPager->tempFile );
39844 if( !pPager->tempFile ){
39845 /* Sector size doesn't matter for temporary files. Also, the file
39846 ** may not have been opened yet, in which case the OsSectorSize()
39847 ** call will segfault.
39849 pPager->sectorSize = sqlite3OsSectorSize(pPager->fd);
39851 if( pPager->sectorSize<32 ){
39852 pPager->sectorSize = 512;
39854 if( pPager->sectorSize>MAX_SECTOR_SIZE ){
39855 assert( MAX_SECTOR_SIZE>=512 );
39856 pPager->sectorSize = MAX_SECTOR_SIZE;
39861 ** Playback the journal and thus restore the database file to
39862 ** the state it was in before we started making changes.
39864 ** The journal file format is as follows:
39866 ** (1) 8 byte prefix. A copy of aJournalMagic[].
39867 ** (2) 4 byte big-endian integer which is the number of valid page records
39868 ** in the journal. If this value is 0xffffffff, then compute the
39869 ** number of page records from the journal size.
39870 ** (3) 4 byte big-endian integer which is the initial value for the
39871 ** sanity checksum.
39872 ** (4) 4 byte integer which is the number of pages to truncate the
39873 ** database to during a rollback.
39874 ** (5) 4 byte big-endian integer which is the sector size. The header
39875 ** is this many bytes in size.
39876 ** (6) 4 byte big-endian integer which is the page size.
39877 ** (7) zero padding out to the next sector size.
39878 ** (8) Zero or more pages instances, each as follows:
39879 ** + 4 byte page number.
39880 ** + pPager->pageSize bytes of data.
39881 ** + 4 byte checksum
39883 ** When we speak of the journal header, we mean the first 7 items above.
39884 ** Each entry in the journal is an instance of the 8th item.
39886 ** Call the value from the second bullet "nRec". nRec is the number of
39887 ** valid page entries in the journal. In most cases, you can compute the
39888 ** value of nRec from the size of the journal file. But if a power
39889 ** failure occurred while the journal was being written, it could be the
39890 ** case that the size of the journal file had already been increased but
39891 ** the extra entries had not yet made it safely to disk. In such a case,
39892 ** the value of nRec computed from the file size would be too large. For
39893 ** that reason, we always use the nRec value in the header.
39895 ** If the nRec value is 0xffffffff it means that nRec should be computed
39896 ** from the file size. This value is used when the user selects the
39897 ** no-sync option for the journal. A power failure could lead to corruption
39898 ** in this case. But for things like temporary table (which will be
39899 ** deleted when the power is restored) we don't care.
39901 ** If the file opened as the journal file is not a well-formed
39902 ** journal file then all pages up to the first corrupted page are rolled
39903 ** back (or no pages if the journal header is corrupted). The journal file
39904 ** is then deleted and SQLITE_OK returned, just as if no corruption had
39905 ** been encountered.
39907 ** If an I/O or malloc() error occurs, the journal-file is not deleted
39908 ** and an error code is returned.
39910 ** The isHot parameter indicates that we are trying to rollback a journal
39911 ** that might be a hot journal. Or, it could be that the journal is
39912 ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
39913 ** If the journal really is hot, reset the pager cache prior rolling
39914 ** back any content. If the journal is merely persistent, no reset is
39915 ** needed.
39917 static int pager_playback(Pager *pPager, int isHot){
39918 sqlite3_vfs *pVfs = pPager->pVfs;
39919 i64 szJ; /* Size of the journal file in bytes */
39920 u32 nRec; /* Number of Records in the journal */
39921 u32 u; /* Unsigned loop counter */
39922 Pgno mxPg = 0; /* Size of the original file in pages */
39923 int rc; /* Result code of a subroutine */
39924 int res = 1; /* Value returned by sqlite3OsAccess() */
39925 char *zMaster = 0; /* Name of master journal file if any */
39926 int needPagerReset; /* True to reset page prior to first page rollback */
39928 /* Figure out how many records are in the journal. Abort early if
39929 ** the journal is empty.
39931 assert( isOpen(pPager->jfd) );
39932 rc = sqlite3OsFileSize(pPager->jfd, &szJ);
39933 if( rc!=SQLITE_OK ){
39934 goto end_playback;
39937 /* Read the master journal name from the journal, if it is present.
39938 ** If a master journal file name is specified, but the file is not
39939 ** present on disk, then the journal is not hot and does not need to be
39940 ** played back.
39942 ** TODO: Technically the following is an error because it assumes that
39943 ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
39944 ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
39945 ** mxPathname is 512, which is the same as the minimum allowable value
39946 ** for pageSize.
39948 zMaster = pPager->pTmpSpace;
39949 rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
39950 if( rc==SQLITE_OK && zMaster[0] ){
39951 rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
39953 zMaster = 0;
39954 if( rc!=SQLITE_OK || !res ){
39955 goto end_playback;
39957 pPager->journalOff = 0;
39958 needPagerReset = isHot;
39960 /* This loop terminates either when a readJournalHdr() or
39961 ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
39962 ** occurs.
39964 while( 1 ){
39965 /* Read the next journal header from the journal file. If there are
39966 ** not enough bytes left in the journal file for a complete header, or
39967 ** it is corrupted, then a process must have failed while writing it.
39968 ** This indicates nothing more needs to be rolled back.
39970 rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
39971 if( rc!=SQLITE_OK ){
39972 if( rc==SQLITE_DONE ){
39973 rc = SQLITE_OK;
39975 goto end_playback;
39978 /* If nRec is 0xffffffff, then this journal was created by a process
39979 ** working in no-sync mode. This means that the rest of the journal
39980 ** file consists of pages, there are no more journal headers. Compute
39981 ** the value of nRec based on this assumption.
39983 if( nRec==0xffffffff ){
39984 assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
39985 nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
39988 /* If nRec is 0 and this rollback is of a transaction created by this
39989 ** process and if this is the final header in the journal, then it means
39990 ** that this part of the journal was being filled but has not yet been
39991 ** synced to disk. Compute the number of pages based on the remaining
39992 ** size of the file.
39994 ** The third term of the test was added to fix ticket #2565.
39995 ** When rolling back a hot journal, nRec==0 always means that the next
39996 ** chunk of the journal contains zero pages to be rolled back. But
39997 ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
39998 ** the journal, it means that the journal might contain additional
39999 ** pages that need to be rolled back and that the number of pages
40000 ** should be computed based on the journal file size.
40002 if( nRec==0 && !isHot &&
40003 pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
40004 nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
40007 /* If this is the first header read from the journal, truncate the
40008 ** database file back to its original size.
40010 if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
40011 rc = pager_truncate(pPager, mxPg);
40012 if( rc!=SQLITE_OK ){
40013 goto end_playback;
40015 pPager->dbSize = mxPg;
40018 /* Copy original pages out of the journal and back into the
40019 ** database file and/or page cache.
40021 for(u=0; u<nRec; u++){
40022 if( needPagerReset ){
40023 pager_reset(pPager);
40024 needPagerReset = 0;
40026 rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
40027 if( rc!=SQLITE_OK ){
40028 if( rc==SQLITE_DONE ){
40029 pPager->journalOff = szJ;
40030 break;
40031 }else if( rc==SQLITE_IOERR_SHORT_READ ){
40032 /* If the journal has been truncated, simply stop reading and
40033 ** processing the journal. This might happen if the journal was
40034 ** not completely written and synced prior to a crash. In that
40035 ** case, the database should have never been written in the
40036 ** first place so it is OK to simply abandon the rollback. */
40037 rc = SQLITE_OK;
40038 goto end_playback;
40039 }else{
40040 /* If we are unable to rollback, quit and return the error
40041 ** code. This will cause the pager to enter the error state
40042 ** so that no further harm will be done. Perhaps the next
40043 ** process to come along will be able to rollback the database.
40045 goto end_playback;
40050 /*NOTREACHED*/
40051 assert( 0 );
40053 end_playback:
40054 /* Following a rollback, the database file should be back in its original
40055 ** state prior to the start of the transaction, so invoke the
40056 ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
40057 ** assertion that the transaction counter was modified.
40059 assert(
40060 pPager->fd->pMethods==0 ||
40061 sqlite3OsFileControl(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0)>=SQLITE_OK
40064 /* If this playback is happening automatically as a result of an IO or
40065 ** malloc error that occurred after the change-counter was updated but
40066 ** before the transaction was committed, then the change-counter
40067 ** modification may just have been reverted. If this happens in exclusive
40068 ** mode, then subsequent transactions performed by the connection will not
40069 ** update the change-counter at all. This may lead to cache inconsistency
40070 ** problems for other processes at some point in the future. So, just
40071 ** in case this has happened, clear the changeCountDone flag now.
40073 pPager->changeCountDone = pPager->tempFile;
40075 if( rc==SQLITE_OK ){
40076 zMaster = pPager->pTmpSpace;
40077 rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
40078 testcase( rc!=SQLITE_OK );
40080 if( rc==SQLITE_OK
40081 && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
40083 rc = sqlite3PagerSync(pPager);
40085 if( rc==SQLITE_OK ){
40086 rc = pager_end_transaction(pPager, zMaster[0]!='\0');
40087 testcase( rc!=SQLITE_OK );
40089 if( rc==SQLITE_OK && zMaster[0] && res ){
40090 /* If there was a master journal and this routine will return success,
40091 ** see if it is possible to delete the master journal.
40093 rc = pager_delmaster(pPager, zMaster);
40094 testcase( rc!=SQLITE_OK );
40097 /* The Pager.sectorSize variable may have been updated while rolling
40098 ** back a journal created by a process with a different sector size
40099 ** value. Reset it to the correct value for this process.
40101 setSectorSize(pPager);
40102 return rc;
40107 ** Read the content for page pPg out of the database file and into
40108 ** pPg->pData. A shared lock or greater must be held on the database
40109 ** file before this function is called.
40111 ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
40112 ** the value read from the database file.
40114 ** If an IO error occurs, then the IO error is returned to the caller.
40115 ** Otherwise, SQLITE_OK is returned.
40117 static int readDbPage(PgHdr *pPg){
40118 Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
40119 Pgno pgno = pPg->pgno; /* Page number to read */
40120 int rc = SQLITE_OK; /* Return code */
40121 int isInWal = 0; /* True if page is in log file */
40122 int pgsz = pPager->pageSize; /* Number of bytes to read */
40124 assert( pPager->eState>=PAGER_READER && !MEMDB );
40125 assert( isOpen(pPager->fd) );
40127 if( NEVER(!isOpen(pPager->fd)) ){
40128 assert( pPager->tempFile );
40129 memset(pPg->pData, 0, pPager->pageSize);
40130 return SQLITE_OK;
40133 if( pagerUseWal(pPager) ){
40134 /* Try to pull the page from the write-ahead log. */
40135 rc = sqlite3WalRead(pPager->pWal, pgno, &isInWal, pgsz, pPg->pData);
40137 if( rc==SQLITE_OK && !isInWal ){
40138 i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
40139 rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
40140 if( rc==SQLITE_IOERR_SHORT_READ ){
40141 rc = SQLITE_OK;
40145 if( pgno==1 ){
40146 if( rc ){
40147 /* If the read is unsuccessful, set the dbFileVers[] to something
40148 ** that will never be a valid file version. dbFileVers[] is a copy
40149 ** of bytes 24..39 of the database. Bytes 28..31 should always be
40150 ** zero or the size of the database in page. Bytes 32..35 and 35..39
40151 ** should be page numbers which are never 0xffffffff. So filling
40152 ** pPager->dbFileVers[] with all 0xff bytes should suffice.
40154 ** For an encrypted database, the situation is more complex: bytes
40155 ** 24..39 of the database are white noise. But the probability of
40156 ** white noising equaling 16 bytes of 0xff is vanishingly small so
40157 ** we should still be ok.
40159 memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
40160 }else{
40161 u8 *dbFileVers = &((u8*)pPg->pData)[24];
40162 memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
40165 CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
40167 PAGER_INCR(sqlite3_pager_readdb_count);
40168 PAGER_INCR(pPager->nRead);
40169 IOTRACE(("PGIN %p %d\n", pPager, pgno));
40170 PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
40171 PAGERID(pPager), pgno, pager_pagehash(pPg)));
40173 return rc;
40177 ** Update the value of the change-counter at offsets 24 and 92 in
40178 ** the header and the sqlite version number at offset 96.
40180 ** This is an unconditional update. See also the pager_incr_changecounter()
40181 ** routine which only updates the change-counter if the update is actually
40182 ** needed, as determined by the pPager->changeCountDone state variable.
40184 static void pager_write_changecounter(PgHdr *pPg){
40185 u32 change_counter;
40187 /* Increment the value just read and write it back to byte 24. */
40188 change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
40189 put32bits(((char*)pPg->pData)+24, change_counter);
40191 /* Also store the SQLite version number in bytes 96..99 and in
40192 ** bytes 92..95 store the change counter for which the version number
40193 ** is valid. */
40194 put32bits(((char*)pPg->pData)+92, change_counter);
40195 put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
40198 #ifndef SQLITE_OMIT_WAL
40200 ** This function is invoked once for each page that has already been
40201 ** written into the log file when a WAL transaction is rolled back.
40202 ** Parameter iPg is the page number of said page. The pCtx argument
40203 ** is actually a pointer to the Pager structure.
40205 ** If page iPg is present in the cache, and has no outstanding references,
40206 ** it is discarded. Otherwise, if there are one or more outstanding
40207 ** references, the page content is reloaded from the database. If the
40208 ** attempt to reload content from the database is required and fails,
40209 ** return an SQLite error code. Otherwise, SQLITE_OK.
40211 static int pagerUndoCallback(void *pCtx, Pgno iPg){
40212 int rc = SQLITE_OK;
40213 Pager *pPager = (Pager *)pCtx;
40214 PgHdr *pPg;
40216 pPg = sqlite3PagerLookup(pPager, iPg);
40217 if( pPg ){
40218 if( sqlite3PcachePageRefcount(pPg)==1 ){
40219 sqlite3PcacheDrop(pPg);
40220 }else{
40221 rc = readDbPage(pPg);
40222 if( rc==SQLITE_OK ){
40223 pPager->xReiniter(pPg);
40225 sqlite3PagerUnref(pPg);
40229 /* Normally, if a transaction is rolled back, any backup processes are
40230 ** updated as data is copied out of the rollback journal and into the
40231 ** database. This is not generally possible with a WAL database, as
40232 ** rollback involves simply truncating the log file. Therefore, if one
40233 ** or more frames have already been written to the log (and therefore
40234 ** also copied into the backup databases) as part of this transaction,
40235 ** the backups must be restarted.
40237 sqlite3BackupRestart(pPager->pBackup);
40239 return rc;
40243 ** This function is called to rollback a transaction on a WAL database.
40245 static int pagerRollbackWal(Pager *pPager){
40246 int rc; /* Return Code */
40247 PgHdr *pList; /* List of dirty pages to revert */
40249 /* For all pages in the cache that are currently dirty or have already
40250 ** been written (but not committed) to the log file, do one of the
40251 ** following:
40253 ** + Discard the cached page (if refcount==0), or
40254 ** + Reload page content from the database (if refcount>0).
40256 pPager->dbSize = pPager->dbOrigSize;
40257 rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
40258 pList = sqlite3PcacheDirtyList(pPager->pPCache);
40259 while( pList && rc==SQLITE_OK ){
40260 PgHdr *pNext = pList->pDirty;
40261 rc = pagerUndoCallback((void *)pPager, pList->pgno);
40262 pList = pNext;
40265 return rc;
40269 ** This function is a wrapper around sqlite3WalFrames(). As well as logging
40270 ** the contents of the list of pages headed by pList (connected by pDirty),
40271 ** this function notifies any active backup processes that the pages have
40272 ** changed.
40274 ** The list of pages passed into this routine is always sorted by page number.
40275 ** Hence, if page 1 appears anywhere on the list, it will be the first page.
40277 static int pagerWalFrames(
40278 Pager *pPager, /* Pager object */
40279 PgHdr *pList, /* List of frames to log */
40280 Pgno nTruncate, /* Database size after this commit */
40281 int isCommit, /* True if this is a commit */
40282 int syncFlags /* Flags to pass to OsSync() (or 0) */
40284 int rc; /* Return code */
40285 #if defined(SQLITE_DEBUG) || defined(SQLITE_CHECK_PAGES)
40286 PgHdr *p; /* For looping over pages */
40287 #endif
40289 assert( pPager->pWal );
40290 assert( pList );
40291 #ifdef SQLITE_DEBUG
40292 /* Verify that the page list is in accending order */
40293 for(p=pList; p && p->pDirty; p=p->pDirty){
40294 assert( p->pgno < p->pDirty->pgno );
40296 #endif
40298 if( isCommit ){
40299 /* If a WAL transaction is being committed, there is no point in writing
40300 ** any pages with page numbers greater than nTruncate into the WAL file.
40301 ** They will never be read by any client. So remove them from the pDirty
40302 ** list here. */
40303 PgHdr *p;
40304 PgHdr **ppNext = &pList;
40305 for(p=pList; (*ppNext = p); p=p->pDirty){
40306 if( p->pgno<=nTruncate ) ppNext = &p->pDirty;
40308 assert( pList );
40311 if( pList->pgno==1 ) pager_write_changecounter(pList);
40312 rc = sqlite3WalFrames(pPager->pWal,
40313 pPager->pageSize, pList, nTruncate, isCommit, syncFlags
40315 if( rc==SQLITE_OK && pPager->pBackup ){
40316 PgHdr *p;
40317 for(p=pList; p; p=p->pDirty){
40318 sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
40322 #ifdef SQLITE_CHECK_PAGES
40323 pList = sqlite3PcacheDirtyList(pPager->pPCache);
40324 for(p=pList; p; p=p->pDirty){
40325 pager_set_pagehash(p);
40327 #endif
40329 return rc;
40333 ** Begin a read transaction on the WAL.
40335 ** This routine used to be called "pagerOpenSnapshot()" because it essentially
40336 ** makes a snapshot of the database at the current point in time and preserves
40337 ** that snapshot for use by the reader in spite of concurrently changes by
40338 ** other writers or checkpointers.
40340 static int pagerBeginReadTransaction(Pager *pPager){
40341 int rc; /* Return code */
40342 int changed = 0; /* True if cache must be reset */
40344 assert( pagerUseWal(pPager) );
40345 assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
40347 /* sqlite3WalEndReadTransaction() was not called for the previous
40348 ** transaction in locking_mode=EXCLUSIVE. So call it now. If we
40349 ** are in locking_mode=NORMAL and EndRead() was previously called,
40350 ** the duplicate call is harmless.
40352 sqlite3WalEndReadTransaction(pPager->pWal);
40354 rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
40355 if( rc!=SQLITE_OK || changed ){
40356 pager_reset(pPager);
40359 return rc;
40361 #endif
40364 ** This function is called as part of the transition from PAGER_OPEN
40365 ** to PAGER_READER state to determine the size of the database file
40366 ** in pages (assuming the page size currently stored in Pager.pageSize).
40368 ** If no error occurs, SQLITE_OK is returned and the size of the database
40369 ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
40370 ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
40372 static int pagerPagecount(Pager *pPager, Pgno *pnPage){
40373 Pgno nPage; /* Value to return via *pnPage */
40375 /* Query the WAL sub-system for the database size. The WalDbsize()
40376 ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
40377 ** if the database size is not available. The database size is not
40378 ** available from the WAL sub-system if the log file is empty or
40379 ** contains no valid committed transactions.
40381 assert( pPager->eState==PAGER_OPEN );
40382 assert( pPager->eLock>=SHARED_LOCK || pPager->noReadlock );
40383 nPage = sqlite3WalDbsize(pPager->pWal);
40385 /* If the database size was not available from the WAL sub-system,
40386 ** determine it based on the size of the database file. If the size
40387 ** of the database file is not an integer multiple of the page-size,
40388 ** round down to the nearest page. Except, any file larger than 0
40389 ** bytes in size is considered to contain at least one page.
40391 if( nPage==0 ){
40392 i64 n = 0; /* Size of db file in bytes */
40393 assert( isOpen(pPager->fd) || pPager->tempFile );
40394 if( isOpen(pPager->fd) ){
40395 int rc = sqlite3OsFileSize(pPager->fd, &n);
40396 if( rc!=SQLITE_OK ){
40397 return rc;
40400 nPage = (Pgno)(n / pPager->pageSize);
40401 if( nPage==0 && n>0 ){
40402 nPage = 1;
40406 /* If the current number of pages in the file is greater than the
40407 ** configured maximum pager number, increase the allowed limit so
40408 ** that the file can be read.
40410 if( nPage>pPager->mxPgno ){
40411 pPager->mxPgno = (Pgno)nPage;
40414 *pnPage = nPage;
40415 return SQLITE_OK;
40418 #ifndef SQLITE_OMIT_WAL
40420 ** Check if the *-wal file that corresponds to the database opened by pPager
40421 ** exists if the database is not empy, or verify that the *-wal file does
40422 ** not exist (by deleting it) if the database file is empty.
40424 ** If the database is not empty and the *-wal file exists, open the pager
40425 ** in WAL mode. If the database is empty or if no *-wal file exists and
40426 ** if no error occurs, make sure Pager.journalMode is not set to
40427 ** PAGER_JOURNALMODE_WAL.
40429 ** Return SQLITE_OK or an error code.
40431 ** The caller must hold a SHARED lock on the database file to call this
40432 ** function. Because an EXCLUSIVE lock on the db file is required to delete
40433 ** a WAL on a none-empty database, this ensures there is no race condition
40434 ** between the xAccess() below and an xDelete() being executed by some
40435 ** other connection.
40437 static int pagerOpenWalIfPresent(Pager *pPager){
40438 int rc = SQLITE_OK;
40439 assert( pPager->eState==PAGER_OPEN );
40440 assert( pPager->eLock>=SHARED_LOCK || pPager->noReadlock );
40442 if( !pPager->tempFile ){
40443 int isWal; /* True if WAL file exists */
40444 Pgno nPage; /* Size of the database file */
40446 rc = pagerPagecount(pPager, &nPage);
40447 if( rc ) return rc;
40448 if( nPage==0 ){
40449 rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
40450 isWal = 0;
40451 }else{
40452 rc = sqlite3OsAccess(
40453 pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
40456 if( rc==SQLITE_OK ){
40457 if( isWal ){
40458 testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
40459 rc = sqlite3PagerOpenWal(pPager, 0);
40460 }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
40461 pPager->journalMode = PAGER_JOURNALMODE_DELETE;
40465 return rc;
40467 #endif
40470 ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
40471 ** the entire master journal file. The case pSavepoint==NULL occurs when
40472 ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
40473 ** savepoint.
40475 ** When pSavepoint is not NULL (meaning a non-transaction savepoint is
40476 ** being rolled back), then the rollback consists of up to three stages,
40477 ** performed in the order specified:
40479 ** * Pages are played back from the main journal starting at byte
40480 ** offset PagerSavepoint.iOffset and continuing to
40481 ** PagerSavepoint.iHdrOffset, or to the end of the main journal
40482 ** file if PagerSavepoint.iHdrOffset is zero.
40484 ** * If PagerSavepoint.iHdrOffset is not zero, then pages are played
40485 ** back starting from the journal header immediately following
40486 ** PagerSavepoint.iHdrOffset to the end of the main journal file.
40488 ** * Pages are then played back from the sub-journal file, starting
40489 ** with the PagerSavepoint.iSubRec and continuing to the end of
40490 ** the journal file.
40492 ** Throughout the rollback process, each time a page is rolled back, the
40493 ** corresponding bit is set in a bitvec structure (variable pDone in the
40494 ** implementation below). This is used to ensure that a page is only
40495 ** rolled back the first time it is encountered in either journal.
40497 ** If pSavepoint is NULL, then pages are only played back from the main
40498 ** journal file. There is no need for a bitvec in this case.
40500 ** In either case, before playback commences the Pager.dbSize variable
40501 ** is reset to the value that it held at the start of the savepoint
40502 ** (or transaction). No page with a page-number greater than this value
40503 ** is played back. If one is encountered it is simply skipped.
40505 static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
40506 i64 szJ; /* Effective size of the main journal */
40507 i64 iHdrOff; /* End of first segment of main-journal records */
40508 int rc = SQLITE_OK; /* Return code */
40509 Bitvec *pDone = 0; /* Bitvec to ensure pages played back only once */
40511 assert( pPager->eState!=PAGER_ERROR );
40512 assert( pPager->eState>=PAGER_WRITER_LOCKED );
40514 /* Allocate a bitvec to use to store the set of pages rolled back */
40515 if( pSavepoint ){
40516 pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
40517 if( !pDone ){
40518 return SQLITE_NOMEM;
40522 /* Set the database size back to the value it was before the savepoint
40523 ** being reverted was opened.
40525 pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
40526 pPager->changeCountDone = pPager->tempFile;
40528 if( !pSavepoint && pagerUseWal(pPager) ){
40529 return pagerRollbackWal(pPager);
40532 /* Use pPager->journalOff as the effective size of the main rollback
40533 ** journal. The actual file might be larger than this in
40534 ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST. But anything
40535 ** past pPager->journalOff is off-limits to us.
40537 szJ = pPager->journalOff;
40538 assert( pagerUseWal(pPager)==0 || szJ==0 );
40540 /* Begin by rolling back records from the main journal starting at
40541 ** PagerSavepoint.iOffset and continuing to the next journal header.
40542 ** There might be records in the main journal that have a page number
40543 ** greater than the current database size (pPager->dbSize) but those
40544 ** will be skipped automatically. Pages are added to pDone as they
40545 ** are played back.
40547 if( pSavepoint && !pagerUseWal(pPager) ){
40548 iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
40549 pPager->journalOff = pSavepoint->iOffset;
40550 while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
40551 rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
40553 assert( rc!=SQLITE_DONE );
40554 }else{
40555 pPager->journalOff = 0;
40558 /* Continue rolling back records out of the main journal starting at
40559 ** the first journal header seen and continuing until the effective end
40560 ** of the main journal file. Continue to skip out-of-range pages and
40561 ** continue adding pages rolled back to pDone.
40563 while( rc==SQLITE_OK && pPager->journalOff<szJ ){
40564 u32 ii; /* Loop counter */
40565 u32 nJRec = 0; /* Number of Journal Records */
40566 u32 dummy;
40567 rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
40568 assert( rc!=SQLITE_DONE );
40571 ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
40572 ** test is related to ticket #2565. See the discussion in the
40573 ** pager_playback() function for additional information.
40575 if( nJRec==0
40576 && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
40578 nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
40580 for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
40581 rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
40583 assert( rc!=SQLITE_DONE );
40585 assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
40587 /* Finally, rollback pages from the sub-journal. Page that were
40588 ** previously rolled back out of the main journal (and are hence in pDone)
40589 ** will be skipped. Out-of-range pages are also skipped.
40591 if( pSavepoint ){
40592 u32 ii; /* Loop counter */
40593 i64 offset = pSavepoint->iSubRec*(4+pPager->pageSize);
40595 if( pagerUseWal(pPager) ){
40596 rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
40598 for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
40599 assert( offset==ii*(4+pPager->pageSize) );
40600 rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
40602 assert( rc!=SQLITE_DONE );
40605 sqlite3BitvecDestroy(pDone);
40606 if( rc==SQLITE_OK ){
40607 pPager->journalOff = szJ;
40610 return rc;
40614 ** Change the maximum number of in-memory pages that are allowed.
40616 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
40617 sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
40621 ** Adjust the robustness of the database to damage due to OS crashes
40622 ** or power failures by changing the number of syncs()s when writing
40623 ** the rollback journal. There are three levels:
40625 ** OFF sqlite3OsSync() is never called. This is the default
40626 ** for temporary and transient files.
40628 ** NORMAL The journal is synced once before writes begin on the
40629 ** database. This is normally adequate protection, but
40630 ** it is theoretically possible, though very unlikely,
40631 ** that an inopertune power failure could leave the journal
40632 ** in a state which would cause damage to the database
40633 ** when it is rolled back.
40635 ** FULL The journal is synced twice before writes begin on the
40636 ** database (with some additional information - the nRec field
40637 ** of the journal header - being written in between the two
40638 ** syncs). If we assume that writing a
40639 ** single disk sector is atomic, then this mode provides
40640 ** assurance that the journal will not be corrupted to the
40641 ** point of causing damage to the database during rollback.
40643 ** The above is for a rollback-journal mode. For WAL mode, OFF continues
40644 ** to mean that no syncs ever occur. NORMAL means that the WAL is synced
40645 ** prior to the start of checkpoint and that the database file is synced
40646 ** at the conclusion of the checkpoint if the entire content of the WAL
40647 ** was written back into the database. But no sync operations occur for
40648 ** an ordinary commit in NORMAL mode with WAL. FULL means that the WAL
40649 ** file is synced following each commit operation, in addition to the
40650 ** syncs associated with NORMAL.
40652 ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL. The
40653 ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
40654 ** using fcntl(F_FULLFSYNC). SQLITE_SYNC_NORMAL means to do an
40655 ** ordinary fsync() call. There is no difference between SQLITE_SYNC_FULL
40656 ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX. But the
40657 ** synchronous=FULL versus synchronous=NORMAL setting determines when
40658 ** the xSync primitive is called and is relevant to all platforms.
40660 ** Numeric values associated with these states are OFF==1, NORMAL=2,
40661 ** and FULL=3.
40663 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
40664 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(
40665 Pager *pPager, /* The pager to set safety level for */
40666 int level, /* PRAGMA synchronous. 1=OFF, 2=NORMAL, 3=FULL */
40667 int bFullFsync, /* PRAGMA fullfsync */
40668 int bCkptFullFsync /* PRAGMA checkpoint_fullfsync */
40670 assert( level>=1 && level<=3 );
40671 pPager->noSync = (level==1 || pPager->tempFile) ?1:0;
40672 pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
40673 if( pPager->noSync ){
40674 pPager->syncFlags = 0;
40675 pPager->ckptSyncFlags = 0;
40676 }else if( bFullFsync ){
40677 pPager->syncFlags = SQLITE_SYNC_FULL;
40678 pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
40679 }else if( bCkptFullFsync ){
40680 pPager->syncFlags = SQLITE_SYNC_NORMAL;
40681 pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
40682 }else{
40683 pPager->syncFlags = SQLITE_SYNC_NORMAL;
40684 pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
40687 #endif
40690 ** The following global variable is incremented whenever the library
40691 ** attempts to open a temporary file. This information is used for
40692 ** testing and analysis only.
40694 #ifdef SQLITE_TEST
40695 SQLITE_API int sqlite3_opentemp_count = 0;
40696 #endif
40699 ** Open a temporary file.
40701 ** Write the file descriptor into *pFile. Return SQLITE_OK on success
40702 ** or some other error code if we fail. The OS will automatically
40703 ** delete the temporary file when it is closed.
40705 ** The flags passed to the VFS layer xOpen() call are those specified
40706 ** by parameter vfsFlags ORed with the following:
40708 ** SQLITE_OPEN_READWRITE
40709 ** SQLITE_OPEN_CREATE
40710 ** SQLITE_OPEN_EXCLUSIVE
40711 ** SQLITE_OPEN_DELETEONCLOSE
40713 static int pagerOpentemp(
40714 Pager *pPager, /* The pager object */
40715 sqlite3_file *pFile, /* Write the file descriptor here */
40716 int vfsFlags /* Flags passed through to the VFS */
40718 int rc; /* Return code */
40720 #ifdef SQLITE_TEST
40721 sqlite3_opentemp_count++; /* Used for testing and analysis only */
40722 #endif
40724 vfsFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
40725 SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
40726 rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
40727 assert( rc!=SQLITE_OK || isOpen(pFile) );
40728 return rc;
40732 ** Set the busy handler function.
40734 ** The pager invokes the busy-handler if sqlite3OsLock() returns
40735 ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
40736 ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
40737 ** lock. It does *not* invoke the busy handler when upgrading from
40738 ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
40739 ** (which occurs during hot-journal rollback). Summary:
40741 ** Transition | Invokes xBusyHandler
40742 ** --------------------------------------------------------
40743 ** NO_LOCK -> SHARED_LOCK | Yes
40744 ** SHARED_LOCK -> RESERVED_LOCK | No
40745 ** SHARED_LOCK -> EXCLUSIVE_LOCK | No
40746 ** RESERVED_LOCK -> EXCLUSIVE_LOCK | Yes
40748 ** If the busy-handler callback returns non-zero, the lock is
40749 ** retried. If it returns zero, then the SQLITE_BUSY error is
40750 ** returned to the caller of the pager API function.
40752 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
40753 Pager *pPager, /* Pager object */
40754 int (*xBusyHandler)(void *), /* Pointer to busy-handler function */
40755 void *pBusyHandlerArg /* Argument to pass to xBusyHandler */
40757 pPager->xBusyHandler = xBusyHandler;
40758 pPager->pBusyHandlerArg = pBusyHandlerArg;
40762 ** Change the page size used by the Pager object. The new page size
40763 ** is passed in *pPageSize.
40765 ** If the pager is in the error state when this function is called, it
40766 ** is a no-op. The value returned is the error state error code (i.e.
40767 ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
40769 ** Otherwise, if all of the following are true:
40771 ** * the new page size (value of *pPageSize) is valid (a power
40772 ** of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
40774 ** * there are no outstanding page references, and
40776 ** * the database is either not an in-memory database or it is
40777 ** an in-memory database that currently consists of zero pages.
40779 ** then the pager object page size is set to *pPageSize.
40781 ** If the page size is changed, then this function uses sqlite3PagerMalloc()
40782 ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
40783 ** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
40784 ** In all other cases, SQLITE_OK is returned.
40786 ** If the page size is not changed, either because one of the enumerated
40787 ** conditions above is not true, the pager was in error state when this
40788 ** function was called, or because the memory allocation attempt failed,
40789 ** then *pPageSize is set to the old, retained page size before returning.
40791 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
40792 int rc = SQLITE_OK;
40794 /* It is not possible to do a full assert_pager_state() here, as this
40795 ** function may be called from within PagerOpen(), before the state
40796 ** of the Pager object is internally consistent.
40798 ** At one point this function returned an error if the pager was in
40799 ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
40800 ** there is at least one outstanding page reference, this function
40801 ** is a no-op for that case anyhow.
40804 u32 pageSize = *pPageSize;
40805 assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
40806 if( (pPager->memDb==0 || pPager->dbSize==0)
40807 && sqlite3PcacheRefCount(pPager->pPCache)==0
40808 && pageSize && pageSize!=(u32)pPager->pageSize
40810 char *pNew = NULL; /* New temp space */
40811 i64 nByte = 0;
40813 if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
40814 rc = sqlite3OsFileSize(pPager->fd, &nByte);
40816 if( rc==SQLITE_OK ){
40817 pNew = (char *)sqlite3PageMalloc(pageSize);
40818 if( !pNew ) rc = SQLITE_NOMEM;
40821 if( rc==SQLITE_OK ){
40822 pager_reset(pPager);
40823 pPager->dbSize = (Pgno)(nByte/pageSize);
40824 pPager->pageSize = pageSize;
40825 sqlite3PageFree(pPager->pTmpSpace);
40826 pPager->pTmpSpace = pNew;
40827 sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
40831 *pPageSize = pPager->pageSize;
40832 if( rc==SQLITE_OK ){
40833 if( nReserve<0 ) nReserve = pPager->nReserve;
40834 assert( nReserve>=0 && nReserve<1000 );
40835 pPager->nReserve = (i16)nReserve;
40836 pagerReportSize(pPager);
40838 return rc;
40842 ** Return a pointer to the "temporary page" buffer held internally
40843 ** by the pager. This is a buffer that is big enough to hold the
40844 ** entire content of a database page. This buffer is used internally
40845 ** during rollback and will be overwritten whenever a rollback
40846 ** occurs. But other modules are free to use it too, as long as
40847 ** no rollbacks are happening.
40849 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
40850 return pPager->pTmpSpace;
40854 ** Attempt to set the maximum database page count if mxPage is positive.
40855 ** Make no changes if mxPage is zero or negative. And never reduce the
40856 ** maximum page count below the current size of the database.
40858 ** Regardless of mxPage, return the current maximum page count.
40860 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
40861 if( mxPage>0 ){
40862 pPager->mxPgno = mxPage;
40864 assert( pPager->eState!=PAGER_OPEN ); /* Called only by OP_MaxPgcnt */
40865 assert( pPager->mxPgno>=pPager->dbSize ); /* OP_MaxPgcnt enforces this */
40866 return pPager->mxPgno;
40870 ** The following set of routines are used to disable the simulated
40871 ** I/O error mechanism. These routines are used to avoid simulated
40872 ** errors in places where we do not care about errors.
40874 ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
40875 ** and generate no code.
40877 #ifdef SQLITE_TEST
40878 SQLITE_API extern int sqlite3_io_error_pending;
40879 SQLITE_API extern int sqlite3_io_error_hit;
40880 static int saved_cnt;
40881 void disable_simulated_io_errors(void){
40882 saved_cnt = sqlite3_io_error_pending;
40883 sqlite3_io_error_pending = -1;
40885 void enable_simulated_io_errors(void){
40886 sqlite3_io_error_pending = saved_cnt;
40888 #else
40889 # define disable_simulated_io_errors()
40890 # define enable_simulated_io_errors()
40891 #endif
40894 ** Read the first N bytes from the beginning of the file into memory
40895 ** that pDest points to.
40897 ** If the pager was opened on a transient file (zFilename==""), or
40898 ** opened on a file less than N bytes in size, the output buffer is
40899 ** zeroed and SQLITE_OK returned. The rationale for this is that this
40900 ** function is used to read database headers, and a new transient or
40901 ** zero sized database has a header than consists entirely of zeroes.
40903 ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
40904 ** the error code is returned to the caller and the contents of the
40905 ** output buffer undefined.
40907 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
40908 int rc = SQLITE_OK;
40909 memset(pDest, 0, N);
40910 assert( isOpen(pPager->fd) || pPager->tempFile );
40912 /* This routine is only called by btree immediately after creating
40913 ** the Pager object. There has not been an opportunity to transition
40914 ** to WAL mode yet.
40916 assert( !pagerUseWal(pPager) );
40918 if( isOpen(pPager->fd) ){
40919 IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
40920 rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
40921 if( rc==SQLITE_IOERR_SHORT_READ ){
40922 rc = SQLITE_OK;
40925 return rc;
40929 ** This function may only be called when a read-transaction is open on
40930 ** the pager. It returns the total number of pages in the database.
40932 ** However, if the file is between 1 and <page-size> bytes in size, then
40933 ** this is considered a 1 page file.
40935 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
40936 assert( pPager->eState>=PAGER_READER );
40937 assert( pPager->eState!=PAGER_WRITER_FINISHED );
40938 *pnPage = (int)pPager->dbSize;
40943 ** Try to obtain a lock of type locktype on the database file. If
40944 ** a similar or greater lock is already held, this function is a no-op
40945 ** (returning SQLITE_OK immediately).
40947 ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
40948 ** the busy callback if the lock is currently not available. Repeat
40949 ** until the busy callback returns false or until the attempt to
40950 ** obtain the lock succeeds.
40952 ** Return SQLITE_OK on success and an error code if we cannot obtain
40953 ** the lock. If the lock is obtained successfully, set the Pager.state
40954 ** variable to locktype before returning.
40956 static int pager_wait_on_lock(Pager *pPager, int locktype){
40957 int rc; /* Return code */
40959 /* Check that this is either a no-op (because the requested lock is
40960 ** already held, or one of the transistions that the busy-handler
40961 ** may be invoked during, according to the comment above
40962 ** sqlite3PagerSetBusyhandler().
40964 assert( (pPager->eLock>=locktype)
40965 || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
40966 || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
40969 do {
40970 rc = pagerLockDb(pPager, locktype);
40971 }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
40972 return rc;
40976 ** Function assertTruncateConstraint(pPager) checks that one of the
40977 ** following is true for all dirty pages currently in the page-cache:
40979 ** a) The page number is less than or equal to the size of the
40980 ** current database image, in pages, OR
40982 ** b) if the page content were written at this time, it would not
40983 ** be necessary to write the current content out to the sub-journal
40984 ** (as determined by function subjRequiresPage()).
40986 ** If the condition asserted by this function were not true, and the
40987 ** dirty page were to be discarded from the cache via the pagerStress()
40988 ** routine, pagerStress() would not write the current page content to
40989 ** the database file. If a savepoint transaction were rolled back after
40990 ** this happened, the correct behaviour would be to restore the current
40991 ** content of the page. However, since this content is not present in either
40992 ** the database file or the portion of the rollback journal and
40993 ** sub-journal rolled back the content could not be restored and the
40994 ** database image would become corrupt. It is therefore fortunate that
40995 ** this circumstance cannot arise.
40997 #if defined(SQLITE_DEBUG)
40998 static void assertTruncateConstraintCb(PgHdr *pPg){
40999 assert( pPg->flags&PGHDR_DIRTY );
41000 assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
41002 static void assertTruncateConstraint(Pager *pPager){
41003 sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
41005 #else
41006 # define assertTruncateConstraint(pPager)
41007 #endif
41010 ** Truncate the in-memory database file image to nPage pages. This
41011 ** function does not actually modify the database file on disk. It
41012 ** just sets the internal state of the pager object so that the
41013 ** truncation will be done when the current transaction is committed.
41015 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
41016 assert( pPager->dbSize>=nPage );
41017 assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
41018 pPager->dbSize = nPage;
41019 assertTruncateConstraint(pPager);
41024 ** This function is called before attempting a hot-journal rollback. It
41025 ** syncs the journal file to disk, then sets pPager->journalHdr to the
41026 ** size of the journal file so that the pager_playback() routine knows
41027 ** that the entire journal file has been synced.
41029 ** Syncing a hot-journal to disk before attempting to roll it back ensures
41030 ** that if a power-failure occurs during the rollback, the process that
41031 ** attempts rollback following system recovery sees the same journal
41032 ** content as this process.
41034 ** If everything goes as planned, SQLITE_OK is returned. Otherwise,
41035 ** an SQLite error code.
41037 static int pagerSyncHotJournal(Pager *pPager){
41038 int rc = SQLITE_OK;
41039 if( !pPager->noSync ){
41040 rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
41042 if( rc==SQLITE_OK ){
41043 rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
41045 return rc;
41049 ** Shutdown the page cache. Free all memory and close all files.
41051 ** If a transaction was in progress when this routine is called, that
41052 ** transaction is rolled back. All outstanding pages are invalidated
41053 ** and their memory is freed. Any attempt to use a page associated
41054 ** with this page cache after this function returns will likely
41055 ** result in a coredump.
41057 ** This function always succeeds. If a transaction is active an attempt
41058 ** is made to roll it back. If an error occurs during the rollback
41059 ** a hot journal may be left in the filesystem but no error is returned
41060 ** to the caller.
41062 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
41063 u8 *pTmp = (u8 *)pPager->pTmpSpace;
41065 assert( assert_pager_state(pPager) );
41066 disable_simulated_io_errors();
41067 sqlite3BeginBenignMalloc();
41068 /* pPager->errCode = 0; */
41069 pPager->exclusiveMode = 0;
41070 #ifndef SQLITE_OMIT_WAL
41071 sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
41072 pPager->pWal = 0;
41073 #endif
41074 pager_reset(pPager);
41075 if( MEMDB ){
41076 pager_unlock(pPager);
41077 }else{
41078 /* If it is open, sync the journal file before calling UnlockAndRollback.
41079 ** If this is not done, then an unsynced portion of the open journal
41080 ** file may be played back into the database. If a power failure occurs
41081 ** while this is happening, the database could become corrupt.
41083 ** If an error occurs while trying to sync the journal, shift the pager
41084 ** into the ERROR state. This causes UnlockAndRollback to unlock the
41085 ** database and close the journal file without attempting to roll it
41086 ** back or finalize it. The next database user will have to do hot-journal
41087 ** rollback before accessing the database file.
41089 if( isOpen(pPager->jfd) ){
41090 pager_error(pPager, pagerSyncHotJournal(pPager));
41092 pagerUnlockAndRollback(pPager);
41094 sqlite3EndBenignMalloc();
41095 enable_simulated_io_errors();
41096 PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
41097 IOTRACE(("CLOSE %p\n", pPager))
41098 sqlite3OsClose(pPager->jfd);
41099 sqlite3OsClose(pPager->fd);
41100 sqlite3PageFree(pTmp);
41101 sqlite3PcacheClose(pPager->pPCache);
41103 #ifdef SQLITE_HAS_CODEC
41104 if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
41105 #endif
41107 assert( !pPager->aSavepoint && !pPager->pInJournal );
41108 assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
41110 sqlite3_free(pPager);
41111 return SQLITE_OK;
41114 #if !defined(NDEBUG) || defined(SQLITE_TEST)
41116 ** Return the page number for page pPg.
41118 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
41119 return pPg->pgno;
41121 #endif
41124 ** Increment the reference count for page pPg.
41126 SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
41127 sqlite3PcacheRef(pPg);
41131 ** Sync the journal. In other words, make sure all the pages that have
41132 ** been written to the journal have actually reached the surface of the
41133 ** disk and can be restored in the event of a hot-journal rollback.
41135 ** If the Pager.noSync flag is set, then this function is a no-op.
41136 ** Otherwise, the actions required depend on the journal-mode and the
41137 ** device characteristics of the the file-system, as follows:
41139 ** * If the journal file is an in-memory journal file, no action need
41140 ** be taken.
41142 ** * Otherwise, if the device does not support the SAFE_APPEND property,
41143 ** then the nRec field of the most recently written journal header
41144 ** is updated to contain the number of journal records that have
41145 ** been written following it. If the pager is operating in full-sync
41146 ** mode, then the journal file is synced before this field is updated.
41148 ** * If the device does not support the SEQUENTIAL property, then
41149 ** journal file is synced.
41151 ** Or, in pseudo-code:
41153 ** if( NOT <in-memory journal> ){
41154 ** if( NOT SAFE_APPEND ){
41155 ** if( <full-sync mode> ) xSync(<journal file>);
41156 ** <update nRec field>
41157 ** }
41158 ** if( NOT SEQUENTIAL ) xSync(<journal file>);
41159 ** }
41161 ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
41162 ** page currently held in memory before returning SQLITE_OK. If an IO
41163 ** error is encountered, then the IO error code is returned to the caller.
41165 static int syncJournal(Pager *pPager, int newHdr){
41166 int rc; /* Return code */
41168 assert( pPager->eState==PAGER_WRITER_CACHEMOD
41169 || pPager->eState==PAGER_WRITER_DBMOD
41171 assert( assert_pager_state(pPager) );
41172 assert( !pagerUseWal(pPager) );
41174 rc = sqlite3PagerExclusiveLock(pPager);
41175 if( rc!=SQLITE_OK ) return rc;
41177 if( !pPager->noSync ){
41178 assert( !pPager->tempFile );
41179 if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
41180 const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
41181 assert( isOpen(pPager->jfd) );
41183 if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
41184 /* This block deals with an obscure problem. If the last connection
41185 ** that wrote to this database was operating in persistent-journal
41186 ** mode, then the journal file may at this point actually be larger
41187 ** than Pager.journalOff bytes. If the next thing in the journal
41188 ** file happens to be a journal-header (written as part of the
41189 ** previous connection's transaction), and a crash or power-failure
41190 ** occurs after nRec is updated but before this connection writes
41191 ** anything else to the journal file (or commits/rolls back its
41192 ** transaction), then SQLite may become confused when doing the
41193 ** hot-journal rollback following recovery. It may roll back all
41194 ** of this connections data, then proceed to rolling back the old,
41195 ** out-of-date data that follows it. Database corruption.
41197 ** To work around this, if the journal file does appear to contain
41198 ** a valid header following Pager.journalOff, then write a 0x00
41199 ** byte to the start of it to prevent it from being recognized.
41201 ** Variable iNextHdrOffset is set to the offset at which this
41202 ** problematic header will occur, if it exists. aMagic is used
41203 ** as a temporary buffer to inspect the first couple of bytes of
41204 ** the potential journal header.
41206 i64 iNextHdrOffset;
41207 u8 aMagic[8];
41208 u8 zHeader[sizeof(aJournalMagic)+4];
41210 memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
41211 put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
41213 iNextHdrOffset = journalHdrOffset(pPager);
41214 rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
41215 if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
41216 static const u8 zerobyte = 0;
41217 rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
41219 if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
41220 return rc;
41223 /* Write the nRec value into the journal file header. If in
41224 ** full-synchronous mode, sync the journal first. This ensures that
41225 ** all data has really hit the disk before nRec is updated to mark
41226 ** it as a candidate for rollback.
41228 ** This is not required if the persistent media supports the
41229 ** SAFE_APPEND property. Because in this case it is not possible
41230 ** for garbage data to be appended to the file, the nRec field
41231 ** is populated with 0xFFFFFFFF when the journal header is written
41232 ** and never needs to be updated.
41234 if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
41235 PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
41236 IOTRACE(("JSYNC %p\n", pPager))
41237 rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
41238 if( rc!=SQLITE_OK ) return rc;
41240 IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
41241 rc = sqlite3OsWrite(
41242 pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
41244 if( rc!=SQLITE_OK ) return rc;
41246 if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
41247 PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
41248 IOTRACE(("JSYNC %p\n", pPager))
41249 rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
41250 (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
41252 if( rc!=SQLITE_OK ) return rc;
41255 pPager->journalHdr = pPager->journalOff;
41256 if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
41257 pPager->nRec = 0;
41258 rc = writeJournalHdr(pPager);
41259 if( rc!=SQLITE_OK ) return rc;
41261 }else{
41262 pPager->journalHdr = pPager->journalOff;
41266 /* Unless the pager is in noSync mode, the journal file was just
41267 ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
41268 ** all pages.
41270 sqlite3PcacheClearSyncFlags(pPager->pPCache);
41271 pPager->eState = PAGER_WRITER_DBMOD;
41272 assert( assert_pager_state(pPager) );
41273 return SQLITE_OK;
41277 ** The argument is the first in a linked list of dirty pages connected
41278 ** by the PgHdr.pDirty pointer. This function writes each one of the
41279 ** in-memory pages in the list to the database file. The argument may
41280 ** be NULL, representing an empty list. In this case this function is
41281 ** a no-op.
41283 ** The pager must hold at least a RESERVED lock when this function
41284 ** is called. Before writing anything to the database file, this lock
41285 ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
41286 ** SQLITE_BUSY is returned and no data is written to the database file.
41288 ** If the pager is a temp-file pager and the actual file-system file
41289 ** is not yet open, it is created and opened before any data is
41290 ** written out.
41292 ** Once the lock has been upgraded and, if necessary, the file opened,
41293 ** the pages are written out to the database file in list order. Writing
41294 ** a page is skipped if it meets either of the following criteria:
41296 ** * The page number is greater than Pager.dbSize, or
41297 ** * The PGHDR_DONT_WRITE flag is set on the page.
41299 ** If writing out a page causes the database file to grow, Pager.dbFileSize
41300 ** is updated accordingly. If page 1 is written out, then the value cached
41301 ** in Pager.dbFileVers[] is updated to match the new value stored in
41302 ** the database file.
41304 ** If everything is successful, SQLITE_OK is returned. If an IO error
41305 ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
41306 ** be obtained, SQLITE_BUSY is returned.
41308 static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
41309 int rc = SQLITE_OK; /* Return code */
41311 /* This function is only called for rollback pagers in WRITER_DBMOD state. */
41312 assert( !pagerUseWal(pPager) );
41313 assert( pPager->eState==PAGER_WRITER_DBMOD );
41314 assert( pPager->eLock==EXCLUSIVE_LOCK );
41316 /* If the file is a temp-file has not yet been opened, open it now. It
41317 ** is not possible for rc to be other than SQLITE_OK if this branch
41318 ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
41320 if( !isOpen(pPager->fd) ){
41321 assert( pPager->tempFile && rc==SQLITE_OK );
41322 rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
41325 /* Before the first write, give the VFS a hint of what the final
41326 ** file size will be.
41328 assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
41329 if( rc==SQLITE_OK && pPager->dbSize>pPager->dbHintSize ){
41330 sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
41331 sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
41332 pPager->dbHintSize = pPager->dbSize;
41335 while( rc==SQLITE_OK && pList ){
41336 Pgno pgno = pList->pgno;
41338 /* If there are dirty pages in the page cache with page numbers greater
41339 ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
41340 ** make the file smaller (presumably by auto-vacuum code). Do not write
41341 ** any such pages to the file.
41343 ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
41344 ** set (set by sqlite3PagerDontWrite()).
41346 if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
41347 i64 offset = (pgno-1)*(i64)pPager->pageSize; /* Offset to write */
41348 char *pData; /* Data to write */
41350 assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
41351 if( pList->pgno==1 ) pager_write_changecounter(pList);
41353 /* Encode the database */
41354 CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
41356 /* Write out the page data. */
41357 rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
41359 /* If page 1 was just written, update Pager.dbFileVers to match
41360 ** the value now stored in the database file. If writing this
41361 ** page caused the database file to grow, update dbFileSize.
41363 if( pgno==1 ){
41364 memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
41366 if( pgno>pPager->dbFileSize ){
41367 pPager->dbFileSize = pgno;
41370 /* Update any backup objects copying the contents of this pager. */
41371 sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
41373 PAGERTRACE(("STORE %d page %d hash(%08x)\n",
41374 PAGERID(pPager), pgno, pager_pagehash(pList)));
41375 IOTRACE(("PGOUT %p %d\n", pPager, pgno));
41376 PAGER_INCR(sqlite3_pager_writedb_count);
41377 PAGER_INCR(pPager->nWrite);
41378 }else{
41379 PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
41381 pager_set_pagehash(pList);
41382 pList = pList->pDirty;
41385 return rc;
41389 ** Ensure that the sub-journal file is open. If it is already open, this
41390 ** function is a no-op.
41392 ** SQLITE_OK is returned if everything goes according to plan. An
41393 ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
41394 ** fails.
41396 static int openSubJournal(Pager *pPager){
41397 int rc = SQLITE_OK;
41398 if( !isOpen(pPager->sjfd) ){
41399 if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
41400 sqlite3MemJournalOpen(pPager->sjfd);
41401 }else{
41402 rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
41405 return rc;
41409 ** Append a record of the current state of page pPg to the sub-journal.
41410 ** It is the callers responsibility to use subjRequiresPage() to check
41411 ** that it is really required before calling this function.
41413 ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
41414 ** for all open savepoints before returning.
41416 ** This function returns SQLITE_OK if everything is successful, an IO
41417 ** error code if the attempt to write to the sub-journal fails, or
41418 ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
41419 ** bitvec.
41421 static int subjournalPage(PgHdr *pPg){
41422 int rc = SQLITE_OK;
41423 Pager *pPager = pPg->pPager;
41424 if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
41426 /* Open the sub-journal, if it has not already been opened */
41427 assert( pPager->useJournal );
41428 assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
41429 assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
41430 assert( pagerUseWal(pPager)
41431 || pageInJournal(pPg)
41432 || pPg->pgno>pPager->dbOrigSize
41434 rc = openSubJournal(pPager);
41436 /* If the sub-journal was opened successfully (or was already open),
41437 ** write the journal record into the file. */
41438 if( rc==SQLITE_OK ){
41439 void *pData = pPg->pData;
41440 i64 offset = pPager->nSubRec*(4+pPager->pageSize);
41441 char *pData2;
41443 CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
41444 PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
41445 rc = write32bits(pPager->sjfd, offset, pPg->pgno);
41446 if( rc==SQLITE_OK ){
41447 rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
41451 if( rc==SQLITE_OK ){
41452 pPager->nSubRec++;
41453 assert( pPager->nSavepoint>0 );
41454 rc = addToSavepointBitvecs(pPager, pPg->pgno);
41456 return rc;
41460 ** This function is called by the pcache layer when it has reached some
41461 ** soft memory limit. The first argument is a pointer to a Pager object
41462 ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
41463 ** database). The second argument is a reference to a page that is
41464 ** currently dirty but has no outstanding references. The page
41465 ** is always associated with the Pager object passed as the first
41466 ** argument.
41468 ** The job of this function is to make pPg clean by writing its contents
41469 ** out to the database file, if possible. This may involve syncing the
41470 ** journal file.
41472 ** If successful, sqlite3PcacheMakeClean() is called on the page and
41473 ** SQLITE_OK returned. If an IO error occurs while trying to make the
41474 ** page clean, the IO error code is returned. If the page cannot be
41475 ** made clean for some other reason, but no error occurs, then SQLITE_OK
41476 ** is returned by sqlite3PcacheMakeClean() is not called.
41478 static int pagerStress(void *p, PgHdr *pPg){
41479 Pager *pPager = (Pager *)p;
41480 int rc = SQLITE_OK;
41482 assert( pPg->pPager==pPager );
41483 assert( pPg->flags&PGHDR_DIRTY );
41485 /* The doNotSyncSpill flag is set during times when doing a sync of
41486 ** journal (and adding a new header) is not allowed. This occurs
41487 ** during calls to sqlite3PagerWrite() while trying to journal multiple
41488 ** pages belonging to the same sector.
41490 ** The doNotSpill flag inhibits all cache spilling regardless of whether
41491 ** or not a sync is required. This is set during a rollback.
41493 ** Spilling is also prohibited when in an error state since that could
41494 ** lead to database corruption. In the current implementaton it
41495 ** is impossible for sqlite3PcacheFetch() to be called with createFlag==1
41496 ** while in the error state, hence it is impossible for this routine to
41497 ** be called in the error state. Nevertheless, we include a NEVER()
41498 ** test for the error state as a safeguard against future changes.
41500 if( NEVER(pPager->errCode) ) return SQLITE_OK;
41501 if( pPager->doNotSpill ) return SQLITE_OK;
41502 if( pPager->doNotSyncSpill && (pPg->flags & PGHDR_NEED_SYNC)!=0 ){
41503 return SQLITE_OK;
41506 pPg->pDirty = 0;
41507 if( pagerUseWal(pPager) ){
41508 /* Write a single frame for this page to the log. */
41509 if( subjRequiresPage(pPg) ){
41510 rc = subjournalPage(pPg);
41512 if( rc==SQLITE_OK ){
41513 rc = pagerWalFrames(pPager, pPg, 0, 0, 0);
41515 }else{
41517 /* Sync the journal file if required. */
41518 if( pPg->flags&PGHDR_NEED_SYNC
41519 || pPager->eState==PAGER_WRITER_CACHEMOD
41521 rc = syncJournal(pPager, 1);
41524 /* If the page number of this page is larger than the current size of
41525 ** the database image, it may need to be written to the sub-journal.
41526 ** This is because the call to pager_write_pagelist() below will not
41527 ** actually write data to the file in this case.
41529 ** Consider the following sequence of events:
41531 ** BEGIN;
41532 ** <journal page X>
41533 ** <modify page X>
41534 ** SAVEPOINT sp;
41535 ** <shrink database file to Y pages>
41536 ** pagerStress(page X)
41537 ** ROLLBACK TO sp;
41539 ** If (X>Y), then when pagerStress is called page X will not be written
41540 ** out to the database file, but will be dropped from the cache. Then,
41541 ** following the "ROLLBACK TO sp" statement, reading page X will read
41542 ** data from the database file. This will be the copy of page X as it
41543 ** was when the transaction started, not as it was when "SAVEPOINT sp"
41544 ** was executed.
41546 ** The solution is to write the current data for page X into the
41547 ** sub-journal file now (if it is not already there), so that it will
41548 ** be restored to its current value when the "ROLLBACK TO sp" is
41549 ** executed.
41551 if( NEVER(
41552 rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
41553 ) ){
41554 rc = subjournalPage(pPg);
41557 /* Write the contents of the page out to the database file. */
41558 if( rc==SQLITE_OK ){
41559 assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
41560 rc = pager_write_pagelist(pPager, pPg);
41564 /* Mark the page as clean. */
41565 if( rc==SQLITE_OK ){
41566 PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
41567 sqlite3PcacheMakeClean(pPg);
41570 return pager_error(pPager, rc);
41575 ** Allocate and initialize a new Pager object and put a pointer to it
41576 ** in *ppPager. The pager should eventually be freed by passing it
41577 ** to sqlite3PagerClose().
41579 ** The zFilename argument is the path to the database file to open.
41580 ** If zFilename is NULL then a randomly-named temporary file is created
41581 ** and used as the file to be cached. Temporary files are be deleted
41582 ** automatically when they are closed. If zFilename is ":memory:" then
41583 ** all information is held in cache. It is never written to disk.
41584 ** This can be used to implement an in-memory database.
41586 ** The nExtra parameter specifies the number of bytes of space allocated
41587 ** along with each page reference. This space is available to the user
41588 ** via the sqlite3PagerGetExtra() API.
41590 ** The flags argument is used to specify properties that affect the
41591 ** operation of the pager. It should be passed some bitwise combination
41592 ** of the PAGER_OMIT_JOURNAL and PAGER_NO_READLOCK flags.
41594 ** The vfsFlags parameter is a bitmask to pass to the flags parameter
41595 ** of the xOpen() method of the supplied VFS when opening files.
41597 ** If the pager object is allocated and the specified file opened
41598 ** successfully, SQLITE_OK is returned and *ppPager set to point to
41599 ** the new pager object. If an error occurs, *ppPager is set to NULL
41600 ** and error code returned. This function may return SQLITE_NOMEM
41601 ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
41602 ** various SQLITE_IO_XXX errors.
41604 SQLITE_PRIVATE int sqlite3PagerOpen(
41605 sqlite3_vfs *pVfs, /* The virtual file system to use */
41606 Pager **ppPager, /* OUT: Return the Pager structure here */
41607 const char *zFilename, /* Name of the database file to open */
41608 int nExtra, /* Extra bytes append to each in-memory page */
41609 int flags, /* flags controlling this file */
41610 int vfsFlags, /* flags passed through to sqlite3_vfs.xOpen() */
41611 void (*xReinit)(DbPage*) /* Function to reinitialize pages */
41613 u8 *pPtr;
41614 Pager *pPager = 0; /* Pager object to allocate and return */
41615 int rc = SQLITE_OK; /* Return code */
41616 int tempFile = 0; /* True for temp files (incl. in-memory files) */
41617 int memDb = 0; /* True if this is an in-memory file */
41618 int readOnly = 0; /* True if this is a read-only file */
41619 int journalFileSize; /* Bytes to allocate for each journal fd */
41620 char *zPathname = 0; /* Full path to database file */
41621 int nPathname = 0; /* Number of bytes in zPathname */
41622 int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
41623 int noReadlock = (flags & PAGER_NO_READLOCK)!=0; /* True to omit read-lock */
41624 int pcacheSize = sqlite3PcacheSize(); /* Bytes to allocate for PCache */
41625 u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE; /* Default page size */
41626 const char *zUri = 0; /* URI args to copy */
41627 int nUri = 0; /* Number of bytes of URI args at *zUri */
41629 /* Figure out how much space is required for each journal file-handle
41630 ** (there are two of them, the main journal and the sub-journal). This
41631 ** is the maximum space required for an in-memory journal file handle
41632 ** and a regular journal file-handle. Note that a "regular journal-handle"
41633 ** may be a wrapper capable of caching the first portion of the journal
41634 ** file in memory to implement the atomic-write optimization (see
41635 ** source file journal.c).
41637 if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
41638 journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
41639 }else{
41640 journalFileSize = ROUND8(sqlite3MemJournalSize());
41643 /* Set the output variable to NULL in case an error occurs. */
41644 *ppPager = 0;
41646 #ifndef SQLITE_OMIT_MEMORYDB
41647 if( flags & PAGER_MEMORY ){
41648 memDb = 1;
41649 zFilename = 0;
41651 #endif
41653 /* Compute and store the full pathname in an allocated buffer pointed
41654 ** to by zPathname, length nPathname. Or, if this is a temporary file,
41655 ** leave both nPathname and zPathname set to 0.
41657 if( zFilename && zFilename[0] ){
41658 const char *z;
41659 nPathname = pVfs->mxPathname+1;
41660 zPathname = sqlite3Malloc(nPathname*2);
41661 if( zPathname==0 ){
41662 return SQLITE_NOMEM;
41664 zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
41665 rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
41666 nPathname = sqlite3Strlen30(zPathname);
41667 z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
41668 while( *z ){
41669 z += sqlite3Strlen30(z)+1;
41670 z += sqlite3Strlen30(z)+1;
41672 nUri = &z[1] - zUri;
41673 if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
41674 /* This branch is taken when the journal path required by
41675 ** the database being opened will be more than pVfs->mxPathname
41676 ** bytes in length. This means the database cannot be opened,
41677 ** as it will not be possible to open the journal file or even
41678 ** check for a hot-journal before reading.
41680 rc = SQLITE_CANTOPEN_BKPT;
41682 if( rc!=SQLITE_OK ){
41683 sqlite3_free(zPathname);
41684 return rc;
41688 /* Allocate memory for the Pager structure, PCache object, the
41689 ** three file descriptors, the database file name and the journal
41690 ** file name. The layout in memory is as follows:
41692 ** Pager object (sizeof(Pager) bytes)
41693 ** PCache object (sqlite3PcacheSize() bytes)
41694 ** Database file handle (pVfs->szOsFile bytes)
41695 ** Sub-journal file handle (journalFileSize bytes)
41696 ** Main journal file handle (journalFileSize bytes)
41697 ** Database file name (nPathname+1 bytes)
41698 ** Journal file name (nPathname+8+1 bytes)
41700 pPtr = (u8 *)sqlite3MallocZero(
41701 ROUND8(sizeof(*pPager)) + /* Pager structure */
41702 ROUND8(pcacheSize) + /* PCache object */
41703 ROUND8(pVfs->szOsFile) + /* The main db file */
41704 journalFileSize * 2 + /* The two journal files */
41705 nPathname + 1 + nUri + /* zFilename */
41706 nPathname + 8 + 1 /* zJournal */
41707 #ifndef SQLITE_OMIT_WAL
41708 + nPathname + 4 + 1 /* zWal */
41709 #endif
41711 assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
41712 if( !pPtr ){
41713 sqlite3_free(zPathname);
41714 return SQLITE_NOMEM;
41716 pPager = (Pager*)(pPtr);
41717 pPager->pPCache = (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
41718 pPager->fd = (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
41719 pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
41720 pPager->jfd = (sqlite3_file*)(pPtr += journalFileSize);
41721 pPager->zFilename = (char*)(pPtr += journalFileSize);
41722 assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
41724 /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
41725 if( zPathname ){
41726 assert( nPathname>0 );
41727 pPager->zJournal = (char*)(pPtr += nPathname + 1 + nUri);
41728 memcpy(pPager->zFilename, zPathname, nPathname);
41729 memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
41730 memcpy(pPager->zJournal, zPathname, nPathname);
41731 memcpy(&pPager->zJournal[nPathname], "-journal", 8);
41732 sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
41733 #ifndef SQLITE_OMIT_WAL
41734 pPager->zWal = &pPager->zJournal[nPathname+8+1];
41735 memcpy(pPager->zWal, zPathname, nPathname);
41736 memcpy(&pPager->zWal[nPathname], "-wal", 4);
41737 sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
41738 #endif
41739 sqlite3_free(zPathname);
41741 pPager->pVfs = pVfs;
41742 pPager->vfsFlags = vfsFlags;
41744 /* Open the pager file.
41746 if( zFilename && zFilename[0] ){
41747 int fout = 0; /* VFS flags returned by xOpen() */
41748 rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
41749 assert( !memDb );
41750 readOnly = (fout&SQLITE_OPEN_READONLY);
41752 /* If the file was successfully opened for read/write access,
41753 ** choose a default page size in case we have to create the
41754 ** database file. The default page size is the maximum of:
41756 ** + SQLITE_DEFAULT_PAGE_SIZE,
41757 ** + The value returned by sqlite3OsSectorSize()
41758 ** + The largest page size that can be written atomically.
41760 if( rc==SQLITE_OK && !readOnly ){
41761 setSectorSize(pPager);
41762 assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
41763 if( szPageDflt<pPager->sectorSize ){
41764 if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
41765 szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
41766 }else{
41767 szPageDflt = (u32)pPager->sectorSize;
41770 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
41772 int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
41773 int ii;
41774 assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
41775 assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
41776 assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
41777 for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
41778 if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
41779 szPageDflt = ii;
41783 #endif
41785 }else{
41786 /* If a temporary file is requested, it is not opened immediately.
41787 ** In this case we accept the default page size and delay actually
41788 ** opening the file until the first call to OsWrite().
41790 ** This branch is also run for an in-memory database. An in-memory
41791 ** database is the same as a temp-file that is never written out to
41792 ** disk and uses an in-memory rollback journal.
41794 tempFile = 1;
41795 pPager->eState = PAGER_READER;
41796 pPager->eLock = EXCLUSIVE_LOCK;
41797 readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
41800 /* The following call to PagerSetPagesize() serves to set the value of
41801 ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
41803 if( rc==SQLITE_OK ){
41804 assert( pPager->memDb==0 );
41805 rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
41806 testcase( rc!=SQLITE_OK );
41809 /* If an error occurred in either of the blocks above, free the
41810 ** Pager structure and close the file.
41812 if( rc!=SQLITE_OK ){
41813 assert( !pPager->pTmpSpace );
41814 sqlite3OsClose(pPager->fd);
41815 sqlite3_free(pPager);
41816 return rc;
41819 /* Initialize the PCache object. */
41820 assert( nExtra<1000 );
41821 nExtra = ROUND8(nExtra);
41822 sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
41823 !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
41825 PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
41826 IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
41828 pPager->useJournal = (u8)useJournal;
41829 pPager->noReadlock = (noReadlock && readOnly) ?1:0;
41830 /* pPager->stmtOpen = 0; */
41831 /* pPager->stmtInUse = 0; */
41832 /* pPager->nRef = 0; */
41833 /* pPager->stmtSize = 0; */
41834 /* pPager->stmtJSize = 0; */
41835 /* pPager->nPage = 0; */
41836 pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
41837 /* pPager->state = PAGER_UNLOCK; */
41838 #if 0
41839 assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
41840 #endif
41841 /* pPager->errMask = 0; */
41842 pPager->tempFile = (u8)tempFile;
41843 assert( tempFile==PAGER_LOCKINGMODE_NORMAL
41844 || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
41845 assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
41846 pPager->exclusiveMode = (u8)tempFile;
41847 pPager->changeCountDone = pPager->tempFile;
41848 pPager->memDb = (u8)memDb;
41849 pPager->readOnly = (u8)readOnly;
41850 assert( useJournal || pPager->tempFile );
41851 pPager->noSync = pPager->tempFile;
41852 pPager->fullSync = pPager->noSync ?0:1;
41853 pPager->syncFlags = pPager->noSync ? 0 : SQLITE_SYNC_NORMAL;
41854 pPager->ckptSyncFlags = pPager->syncFlags;
41855 /* pPager->pFirst = 0; */
41856 /* pPager->pFirstSynced = 0; */
41857 /* pPager->pLast = 0; */
41858 pPager->nExtra = (u16)nExtra;
41859 pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
41860 assert( isOpen(pPager->fd) || tempFile );
41861 setSectorSize(pPager);
41862 if( !useJournal ){
41863 pPager->journalMode = PAGER_JOURNALMODE_OFF;
41864 }else if( memDb ){
41865 pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
41867 /* pPager->xBusyHandler = 0; */
41868 /* pPager->pBusyHandlerArg = 0; */
41869 pPager->xReiniter = xReinit;
41870 /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
41872 *ppPager = pPager;
41873 return SQLITE_OK;
41879 ** This function is called after transitioning from PAGER_UNLOCK to
41880 ** PAGER_SHARED state. It tests if there is a hot journal present in
41881 ** the file-system for the given pager. A hot journal is one that
41882 ** needs to be played back. According to this function, a hot-journal
41883 ** file exists if the following criteria are met:
41885 ** * The journal file exists in the file system, and
41886 ** * No process holds a RESERVED or greater lock on the database file, and
41887 ** * The database file itself is greater than 0 bytes in size, and
41888 ** * The first byte of the journal file exists and is not 0x00.
41890 ** If the current size of the database file is 0 but a journal file
41891 ** exists, that is probably an old journal left over from a prior
41892 ** database with the same name. In this case the journal file is
41893 ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
41894 ** is returned.
41896 ** This routine does not check if there is a master journal filename
41897 ** at the end of the file. If there is, and that master journal file
41898 ** does not exist, then the journal file is not really hot. In this
41899 ** case this routine will return a false-positive. The pager_playback()
41900 ** routine will discover that the journal file is not really hot and
41901 ** will not roll it back.
41903 ** If a hot-journal file is found to exist, *pExists is set to 1 and
41904 ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
41905 ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
41906 ** to determine whether or not a hot-journal file exists, the IO error
41907 ** code is returned and the value of *pExists is undefined.
41909 static int hasHotJournal(Pager *pPager, int *pExists){
41910 sqlite3_vfs * const pVfs = pPager->pVfs;
41911 int rc = SQLITE_OK; /* Return code */
41912 int exists = 1; /* True if a journal file is present */
41913 int jrnlOpen = !!isOpen(pPager->jfd);
41915 assert( pPager->useJournal );
41916 assert( isOpen(pPager->fd) );
41917 assert( pPager->eState==PAGER_OPEN );
41919 assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
41920 SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
41923 *pExists = 0;
41924 if( !jrnlOpen ){
41925 rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
41927 if( rc==SQLITE_OK && exists ){
41928 int locked = 0; /* True if some process holds a RESERVED lock */
41930 /* Race condition here: Another process might have been holding the
41931 ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
41932 ** call above, but then delete the journal and drop the lock before
41933 ** we get to the following sqlite3OsCheckReservedLock() call. If that
41934 ** is the case, this routine might think there is a hot journal when
41935 ** in fact there is none. This results in a false-positive which will
41936 ** be dealt with by the playback routine. Ticket #3883.
41938 rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
41939 if( rc==SQLITE_OK && !locked ){
41940 Pgno nPage; /* Number of pages in database file */
41942 /* Check the size of the database file. If it consists of 0 pages,
41943 ** then delete the journal file. See the header comment above for
41944 ** the reasoning here. Delete the obsolete journal file under
41945 ** a RESERVED lock to avoid race conditions and to avoid violating
41946 ** [H33020].
41948 rc = pagerPagecount(pPager, &nPage);
41949 if( rc==SQLITE_OK ){
41950 if( nPage==0 ){
41951 sqlite3BeginBenignMalloc();
41952 if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
41953 sqlite3OsDelete(pVfs, pPager->zJournal, 0);
41954 if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
41956 sqlite3EndBenignMalloc();
41957 }else{
41958 /* The journal file exists and no other connection has a reserved
41959 ** or greater lock on the database file. Now check that there is
41960 ** at least one non-zero bytes at the start of the journal file.
41961 ** If there is, then we consider this journal to be hot. If not,
41962 ** it can be ignored.
41964 if( !jrnlOpen ){
41965 int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
41966 rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
41968 if( rc==SQLITE_OK ){
41969 u8 first = 0;
41970 rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
41971 if( rc==SQLITE_IOERR_SHORT_READ ){
41972 rc = SQLITE_OK;
41974 if( !jrnlOpen ){
41975 sqlite3OsClose(pPager->jfd);
41977 *pExists = (first!=0);
41978 }else if( rc==SQLITE_CANTOPEN ){
41979 /* If we cannot open the rollback journal file in order to see if
41980 ** its has a zero header, that might be due to an I/O error, or
41981 ** it might be due to the race condition described above and in
41982 ** ticket #3883. Either way, assume that the journal is hot.
41983 ** This might be a false positive. But if it is, then the
41984 ** automatic journal playback and recovery mechanism will deal
41985 ** with it under an EXCLUSIVE lock where we do not need to
41986 ** worry so much with race conditions.
41988 *pExists = 1;
41989 rc = SQLITE_OK;
41996 return rc;
42000 ** This function is called to obtain a shared lock on the database file.
42001 ** It is illegal to call sqlite3PagerAcquire() until after this function
42002 ** has been successfully called. If a shared-lock is already held when
42003 ** this function is called, it is a no-op.
42005 ** The following operations are also performed by this function.
42007 ** 1) If the pager is currently in PAGER_OPEN state (no lock held
42008 ** on the database file), then an attempt is made to obtain a
42009 ** SHARED lock on the database file. Immediately after obtaining
42010 ** the SHARED lock, the file-system is checked for a hot-journal,
42011 ** which is played back if present. Following any hot-journal
42012 ** rollback, the contents of the cache are validated by checking
42013 ** the 'change-counter' field of the database file header and
42014 ** discarded if they are found to be invalid.
42016 ** 2) If the pager is running in exclusive-mode, and there are currently
42017 ** no outstanding references to any pages, and is in the error state,
42018 ** then an attempt is made to clear the error state by discarding
42019 ** the contents of the page cache and rolling back any open journal
42020 ** file.
42022 ** If everything is successful, SQLITE_OK is returned. If an IO error
42023 ** occurs while locking the database, checking for a hot-journal file or
42024 ** rolling back a journal file, the IO error code is returned.
42026 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
42027 int rc = SQLITE_OK; /* Return code */
42029 /* This routine is only called from b-tree and only when there are no
42030 ** outstanding pages. This implies that the pager state should either
42031 ** be OPEN or READER. READER is only possible if the pager is or was in
42032 ** exclusive access mode.
42034 assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
42035 assert( assert_pager_state(pPager) );
42036 assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
42037 if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
42039 if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
42040 int bHotJournal = 1; /* True if there exists a hot journal-file */
42042 assert( !MEMDB );
42043 assert( pPager->noReadlock==0 || pPager->readOnly );
42045 if( pPager->noReadlock==0 ){
42046 rc = pager_wait_on_lock(pPager, SHARED_LOCK);
42047 if( rc!=SQLITE_OK ){
42048 assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
42049 goto failed;
42053 /* If a journal file exists, and there is no RESERVED lock on the
42054 ** database file, then it either needs to be played back or deleted.
42056 if( pPager->eLock<=SHARED_LOCK ){
42057 rc = hasHotJournal(pPager, &bHotJournal);
42059 if( rc!=SQLITE_OK ){
42060 goto failed;
42062 if( bHotJournal ){
42063 /* Get an EXCLUSIVE lock on the database file. At this point it is
42064 ** important that a RESERVED lock is not obtained on the way to the
42065 ** EXCLUSIVE lock. If it were, another process might open the
42066 ** database file, detect the RESERVED lock, and conclude that the
42067 ** database is safe to read while this process is still rolling the
42068 ** hot-journal back.
42070 ** Because the intermediate RESERVED lock is not requested, any
42071 ** other process attempting to access the database file will get to
42072 ** this point in the code and fail to obtain its own EXCLUSIVE lock
42073 ** on the database file.
42075 ** Unless the pager is in locking_mode=exclusive mode, the lock is
42076 ** downgraded to SHARED_LOCK before this function returns.
42078 rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
42079 if( rc!=SQLITE_OK ){
42080 goto failed;
42083 /* If it is not already open and the file exists on disk, open the
42084 ** journal for read/write access. Write access is required because
42085 ** in exclusive-access mode the file descriptor will be kept open
42086 ** and possibly used for a transaction later on. Also, write-access
42087 ** is usually required to finalize the journal in journal_mode=persist
42088 ** mode (and also for journal_mode=truncate on some systems).
42090 ** If the journal does not exist, it usually means that some
42091 ** other connection managed to get in and roll it back before
42092 ** this connection obtained the exclusive lock above. Or, it
42093 ** may mean that the pager was in the error-state when this
42094 ** function was called and the journal file does not exist.
42096 if( !isOpen(pPager->jfd) ){
42097 sqlite3_vfs * const pVfs = pPager->pVfs;
42098 int bExists; /* True if journal file exists */
42099 rc = sqlite3OsAccess(
42100 pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
42101 if( rc==SQLITE_OK && bExists ){
42102 int fout = 0;
42103 int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
42104 assert( !pPager->tempFile );
42105 rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
42106 assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
42107 if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
42108 rc = SQLITE_CANTOPEN_BKPT;
42109 sqlite3OsClose(pPager->jfd);
42114 /* Playback and delete the journal. Drop the database write
42115 ** lock and reacquire the read lock. Purge the cache before
42116 ** playing back the hot-journal so that we don't end up with
42117 ** an inconsistent cache. Sync the hot journal before playing
42118 ** it back since the process that crashed and left the hot journal
42119 ** probably did not sync it and we are required to always sync
42120 ** the journal before playing it back.
42122 if( isOpen(pPager->jfd) ){
42123 assert( rc==SQLITE_OK );
42124 rc = pagerSyncHotJournal(pPager);
42125 if( rc==SQLITE_OK ){
42126 rc = pager_playback(pPager, 1);
42127 pPager->eState = PAGER_OPEN;
42129 }else if( !pPager->exclusiveMode ){
42130 pagerUnlockDb(pPager, SHARED_LOCK);
42133 if( rc!=SQLITE_OK ){
42134 /* This branch is taken if an error occurs while trying to open
42135 ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
42136 ** pager_unlock() routine will be called before returning to unlock
42137 ** the file. If the unlock attempt fails, then Pager.eLock must be
42138 ** set to UNKNOWN_LOCK (see the comment above the #define for
42139 ** UNKNOWN_LOCK above for an explanation).
42141 ** In order to get pager_unlock() to do this, set Pager.eState to
42142 ** PAGER_ERROR now. This is not actually counted as a transition
42143 ** to ERROR state in the state diagram at the top of this file,
42144 ** since we know that the same call to pager_unlock() will very
42145 ** shortly transition the pager object to the OPEN state. Calling
42146 ** assert_pager_state() would fail now, as it should not be possible
42147 ** to be in ERROR state when there are zero outstanding page
42148 ** references.
42150 pager_error(pPager, rc);
42151 goto failed;
42154 assert( pPager->eState==PAGER_OPEN );
42155 assert( (pPager->eLock==SHARED_LOCK)
42156 || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
42160 if( !pPager->tempFile
42161 && (pPager->pBackup || sqlite3PcachePagecount(pPager->pPCache)>0)
42163 /* The shared-lock has just been acquired on the database file
42164 ** and there are already pages in the cache (from a previous
42165 ** read or write transaction). Check to see if the database
42166 ** has been modified. If the database has changed, flush the
42167 ** cache.
42169 ** Database changes is detected by looking at 15 bytes beginning
42170 ** at offset 24 into the file. The first 4 of these 16 bytes are
42171 ** a 32-bit counter that is incremented with each change. The
42172 ** other bytes change randomly with each file change when
42173 ** a codec is in use.
42175 ** There is a vanishingly small chance that a change will not be
42176 ** detected. The chance of an undetected change is so small that
42177 ** it can be neglected.
42179 Pgno nPage = 0;
42180 char dbFileVers[sizeof(pPager->dbFileVers)];
42182 rc = pagerPagecount(pPager, &nPage);
42183 if( rc ) goto failed;
42185 if( nPage>0 ){
42186 IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
42187 rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
42188 if( rc!=SQLITE_OK ){
42189 goto failed;
42191 }else{
42192 memset(dbFileVers, 0, sizeof(dbFileVers));
42195 if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
42196 pager_reset(pPager);
42200 /* If there is a WAL file in the file-system, open this database in WAL
42201 ** mode. Otherwise, the following function call is a no-op.
42203 rc = pagerOpenWalIfPresent(pPager);
42204 #ifndef SQLITE_OMIT_WAL
42205 assert( pPager->pWal==0 || rc==SQLITE_OK );
42206 #endif
42209 if( pagerUseWal(pPager) ){
42210 assert( rc==SQLITE_OK );
42211 rc = pagerBeginReadTransaction(pPager);
42214 if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
42215 rc = pagerPagecount(pPager, &pPager->dbSize);
42218 failed:
42219 if( rc!=SQLITE_OK ){
42220 assert( !MEMDB );
42221 pager_unlock(pPager);
42222 assert( pPager->eState==PAGER_OPEN );
42223 }else{
42224 pPager->eState = PAGER_READER;
42226 return rc;
42230 ** If the reference count has reached zero, rollback any active
42231 ** transaction and unlock the pager.
42233 ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
42234 ** the rollback journal, the unlock is not performed and there is
42235 ** nothing to rollback, so this routine is a no-op.
42237 static void pagerUnlockIfUnused(Pager *pPager){
42238 if( (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
42239 pagerUnlockAndRollback(pPager);
42244 ** Acquire a reference to page number pgno in pager pPager (a page
42245 ** reference has type DbPage*). If the requested reference is
42246 ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
42248 ** If the requested page is already in the cache, it is returned.
42249 ** Otherwise, a new page object is allocated and populated with data
42250 ** read from the database file. In some cases, the pcache module may
42251 ** choose not to allocate a new page object and may reuse an existing
42252 ** object with no outstanding references.
42254 ** The extra data appended to a page is always initialized to zeros the
42255 ** first time a page is loaded into memory. If the page requested is
42256 ** already in the cache when this function is called, then the extra
42257 ** data is left as it was when the page object was last used.
42259 ** If the database image is smaller than the requested page or if a
42260 ** non-zero value is passed as the noContent parameter and the
42261 ** requested page is not already stored in the cache, then no
42262 ** actual disk read occurs. In this case the memory image of the
42263 ** page is initialized to all zeros.
42265 ** If noContent is true, it means that we do not care about the contents
42266 ** of the page. This occurs in two seperate scenarios:
42268 ** a) When reading a free-list leaf page from the database, and
42270 ** b) When a savepoint is being rolled back and we need to load
42271 ** a new page into the cache to be filled with the data read
42272 ** from the savepoint journal.
42274 ** If noContent is true, then the data returned is zeroed instead of
42275 ** being read from the database. Additionally, the bits corresponding
42276 ** to pgno in Pager.pInJournal (bitvec of pages already written to the
42277 ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
42278 ** savepoints are set. This means if the page is made writable at any
42279 ** point in the future, using a call to sqlite3PagerWrite(), its contents
42280 ** will not be journaled. This saves IO.
42282 ** The acquisition might fail for several reasons. In all cases,
42283 ** an appropriate error code is returned and *ppPage is set to NULL.
42285 ** See also sqlite3PagerLookup(). Both this routine and Lookup() attempt
42286 ** to find a page in the in-memory cache first. If the page is not already
42287 ** in memory, this routine goes to disk to read it in whereas Lookup()
42288 ** just returns 0. This routine acquires a read-lock the first time it
42289 ** has to go to disk, and could also playback an old journal if necessary.
42290 ** Since Lookup() never goes to disk, it never has to deal with locks
42291 ** or journal files.
42293 SQLITE_PRIVATE int sqlite3PagerAcquire(
42294 Pager *pPager, /* The pager open on the database file */
42295 Pgno pgno, /* Page number to fetch */
42296 DbPage **ppPage, /* Write a pointer to the page here */
42297 int noContent /* Do not bother reading content from disk if true */
42299 int rc;
42300 PgHdr *pPg;
42302 assert( pPager->eState>=PAGER_READER );
42303 assert( assert_pager_state(pPager) );
42305 if( pgno==0 ){
42306 return SQLITE_CORRUPT_BKPT;
42309 /* If the pager is in the error state, return an error immediately.
42310 ** Otherwise, request the page from the PCache layer. */
42311 if( pPager->errCode!=SQLITE_OK ){
42312 rc = pPager->errCode;
42313 }else{
42314 rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, ppPage);
42317 if( rc!=SQLITE_OK ){
42318 /* Either the call to sqlite3PcacheFetch() returned an error or the
42319 ** pager was already in the error-state when this function was called.
42320 ** Set pPg to 0 and jump to the exception handler. */
42321 pPg = 0;
42322 goto pager_acquire_err;
42324 assert( (*ppPage)->pgno==pgno );
42325 assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
42327 if( (*ppPage)->pPager && !noContent ){
42328 /* In this case the pcache already contains an initialized copy of
42329 ** the page. Return without further ado. */
42330 assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
42331 pPager->nHit++;
42332 return SQLITE_OK;
42334 }else{
42335 /* The pager cache has created a new page. Its content needs to
42336 ** be initialized. */
42338 pPg = *ppPage;
42339 pPg->pPager = pPager;
42341 /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
42342 ** number greater than this, or the unused locking-page, is requested. */
42343 if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
42344 rc = SQLITE_CORRUPT_BKPT;
42345 goto pager_acquire_err;
42348 if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){
42349 if( pgno>pPager->mxPgno ){
42350 rc = SQLITE_FULL;
42351 goto pager_acquire_err;
42353 if( noContent ){
42354 /* Failure to set the bits in the InJournal bit-vectors is benign.
42355 ** It merely means that we might do some extra work to journal a
42356 ** page that does not need to be journaled. Nevertheless, be sure
42357 ** to test the case where a malloc error occurs while trying to set
42358 ** a bit in a bit vector.
42360 sqlite3BeginBenignMalloc();
42361 if( pgno<=pPager->dbOrigSize ){
42362 TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
42363 testcase( rc==SQLITE_NOMEM );
42365 TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
42366 testcase( rc==SQLITE_NOMEM );
42367 sqlite3EndBenignMalloc();
42369 memset(pPg->pData, 0, pPager->pageSize);
42370 IOTRACE(("ZERO %p %d\n", pPager, pgno));
42371 }else{
42372 assert( pPg->pPager==pPager );
42373 pPager->nMiss++;
42374 rc = readDbPage(pPg);
42375 if( rc!=SQLITE_OK ){
42376 goto pager_acquire_err;
42379 pager_set_pagehash(pPg);
42382 return SQLITE_OK;
42384 pager_acquire_err:
42385 assert( rc!=SQLITE_OK );
42386 if( pPg ){
42387 sqlite3PcacheDrop(pPg);
42389 pagerUnlockIfUnused(pPager);
42391 *ppPage = 0;
42392 return rc;
42396 ** Acquire a page if it is already in the in-memory cache. Do
42397 ** not read the page from disk. Return a pointer to the page,
42398 ** or 0 if the page is not in cache.
42400 ** See also sqlite3PagerGet(). The difference between this routine
42401 ** and sqlite3PagerGet() is that _get() will go to the disk and read
42402 ** in the page if the page is not already in cache. This routine
42403 ** returns NULL if the page is not in cache or if a disk I/O error
42404 ** has ever happened.
42406 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
42407 PgHdr *pPg = 0;
42408 assert( pPager!=0 );
42409 assert( pgno!=0 );
42410 assert( pPager->pPCache!=0 );
42411 assert( pPager->eState>=PAGER_READER && pPager->eState!=PAGER_ERROR );
42412 sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
42413 return pPg;
42417 ** Release a page reference.
42419 ** If the number of references to the page drop to zero, then the
42420 ** page is added to the LRU list. When all references to all pages
42421 ** are released, a rollback occurs and the lock on the database is
42422 ** removed.
42424 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
42425 if( pPg ){
42426 Pager *pPager = pPg->pPager;
42427 sqlite3PcacheRelease(pPg);
42428 pagerUnlockIfUnused(pPager);
42433 ** This function is called at the start of every write transaction.
42434 ** There must already be a RESERVED or EXCLUSIVE lock on the database
42435 ** file when this routine is called.
42437 ** Open the journal file for pager pPager and write a journal header
42438 ** to the start of it. If there are active savepoints, open the sub-journal
42439 ** as well. This function is only used when the journal file is being
42440 ** opened to write a rollback log for a transaction. It is not used
42441 ** when opening a hot journal file to roll it back.
42443 ** If the journal file is already open (as it may be in exclusive mode),
42444 ** then this function just writes a journal header to the start of the
42445 ** already open file.
42447 ** Whether or not the journal file is opened by this function, the
42448 ** Pager.pInJournal bitvec structure is allocated.
42450 ** Return SQLITE_OK if everything is successful. Otherwise, return
42451 ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
42452 ** an IO error code if opening or writing the journal file fails.
42454 static int pager_open_journal(Pager *pPager){
42455 int rc = SQLITE_OK; /* Return code */
42456 sqlite3_vfs * const pVfs = pPager->pVfs; /* Local cache of vfs pointer */
42458 assert( pPager->eState==PAGER_WRITER_LOCKED );
42459 assert( assert_pager_state(pPager) );
42460 assert( pPager->pInJournal==0 );
42462 /* If already in the error state, this function is a no-op. But on
42463 ** the other hand, this routine is never called if we are already in
42464 ** an error state. */
42465 if( NEVER(pPager->errCode) ) return pPager->errCode;
42467 if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
42468 pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
42469 if( pPager->pInJournal==0 ){
42470 return SQLITE_NOMEM;
42473 /* Open the journal file if it is not already open. */
42474 if( !isOpen(pPager->jfd) ){
42475 if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
42476 sqlite3MemJournalOpen(pPager->jfd);
42477 }else{
42478 const int flags = /* VFS flags to open journal file */
42479 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
42480 (pPager->tempFile ?
42481 (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
42482 (SQLITE_OPEN_MAIN_JOURNAL)
42484 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
42485 rc = sqlite3JournalOpen(
42486 pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
42488 #else
42489 rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
42490 #endif
42492 assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
42496 /* Write the first journal header to the journal file and open
42497 ** the sub-journal if necessary.
42499 if( rc==SQLITE_OK ){
42500 /* TODO: Check if all of these are really required. */
42501 pPager->nRec = 0;
42502 pPager->journalOff = 0;
42503 pPager->setMaster = 0;
42504 pPager->journalHdr = 0;
42505 rc = writeJournalHdr(pPager);
42509 if( rc!=SQLITE_OK ){
42510 sqlite3BitvecDestroy(pPager->pInJournal);
42511 pPager->pInJournal = 0;
42512 }else{
42513 assert( pPager->eState==PAGER_WRITER_LOCKED );
42514 pPager->eState = PAGER_WRITER_CACHEMOD;
42517 return rc;
42521 ** Begin a write-transaction on the specified pager object. If a
42522 ** write-transaction has already been opened, this function is a no-op.
42524 ** If the exFlag argument is false, then acquire at least a RESERVED
42525 ** lock on the database file. If exFlag is true, then acquire at least
42526 ** an EXCLUSIVE lock. If such a lock is already held, no locking
42527 ** functions need be called.
42529 ** If the subjInMemory argument is non-zero, then any sub-journal opened
42530 ** within this transaction will be opened as an in-memory file. This
42531 ** has no effect if the sub-journal is already opened (as it may be when
42532 ** running in exclusive mode) or if the transaction does not require a
42533 ** sub-journal. If the subjInMemory argument is zero, then any required
42534 ** sub-journal is implemented in-memory if pPager is an in-memory database,
42535 ** or using a temporary file otherwise.
42537 SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
42538 int rc = SQLITE_OK;
42540 if( pPager->errCode ) return pPager->errCode;
42541 assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
42542 pPager->subjInMemory = (u8)subjInMemory;
42544 if( ALWAYS(pPager->eState==PAGER_READER) ){
42545 assert( pPager->pInJournal==0 );
42547 if( pagerUseWal(pPager) ){
42548 /* If the pager is configured to use locking_mode=exclusive, and an
42549 ** exclusive lock on the database is not already held, obtain it now.
42551 if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
42552 rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
42553 if( rc!=SQLITE_OK ){
42554 return rc;
42556 sqlite3WalExclusiveMode(pPager->pWal, 1);
42559 /* Grab the write lock on the log file. If successful, upgrade to
42560 ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
42561 ** The busy-handler is not invoked if another connection already
42562 ** holds the write-lock. If possible, the upper layer will call it.
42564 rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
42565 }else{
42566 /* Obtain a RESERVED lock on the database file. If the exFlag parameter
42567 ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
42568 ** busy-handler callback can be used when upgrading to the EXCLUSIVE
42569 ** lock, but not when obtaining the RESERVED lock.
42571 rc = pagerLockDb(pPager, RESERVED_LOCK);
42572 if( rc==SQLITE_OK && exFlag ){
42573 rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
42577 if( rc==SQLITE_OK ){
42578 /* Change to WRITER_LOCKED state.
42580 ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
42581 ** when it has an open transaction, but never to DBMOD or FINISHED.
42582 ** This is because in those states the code to roll back savepoint
42583 ** transactions may copy data from the sub-journal into the database
42584 ** file as well as into the page cache. Which would be incorrect in
42585 ** WAL mode.
42587 pPager->eState = PAGER_WRITER_LOCKED;
42588 pPager->dbHintSize = pPager->dbSize;
42589 pPager->dbFileSize = pPager->dbSize;
42590 pPager->dbOrigSize = pPager->dbSize;
42591 pPager->journalOff = 0;
42594 assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
42595 assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
42596 assert( assert_pager_state(pPager) );
42599 PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
42600 return rc;
42604 ** Mark a single data page as writeable. The page is written into the
42605 ** main journal or sub-journal as required. If the page is written into
42606 ** one of the journals, the corresponding bit is set in the
42607 ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
42608 ** of any open savepoints as appropriate.
42610 static int pager_write(PgHdr *pPg){
42611 void *pData = pPg->pData;
42612 Pager *pPager = pPg->pPager;
42613 int rc = SQLITE_OK;
42615 /* This routine is not called unless a write-transaction has already
42616 ** been started. The journal file may or may not be open at this point.
42617 ** It is never called in the ERROR state.
42619 assert( pPager->eState==PAGER_WRITER_LOCKED
42620 || pPager->eState==PAGER_WRITER_CACHEMOD
42621 || pPager->eState==PAGER_WRITER_DBMOD
42623 assert( assert_pager_state(pPager) );
42625 /* If an error has been previously detected, report the same error
42626 ** again. This should not happen, but the check provides robustness. */
42627 if( NEVER(pPager->errCode) ) return pPager->errCode;
42629 /* Higher-level routines never call this function if database is not
42630 ** writable. But check anyway, just for robustness. */
42631 if( NEVER(pPager->readOnly) ) return SQLITE_PERM;
42633 CHECK_PAGE(pPg);
42635 /* The journal file needs to be opened. Higher level routines have already
42636 ** obtained the necessary locks to begin the write-transaction, but the
42637 ** rollback journal might not yet be open. Open it now if this is the case.
42639 ** This is done before calling sqlite3PcacheMakeDirty() on the page.
42640 ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
42641 ** an error might occur and the pager would end up in WRITER_LOCKED state
42642 ** with pages marked as dirty in the cache.
42644 if( pPager->eState==PAGER_WRITER_LOCKED ){
42645 rc = pager_open_journal(pPager);
42646 if( rc!=SQLITE_OK ) return rc;
42648 assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
42649 assert( assert_pager_state(pPager) );
42651 /* Mark the page as dirty. If the page has already been written
42652 ** to the journal then we can return right away.
42654 sqlite3PcacheMakeDirty(pPg);
42655 if( pageInJournal(pPg) && !subjRequiresPage(pPg) ){
42656 assert( !pagerUseWal(pPager) );
42657 }else{
42659 /* The transaction journal now exists and we have a RESERVED or an
42660 ** EXCLUSIVE lock on the main database file. Write the current page to
42661 ** the transaction journal if it is not there already.
42663 if( !pageInJournal(pPg) && !pagerUseWal(pPager) ){
42664 assert( pagerUseWal(pPager)==0 );
42665 if( pPg->pgno<=pPager->dbOrigSize && isOpen(pPager->jfd) ){
42666 u32 cksum;
42667 char *pData2;
42668 i64 iOff = pPager->journalOff;
42670 /* We should never write to the journal file the page that
42671 ** contains the database locks. The following assert verifies
42672 ** that we do not. */
42673 assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
42675 assert( pPager->journalHdr<=pPager->journalOff );
42676 CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
42677 cksum = pager_cksum(pPager, (u8*)pData2);
42679 /* Even if an IO or diskfull error occurs while journalling the
42680 ** page in the block above, set the need-sync flag for the page.
42681 ** Otherwise, when the transaction is rolled back, the logic in
42682 ** playback_one_page() will think that the page needs to be restored
42683 ** in the database file. And if an IO error occurs while doing so,
42684 ** then corruption may follow.
42686 pPg->flags |= PGHDR_NEED_SYNC;
42688 rc = write32bits(pPager->jfd, iOff, pPg->pgno);
42689 if( rc!=SQLITE_OK ) return rc;
42690 rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
42691 if( rc!=SQLITE_OK ) return rc;
42692 rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
42693 if( rc!=SQLITE_OK ) return rc;
42695 IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
42696 pPager->journalOff, pPager->pageSize));
42697 PAGER_INCR(sqlite3_pager_writej_count);
42698 PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
42699 PAGERID(pPager), pPg->pgno,
42700 ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
42702 pPager->journalOff += 8 + pPager->pageSize;
42703 pPager->nRec++;
42704 assert( pPager->pInJournal!=0 );
42705 rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
42706 testcase( rc==SQLITE_NOMEM );
42707 assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
42708 rc |= addToSavepointBitvecs(pPager, pPg->pgno);
42709 if( rc!=SQLITE_OK ){
42710 assert( rc==SQLITE_NOMEM );
42711 return rc;
42713 }else{
42714 if( pPager->eState!=PAGER_WRITER_DBMOD ){
42715 pPg->flags |= PGHDR_NEED_SYNC;
42717 PAGERTRACE(("APPEND %d page %d needSync=%d\n",
42718 PAGERID(pPager), pPg->pgno,
42719 ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
42723 /* If the statement journal is open and the page is not in it,
42724 ** then write the current page to the statement journal. Note that
42725 ** the statement journal format differs from the standard journal format
42726 ** in that it omits the checksums and the header.
42728 if( subjRequiresPage(pPg) ){
42729 rc = subjournalPage(pPg);
42733 /* Update the database size and return.
42735 if( pPager->dbSize<pPg->pgno ){
42736 pPager->dbSize = pPg->pgno;
42738 return rc;
42742 ** Mark a data page as writeable. This routine must be called before
42743 ** making changes to a page. The caller must check the return value
42744 ** of this function and be careful not to change any page data unless
42745 ** this routine returns SQLITE_OK.
42747 ** The difference between this function and pager_write() is that this
42748 ** function also deals with the special case where 2 or more pages
42749 ** fit on a single disk sector. In this case all co-resident pages
42750 ** must have been written to the journal file before returning.
42752 ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
42753 ** as appropriate. Otherwise, SQLITE_OK.
42755 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
42756 int rc = SQLITE_OK;
42758 PgHdr *pPg = pDbPage;
42759 Pager *pPager = pPg->pPager;
42760 Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
42762 assert( pPager->eState>=PAGER_WRITER_LOCKED );
42763 assert( pPager->eState!=PAGER_ERROR );
42764 assert( assert_pager_state(pPager) );
42766 if( nPagePerSector>1 ){
42767 Pgno nPageCount; /* Total number of pages in database file */
42768 Pgno pg1; /* First page of the sector pPg is located on. */
42769 int nPage = 0; /* Number of pages starting at pg1 to journal */
42770 int ii; /* Loop counter */
42771 int needSync = 0; /* True if any page has PGHDR_NEED_SYNC */
42773 /* Set the doNotSyncSpill flag to 1. This is because we cannot allow
42774 ** a journal header to be written between the pages journaled by
42775 ** this function.
42777 assert( !MEMDB );
42778 assert( pPager->doNotSyncSpill==0 );
42779 pPager->doNotSyncSpill++;
42781 /* This trick assumes that both the page-size and sector-size are
42782 ** an integer power of 2. It sets variable pg1 to the identifier
42783 ** of the first page of the sector pPg is located on.
42785 pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
42787 nPageCount = pPager->dbSize;
42788 if( pPg->pgno>nPageCount ){
42789 nPage = (pPg->pgno - pg1)+1;
42790 }else if( (pg1+nPagePerSector-1)>nPageCount ){
42791 nPage = nPageCount+1-pg1;
42792 }else{
42793 nPage = nPagePerSector;
42795 assert(nPage>0);
42796 assert(pg1<=pPg->pgno);
42797 assert((pg1+nPage)>pPg->pgno);
42799 for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
42800 Pgno pg = pg1+ii;
42801 PgHdr *pPage;
42802 if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
42803 if( pg!=PAGER_MJ_PGNO(pPager) ){
42804 rc = sqlite3PagerGet(pPager, pg, &pPage);
42805 if( rc==SQLITE_OK ){
42806 rc = pager_write(pPage);
42807 if( pPage->flags&PGHDR_NEED_SYNC ){
42808 needSync = 1;
42810 sqlite3PagerUnref(pPage);
42813 }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
42814 if( pPage->flags&PGHDR_NEED_SYNC ){
42815 needSync = 1;
42817 sqlite3PagerUnref(pPage);
42821 /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
42822 ** starting at pg1, then it needs to be set for all of them. Because
42823 ** writing to any of these nPage pages may damage the others, the
42824 ** journal file must contain sync()ed copies of all of them
42825 ** before any of them can be written out to the database file.
42827 if( rc==SQLITE_OK && needSync ){
42828 assert( !MEMDB );
42829 for(ii=0; ii<nPage; ii++){
42830 PgHdr *pPage = pager_lookup(pPager, pg1+ii);
42831 if( pPage ){
42832 pPage->flags |= PGHDR_NEED_SYNC;
42833 sqlite3PagerUnref(pPage);
42838 assert( pPager->doNotSyncSpill==1 );
42839 pPager->doNotSyncSpill--;
42840 }else{
42841 rc = pager_write(pDbPage);
42843 return rc;
42847 ** Return TRUE if the page given in the argument was previously passed
42848 ** to sqlite3PagerWrite(). In other words, return TRUE if it is ok
42849 ** to change the content of the page.
42851 #ifndef NDEBUG
42852 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
42853 return pPg->flags&PGHDR_DIRTY;
42855 #endif
42858 ** A call to this routine tells the pager that it is not necessary to
42859 ** write the information on page pPg back to the disk, even though
42860 ** that page might be marked as dirty. This happens, for example, when
42861 ** the page has been added as a leaf of the freelist and so its
42862 ** content no longer matters.
42864 ** The overlying software layer calls this routine when all of the data
42865 ** on the given page is unused. The pager marks the page as clean so
42866 ** that it does not get written to disk.
42868 ** Tests show that this optimization can quadruple the speed of large
42869 ** DELETE operations.
42871 SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
42872 Pager *pPager = pPg->pPager;
42873 if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
42874 PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
42875 IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
42876 pPg->flags |= PGHDR_DONT_WRITE;
42877 pager_set_pagehash(pPg);
42882 ** This routine is called to increment the value of the database file
42883 ** change-counter, stored as a 4-byte big-endian integer starting at
42884 ** byte offset 24 of the pager file. The secondary change counter at
42885 ** 92 is also updated, as is the SQLite version number at offset 96.
42887 ** But this only happens if the pPager->changeCountDone flag is false.
42888 ** To avoid excess churning of page 1, the update only happens once.
42889 ** See also the pager_write_changecounter() routine that does an
42890 ** unconditional update of the change counters.
42892 ** If the isDirectMode flag is zero, then this is done by calling
42893 ** sqlite3PagerWrite() on page 1, then modifying the contents of the
42894 ** page data. In this case the file will be updated when the current
42895 ** transaction is committed.
42897 ** The isDirectMode flag may only be non-zero if the library was compiled
42898 ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
42899 ** if isDirect is non-zero, then the database file is updated directly
42900 ** by writing an updated version of page 1 using a call to the
42901 ** sqlite3OsWrite() function.
42903 static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
42904 int rc = SQLITE_OK;
42906 assert( pPager->eState==PAGER_WRITER_CACHEMOD
42907 || pPager->eState==PAGER_WRITER_DBMOD
42909 assert( assert_pager_state(pPager) );
42911 /* Declare and initialize constant integer 'isDirect'. If the
42912 ** atomic-write optimization is enabled in this build, then isDirect
42913 ** is initialized to the value passed as the isDirectMode parameter
42914 ** to this function. Otherwise, it is always set to zero.
42916 ** The idea is that if the atomic-write optimization is not
42917 ** enabled at compile time, the compiler can omit the tests of
42918 ** 'isDirect' below, as well as the block enclosed in the
42919 ** "if( isDirect )" condition.
42921 #ifndef SQLITE_ENABLE_ATOMIC_WRITE
42922 # define DIRECT_MODE 0
42923 assert( isDirectMode==0 );
42924 UNUSED_PARAMETER(isDirectMode);
42925 #else
42926 # define DIRECT_MODE isDirectMode
42927 #endif
42929 if( !pPager->changeCountDone && pPager->dbSize>0 ){
42930 PgHdr *pPgHdr; /* Reference to page 1 */
42932 assert( !pPager->tempFile && isOpen(pPager->fd) );
42934 /* Open page 1 of the file for writing. */
42935 rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
42936 assert( pPgHdr==0 || rc==SQLITE_OK );
42938 /* If page one was fetched successfully, and this function is not
42939 ** operating in direct-mode, make page 1 writable. When not in
42940 ** direct mode, page 1 is always held in cache and hence the PagerGet()
42941 ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
42943 if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
42944 rc = sqlite3PagerWrite(pPgHdr);
42947 if( rc==SQLITE_OK ){
42948 /* Actually do the update of the change counter */
42949 pager_write_changecounter(pPgHdr);
42951 /* If running in direct mode, write the contents of page 1 to the file. */
42952 if( DIRECT_MODE ){
42953 const void *zBuf;
42954 assert( pPager->dbFileSize>0 );
42955 CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf);
42956 if( rc==SQLITE_OK ){
42957 rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
42959 if( rc==SQLITE_OK ){
42960 pPager->changeCountDone = 1;
42962 }else{
42963 pPager->changeCountDone = 1;
42967 /* Release the page reference. */
42968 sqlite3PagerUnref(pPgHdr);
42970 return rc;
42974 ** Sync the database file to disk. This is a no-op for in-memory databases
42975 ** or pages with the Pager.noSync flag set.
42977 ** If successful, or if called on a pager for which it is a no-op, this
42978 ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
42980 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager){
42981 int rc = SQLITE_OK;
42982 if( !pPager->noSync ){
42983 assert( !MEMDB );
42984 rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
42985 }else if( isOpen(pPager->fd) ){
42986 assert( !MEMDB );
42987 sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC_OMITTED, (void *)&rc);
42989 return rc;
42993 ** This function may only be called while a write-transaction is active in
42994 ** rollback. If the connection is in WAL mode, this call is a no-op.
42995 ** Otherwise, if the connection does not already have an EXCLUSIVE lock on
42996 ** the database file, an attempt is made to obtain one.
42998 ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
42999 ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
43000 ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
43001 ** returned.
43003 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
43004 int rc = SQLITE_OK;
43005 assert( pPager->eState==PAGER_WRITER_CACHEMOD
43006 || pPager->eState==PAGER_WRITER_DBMOD
43007 || pPager->eState==PAGER_WRITER_LOCKED
43009 assert( assert_pager_state(pPager) );
43010 if( 0==pagerUseWal(pPager) ){
43011 rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
43013 return rc;
43017 ** Sync the database file for the pager pPager. zMaster points to the name
43018 ** of a master journal file that should be written into the individual
43019 ** journal file. zMaster may be NULL, which is interpreted as no master
43020 ** journal (a single database transaction).
43022 ** This routine ensures that:
43024 ** * The database file change-counter is updated,
43025 ** * the journal is synced (unless the atomic-write optimization is used),
43026 ** * all dirty pages are written to the database file,
43027 ** * the database file is truncated (if required), and
43028 ** * the database file synced.
43030 ** The only thing that remains to commit the transaction is to finalize
43031 ** (delete, truncate or zero the first part of) the journal file (or
43032 ** delete the master journal file if specified).
43034 ** Note that if zMaster==NULL, this does not overwrite a previous value
43035 ** passed to an sqlite3PagerCommitPhaseOne() call.
43037 ** If the final parameter - noSync - is true, then the database file itself
43038 ** is not synced. The caller must call sqlite3PagerSync() directly to
43039 ** sync the database file before calling CommitPhaseTwo() to delete the
43040 ** journal file in this case.
43042 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
43043 Pager *pPager, /* Pager object */
43044 const char *zMaster, /* If not NULL, the master journal name */
43045 int noSync /* True to omit the xSync on the db file */
43047 int rc = SQLITE_OK; /* Return code */
43049 assert( pPager->eState==PAGER_WRITER_LOCKED
43050 || pPager->eState==PAGER_WRITER_CACHEMOD
43051 || pPager->eState==PAGER_WRITER_DBMOD
43052 || pPager->eState==PAGER_ERROR
43054 assert( assert_pager_state(pPager) );
43056 /* If a prior error occurred, report that error again. */
43057 if( NEVER(pPager->errCode) ) return pPager->errCode;
43059 PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
43060 pPager->zFilename, zMaster, pPager->dbSize));
43062 /* If no database changes have been made, return early. */
43063 if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
43065 if( MEMDB ){
43066 /* If this is an in-memory db, or no pages have been written to, or this
43067 ** function has already been called, it is mostly a no-op. However, any
43068 ** backup in progress needs to be restarted.
43070 sqlite3BackupRestart(pPager->pBackup);
43071 }else{
43072 if( pagerUseWal(pPager) ){
43073 PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
43074 PgHdr *pPageOne = 0;
43075 if( pList==0 ){
43076 /* Must have at least one page for the WAL commit flag.
43077 ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
43078 rc = sqlite3PagerGet(pPager, 1, &pPageOne);
43079 pList = pPageOne;
43080 pList->pDirty = 0;
43082 assert( rc==SQLITE_OK );
43083 if( ALWAYS(pList) ){
43084 rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1,
43085 (pPager->fullSync ? pPager->syncFlags : 0)
43088 sqlite3PagerUnref(pPageOne);
43089 if( rc==SQLITE_OK ){
43090 sqlite3PcacheCleanAll(pPager->pPCache);
43092 }else{
43093 /* The following block updates the change-counter. Exactly how it
43094 ** does this depends on whether or not the atomic-update optimization
43095 ** was enabled at compile time, and if this transaction meets the
43096 ** runtime criteria to use the operation:
43098 ** * The file-system supports the atomic-write property for
43099 ** blocks of size page-size, and
43100 ** * This commit is not part of a multi-file transaction, and
43101 ** * Exactly one page has been modified and store in the journal file.
43103 ** If the optimization was not enabled at compile time, then the
43104 ** pager_incr_changecounter() function is called to update the change
43105 ** counter in 'indirect-mode'. If the optimization is compiled in but
43106 ** is not applicable to this transaction, call sqlite3JournalCreate()
43107 ** to make sure the journal file has actually been created, then call
43108 ** pager_incr_changecounter() to update the change-counter in indirect
43109 ** mode.
43111 ** Otherwise, if the optimization is both enabled and applicable,
43112 ** then call pager_incr_changecounter() to update the change-counter
43113 ** in 'direct' mode. In this case the journal file will never be
43114 ** created for this transaction.
43116 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
43117 PgHdr *pPg;
43118 assert( isOpen(pPager->jfd)
43119 || pPager->journalMode==PAGER_JOURNALMODE_OFF
43120 || pPager->journalMode==PAGER_JOURNALMODE_WAL
43122 if( !zMaster && isOpen(pPager->jfd)
43123 && pPager->journalOff==jrnlBufferSize(pPager)
43124 && pPager->dbSize>=pPager->dbOrigSize
43125 && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
43127 /* Update the db file change counter via the direct-write method. The
43128 ** following call will modify the in-memory representation of page 1
43129 ** to include the updated change counter and then write page 1
43130 ** directly to the database file. Because of the atomic-write
43131 ** property of the host file-system, this is safe.
43133 rc = pager_incr_changecounter(pPager, 1);
43134 }else{
43135 rc = sqlite3JournalCreate(pPager->jfd);
43136 if( rc==SQLITE_OK ){
43137 rc = pager_incr_changecounter(pPager, 0);
43140 #else
43141 rc = pager_incr_changecounter(pPager, 0);
43142 #endif
43143 if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
43145 /* If this transaction has made the database smaller, then all pages
43146 ** being discarded by the truncation must be written to the journal
43147 ** file. This can only happen in auto-vacuum mode.
43149 ** Before reading the pages with page numbers larger than the
43150 ** current value of Pager.dbSize, set dbSize back to the value
43151 ** that it took at the start of the transaction. Otherwise, the
43152 ** calls to sqlite3PagerGet() return zeroed pages instead of
43153 ** reading data from the database file.
43155 #ifndef SQLITE_OMIT_AUTOVACUUM
43156 if( pPager->dbSize<pPager->dbOrigSize
43157 && pPager->journalMode!=PAGER_JOURNALMODE_OFF
43159 Pgno i; /* Iterator variable */
43160 const Pgno iSkip = PAGER_MJ_PGNO(pPager); /* Pending lock page */
43161 const Pgno dbSize = pPager->dbSize; /* Database image size */
43162 pPager->dbSize = pPager->dbOrigSize;
43163 for( i=dbSize+1; i<=pPager->dbOrigSize; i++ ){
43164 if( !sqlite3BitvecTest(pPager->pInJournal, i) && i!=iSkip ){
43165 PgHdr *pPage; /* Page to journal */
43166 rc = sqlite3PagerGet(pPager, i, &pPage);
43167 if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
43168 rc = sqlite3PagerWrite(pPage);
43169 sqlite3PagerUnref(pPage);
43170 if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
43173 pPager->dbSize = dbSize;
43175 #endif
43177 /* Write the master journal name into the journal file. If a master
43178 ** journal file name has already been written to the journal file,
43179 ** or if zMaster is NULL (no master journal), then this call is a no-op.
43181 rc = writeMasterJournal(pPager, zMaster);
43182 if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
43184 /* Sync the journal file and write all dirty pages to the database.
43185 ** If the atomic-update optimization is being used, this sync will not
43186 ** create the journal file or perform any real IO.
43188 ** Because the change-counter page was just modified, unless the
43189 ** atomic-update optimization is used it is almost certain that the
43190 ** journal requires a sync here. However, in locking_mode=exclusive
43191 ** on a system under memory pressure it is just possible that this is
43192 ** not the case. In this case it is likely enough that the redundant
43193 ** xSync() call will be changed to a no-op by the OS anyhow.
43195 rc = syncJournal(pPager, 0);
43196 if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
43198 rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
43199 if( rc!=SQLITE_OK ){
43200 assert( rc!=SQLITE_IOERR_BLOCKED );
43201 goto commit_phase_one_exit;
43203 sqlite3PcacheCleanAll(pPager->pPCache);
43205 /* If the file on disk is not the same size as the database image,
43206 ** then use pager_truncate to grow or shrink the file here.
43208 if( pPager->dbSize!=pPager->dbFileSize ){
43209 Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
43210 assert( pPager->eState==PAGER_WRITER_DBMOD );
43211 rc = pager_truncate(pPager, nNew);
43212 if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
43215 /* Finally, sync the database file. */
43216 if( !noSync ){
43217 rc = sqlite3PagerSync(pPager);
43219 IOTRACE(("DBSYNC %p\n", pPager))
43223 commit_phase_one_exit:
43224 if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
43225 pPager->eState = PAGER_WRITER_FINISHED;
43227 return rc;
43232 ** When this function is called, the database file has been completely
43233 ** updated to reflect the changes made by the current transaction and
43234 ** synced to disk. The journal file still exists in the file-system
43235 ** though, and if a failure occurs at this point it will eventually
43236 ** be used as a hot-journal and the current transaction rolled back.
43238 ** This function finalizes the journal file, either by deleting,
43239 ** truncating or partially zeroing it, so that it cannot be used
43240 ** for hot-journal rollback. Once this is done the transaction is
43241 ** irrevocably committed.
43243 ** If an error occurs, an IO error code is returned and the pager
43244 ** moves into the error state. Otherwise, SQLITE_OK is returned.
43246 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
43247 int rc = SQLITE_OK; /* Return code */
43249 /* This routine should not be called if a prior error has occurred.
43250 ** But if (due to a coding error elsewhere in the system) it does get
43251 ** called, just return the same error code without doing anything. */
43252 if( NEVER(pPager->errCode) ) return pPager->errCode;
43254 assert( pPager->eState==PAGER_WRITER_LOCKED
43255 || pPager->eState==PAGER_WRITER_FINISHED
43256 || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
43258 assert( assert_pager_state(pPager) );
43260 /* An optimization. If the database was not actually modified during
43261 ** this transaction, the pager is running in exclusive-mode and is
43262 ** using persistent journals, then this function is a no-op.
43264 ** The start of the journal file currently contains a single journal
43265 ** header with the nRec field set to 0. If such a journal is used as
43266 ** a hot-journal during hot-journal rollback, 0 changes will be made
43267 ** to the database file. So there is no need to zero the journal
43268 ** header. Since the pager is in exclusive mode, there is no need
43269 ** to drop any locks either.
43271 if( pPager->eState==PAGER_WRITER_LOCKED
43272 && pPager->exclusiveMode
43273 && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
43275 assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
43276 pPager->eState = PAGER_READER;
43277 return SQLITE_OK;
43280 PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
43281 rc = pager_end_transaction(pPager, pPager->setMaster);
43282 return pager_error(pPager, rc);
43286 ** If a write transaction is open, then all changes made within the
43287 ** transaction are reverted and the current write-transaction is closed.
43288 ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
43289 ** state if an error occurs.
43291 ** If the pager is already in PAGER_ERROR state when this function is called,
43292 ** it returns Pager.errCode immediately. No work is performed in this case.
43294 ** Otherwise, in rollback mode, this function performs two functions:
43296 ** 1) It rolls back the journal file, restoring all database file and
43297 ** in-memory cache pages to the state they were in when the transaction
43298 ** was opened, and
43300 ** 2) It finalizes the journal file, so that it is not used for hot
43301 ** rollback at any point in the future.
43303 ** Finalization of the journal file (task 2) is only performed if the
43304 ** rollback is successful.
43306 ** In WAL mode, all cache-entries containing data modified within the
43307 ** current transaction are either expelled from the cache or reverted to
43308 ** their pre-transaction state by re-reading data from the database or
43309 ** WAL files. The WAL transaction is then closed.
43311 SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
43312 int rc = SQLITE_OK; /* Return code */
43313 PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
43315 /* PagerRollback() is a no-op if called in READER or OPEN state. If
43316 ** the pager is already in the ERROR state, the rollback is not
43317 ** attempted here. Instead, the error code is returned to the caller.
43319 assert( assert_pager_state(pPager) );
43320 if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
43321 if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
43323 if( pagerUseWal(pPager) ){
43324 int rc2;
43325 rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
43326 rc2 = pager_end_transaction(pPager, pPager->setMaster);
43327 if( rc==SQLITE_OK ) rc = rc2;
43328 }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
43329 int eState = pPager->eState;
43330 rc = pager_end_transaction(pPager, 0);
43331 if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
43332 /* This can happen using journal_mode=off. Move the pager to the error
43333 ** state to indicate that the contents of the cache may not be trusted.
43334 ** Any active readers will get SQLITE_ABORT.
43336 pPager->errCode = SQLITE_ABORT;
43337 pPager->eState = PAGER_ERROR;
43338 return rc;
43340 }else{
43341 rc = pager_playback(pPager, 0);
43344 assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
43345 assert( rc==SQLITE_OK || rc==SQLITE_FULL || (rc&0xFF)==SQLITE_IOERR );
43347 /* If an error occurs during a ROLLBACK, we can no longer trust the pager
43348 ** cache. So call pager_error() on the way out to make any error persistent.
43350 return pager_error(pPager, rc);
43354 ** Return TRUE if the database file is opened read-only. Return FALSE
43355 ** if the database is (in theory) writable.
43357 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
43358 return pPager->readOnly;
43362 ** Return the number of references to the pager.
43364 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
43365 return sqlite3PcacheRefCount(pPager->pPCache);
43369 ** Return the approximate number of bytes of memory currently
43370 ** used by the pager and its associated cache.
43372 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
43373 int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
43374 + 5*sizeof(void*);
43375 return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
43376 + sqlite3MallocSize(pPager)
43377 + pPager->pageSize;
43381 ** Return the number of references to the specified page.
43383 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
43384 return sqlite3PcachePageRefcount(pPage);
43387 #ifdef SQLITE_TEST
43389 ** This routine is used for testing and analysis only.
43391 SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
43392 static int a[11];
43393 a[0] = sqlite3PcacheRefCount(pPager->pPCache);
43394 a[1] = sqlite3PcachePagecount(pPager->pPCache);
43395 a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
43396 a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
43397 a[4] = pPager->eState;
43398 a[5] = pPager->errCode;
43399 a[6] = pPager->nHit;
43400 a[7] = pPager->nMiss;
43401 a[8] = 0; /* Used to be pPager->nOvfl */
43402 a[9] = pPager->nRead;
43403 a[10] = pPager->nWrite;
43404 return a;
43406 #endif
43409 ** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or
43410 ** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the
43411 ** current cache hit or miss count, according to the value of eStat. If the
43412 ** reset parameter is non-zero, the cache hit or miss count is zeroed before
43413 ** returning.
43415 SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
43416 int *piStat;
43418 assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
43419 || eStat==SQLITE_DBSTATUS_CACHE_MISS
43421 if( eStat==SQLITE_DBSTATUS_CACHE_HIT ){
43422 piStat = &pPager->nHit;
43423 }else{
43424 piStat = &pPager->nMiss;
43427 *pnVal += *piStat;
43428 if( reset ){
43429 *piStat = 0;
43434 ** Return true if this is an in-memory pager.
43436 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
43437 return MEMDB;
43441 ** Check that there are at least nSavepoint savepoints open. If there are
43442 ** currently less than nSavepoints open, then open one or more savepoints
43443 ** to make up the difference. If the number of savepoints is already
43444 ** equal to nSavepoint, then this function is a no-op.
43446 ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
43447 ** occurs while opening the sub-journal file, then an IO error code is
43448 ** returned. Otherwise, SQLITE_OK.
43450 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
43451 int rc = SQLITE_OK; /* Return code */
43452 int nCurrent = pPager->nSavepoint; /* Current number of savepoints */
43454 assert( pPager->eState>=PAGER_WRITER_LOCKED );
43455 assert( assert_pager_state(pPager) );
43457 if( nSavepoint>nCurrent && pPager->useJournal ){
43458 int ii; /* Iterator variable */
43459 PagerSavepoint *aNew; /* New Pager.aSavepoint array */
43461 /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
43462 ** if the allocation fails. Otherwise, zero the new portion in case a
43463 ** malloc failure occurs while populating it in the for(...) loop below.
43465 aNew = (PagerSavepoint *)sqlite3Realloc(
43466 pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
43468 if( !aNew ){
43469 return SQLITE_NOMEM;
43471 memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
43472 pPager->aSavepoint = aNew;
43474 /* Populate the PagerSavepoint structures just allocated. */
43475 for(ii=nCurrent; ii<nSavepoint; ii++){
43476 aNew[ii].nOrig = pPager->dbSize;
43477 if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
43478 aNew[ii].iOffset = pPager->journalOff;
43479 }else{
43480 aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
43482 aNew[ii].iSubRec = pPager->nSubRec;
43483 aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
43484 if( !aNew[ii].pInSavepoint ){
43485 return SQLITE_NOMEM;
43487 if( pagerUseWal(pPager) ){
43488 sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
43490 pPager->nSavepoint = ii+1;
43492 assert( pPager->nSavepoint==nSavepoint );
43493 assertTruncateConstraint(pPager);
43496 return rc;
43500 ** This function is called to rollback or release (commit) a savepoint.
43501 ** The savepoint to release or rollback need not be the most recently
43502 ** created savepoint.
43504 ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
43505 ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
43506 ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
43507 ** that have occurred since the specified savepoint was created.
43509 ** The savepoint to rollback or release is identified by parameter
43510 ** iSavepoint. A value of 0 means to operate on the outermost savepoint
43511 ** (the first created). A value of (Pager.nSavepoint-1) means operate
43512 ** on the most recently created savepoint. If iSavepoint is greater than
43513 ** (Pager.nSavepoint-1), then this function is a no-op.
43515 ** If a negative value is passed to this function, then the current
43516 ** transaction is rolled back. This is different to calling
43517 ** sqlite3PagerRollback() because this function does not terminate
43518 ** the transaction or unlock the database, it just restores the
43519 ** contents of the database to its original state.
43521 ** In any case, all savepoints with an index greater than iSavepoint
43522 ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
43523 ** then savepoint iSavepoint is also destroyed.
43525 ** This function may return SQLITE_NOMEM if a memory allocation fails,
43526 ** or an IO error code if an IO error occurs while rolling back a
43527 ** savepoint. If no errors occur, SQLITE_OK is returned.
43529 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
43530 int rc = pPager->errCode; /* Return code */
43532 assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
43533 assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
43535 if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
43536 int ii; /* Iterator variable */
43537 int nNew; /* Number of remaining savepoints after this op. */
43539 /* Figure out how many savepoints will still be active after this
43540 ** operation. Store this value in nNew. Then free resources associated
43541 ** with any savepoints that are destroyed by this operation.
43543 nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
43544 for(ii=nNew; ii<pPager->nSavepoint; ii++){
43545 sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
43547 pPager->nSavepoint = nNew;
43549 /* If this is a release of the outermost savepoint, truncate
43550 ** the sub-journal to zero bytes in size. */
43551 if( op==SAVEPOINT_RELEASE ){
43552 if( nNew==0 && isOpen(pPager->sjfd) ){
43553 /* Only truncate if it is an in-memory sub-journal. */
43554 if( sqlite3IsMemJournal(pPager->sjfd) ){
43555 rc = sqlite3OsTruncate(pPager->sjfd, 0);
43556 assert( rc==SQLITE_OK );
43558 pPager->nSubRec = 0;
43561 /* Else this is a rollback operation, playback the specified savepoint.
43562 ** If this is a temp-file, it is possible that the journal file has
43563 ** not yet been opened. In this case there have been no changes to
43564 ** the database file, so the playback operation can be skipped.
43566 else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
43567 PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
43568 rc = pagerPlaybackSavepoint(pPager, pSavepoint);
43569 assert(rc!=SQLITE_DONE);
43573 return rc;
43577 ** Return the full pathname of the database file.
43579 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager){
43580 return pPager->zFilename;
43584 ** Return the VFS structure for the pager.
43586 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
43587 return pPager->pVfs;
43591 ** Return the file handle for the database file associated
43592 ** with the pager. This might return NULL if the file has
43593 ** not yet been opened.
43595 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
43596 return pPager->fd;
43600 ** Return the full pathname of the journal file.
43602 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
43603 return pPager->zJournal;
43607 ** Return true if fsync() calls are disabled for this pager. Return FALSE
43608 ** if fsync()s are executed normally.
43610 SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
43611 return pPager->noSync;
43614 #ifdef SQLITE_HAS_CODEC
43616 ** Set or retrieve the codec for this pager
43618 SQLITE_PRIVATE void sqlite3PagerSetCodec(
43619 Pager *pPager,
43620 void *(*xCodec)(void*,void*,Pgno,int),
43621 void (*xCodecSizeChng)(void*,int,int),
43622 void (*xCodecFree)(void*),
43623 void *pCodec
43625 if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
43626 pPager->xCodec = pPager->memDb ? 0 : xCodec;
43627 pPager->xCodecSizeChng = xCodecSizeChng;
43628 pPager->xCodecFree = xCodecFree;
43629 pPager->pCodec = pCodec;
43630 pagerReportSize(pPager);
43632 SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
43633 return pPager->pCodec;
43635 #endif
43637 #ifndef SQLITE_OMIT_AUTOVACUUM
43639 ** Move the page pPg to location pgno in the file.
43641 ** There must be no references to the page previously located at
43642 ** pgno (which we call pPgOld) though that page is allowed to be
43643 ** in cache. If the page previously located at pgno is not already
43644 ** in the rollback journal, it is not put there by by this routine.
43646 ** References to the page pPg remain valid. Updating any
43647 ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
43648 ** allocated along with the page) is the responsibility of the caller.
43650 ** A transaction must be active when this routine is called. It used to be
43651 ** required that a statement transaction was not active, but this restriction
43652 ** has been removed (CREATE INDEX needs to move a page when a statement
43653 ** transaction is active).
43655 ** If the fourth argument, isCommit, is non-zero, then this page is being
43656 ** moved as part of a database reorganization just before the transaction
43657 ** is being committed. In this case, it is guaranteed that the database page
43658 ** pPg refers to will not be written to again within this transaction.
43660 ** This function may return SQLITE_NOMEM or an IO error code if an error
43661 ** occurs. Otherwise, it returns SQLITE_OK.
43663 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
43664 PgHdr *pPgOld; /* The page being overwritten. */
43665 Pgno needSyncPgno = 0; /* Old value of pPg->pgno, if sync is required */
43666 int rc; /* Return code */
43667 Pgno origPgno; /* The original page number */
43669 assert( pPg->nRef>0 );
43670 assert( pPager->eState==PAGER_WRITER_CACHEMOD
43671 || pPager->eState==PAGER_WRITER_DBMOD
43673 assert( assert_pager_state(pPager) );
43675 /* In order to be able to rollback, an in-memory database must journal
43676 ** the page we are moving from.
43678 if( MEMDB ){
43679 rc = sqlite3PagerWrite(pPg);
43680 if( rc ) return rc;
43683 /* If the page being moved is dirty and has not been saved by the latest
43684 ** savepoint, then save the current contents of the page into the
43685 ** sub-journal now. This is required to handle the following scenario:
43687 ** BEGIN;
43688 ** <journal page X, then modify it in memory>
43689 ** SAVEPOINT one;
43690 ** <Move page X to location Y>
43691 ** ROLLBACK TO one;
43693 ** If page X were not written to the sub-journal here, it would not
43694 ** be possible to restore its contents when the "ROLLBACK TO one"
43695 ** statement were is processed.
43697 ** subjournalPage() may need to allocate space to store pPg->pgno into
43698 ** one or more savepoint bitvecs. This is the reason this function
43699 ** may return SQLITE_NOMEM.
43701 if( pPg->flags&PGHDR_DIRTY
43702 && subjRequiresPage(pPg)
43703 && SQLITE_OK!=(rc = subjournalPage(pPg))
43705 return rc;
43708 PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
43709 PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
43710 IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
43712 /* If the journal needs to be sync()ed before page pPg->pgno can
43713 ** be written to, store pPg->pgno in local variable needSyncPgno.
43715 ** If the isCommit flag is set, there is no need to remember that
43716 ** the journal needs to be sync()ed before database page pPg->pgno
43717 ** can be written to. The caller has already promised not to write to it.
43719 if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
43720 needSyncPgno = pPg->pgno;
43721 assert( pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
43722 assert( pPg->flags&PGHDR_DIRTY );
43725 /* If the cache contains a page with page-number pgno, remove it
43726 ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
43727 ** page pgno before the 'move' operation, it needs to be retained
43728 ** for the page moved there.
43730 pPg->flags &= ~PGHDR_NEED_SYNC;
43731 pPgOld = pager_lookup(pPager, pgno);
43732 assert( !pPgOld || pPgOld->nRef==1 );
43733 if( pPgOld ){
43734 pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
43735 if( MEMDB ){
43736 /* Do not discard pages from an in-memory database since we might
43737 ** need to rollback later. Just move the page out of the way. */
43738 sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
43739 }else{
43740 sqlite3PcacheDrop(pPgOld);
43744 origPgno = pPg->pgno;
43745 sqlite3PcacheMove(pPg, pgno);
43746 sqlite3PcacheMakeDirty(pPg);
43748 /* For an in-memory database, make sure the original page continues
43749 ** to exist, in case the transaction needs to roll back. Use pPgOld
43750 ** as the original page since it has already been allocated.
43752 if( MEMDB ){
43753 assert( pPgOld );
43754 sqlite3PcacheMove(pPgOld, origPgno);
43755 sqlite3PagerUnref(pPgOld);
43758 if( needSyncPgno ){
43759 /* If needSyncPgno is non-zero, then the journal file needs to be
43760 ** sync()ed before any data is written to database file page needSyncPgno.
43761 ** Currently, no such page exists in the page-cache and the
43762 ** "is journaled" bitvec flag has been set. This needs to be remedied by
43763 ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
43764 ** flag.
43766 ** If the attempt to load the page into the page-cache fails, (due
43767 ** to a malloc() or IO failure), clear the bit in the pInJournal[]
43768 ** array. Otherwise, if the page is loaded and written again in
43769 ** this transaction, it may be written to the database file before
43770 ** it is synced into the journal file. This way, it may end up in
43771 ** the journal file twice, but that is not a problem.
43773 PgHdr *pPgHdr;
43774 rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
43775 if( rc!=SQLITE_OK ){
43776 if( needSyncPgno<=pPager->dbOrigSize ){
43777 assert( pPager->pTmpSpace!=0 );
43778 sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
43780 return rc;
43782 pPgHdr->flags |= PGHDR_NEED_SYNC;
43783 sqlite3PcacheMakeDirty(pPgHdr);
43784 sqlite3PagerUnref(pPgHdr);
43787 return SQLITE_OK;
43789 #endif
43792 ** Return a pointer to the data for the specified page.
43794 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
43795 assert( pPg->nRef>0 || pPg->pPager->memDb );
43796 return pPg->pData;
43800 ** Return a pointer to the Pager.nExtra bytes of "extra" space
43801 ** allocated along with the specified page.
43803 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
43804 return pPg->pExtra;
43808 ** Get/set the locking-mode for this pager. Parameter eMode must be one
43809 ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
43810 ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
43811 ** the locking-mode is set to the value specified.
43813 ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
43814 ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
43815 ** locking-mode.
43817 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
43818 assert( eMode==PAGER_LOCKINGMODE_QUERY
43819 || eMode==PAGER_LOCKINGMODE_NORMAL
43820 || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
43821 assert( PAGER_LOCKINGMODE_QUERY<0 );
43822 assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
43823 assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
43824 if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
43825 pPager->exclusiveMode = (u8)eMode;
43827 return (int)pPager->exclusiveMode;
43831 ** Set the journal-mode for this pager. Parameter eMode must be one of:
43833 ** PAGER_JOURNALMODE_DELETE
43834 ** PAGER_JOURNALMODE_TRUNCATE
43835 ** PAGER_JOURNALMODE_PERSIST
43836 ** PAGER_JOURNALMODE_OFF
43837 ** PAGER_JOURNALMODE_MEMORY
43838 ** PAGER_JOURNALMODE_WAL
43840 ** The journalmode is set to the value specified if the change is allowed.
43841 ** The change may be disallowed for the following reasons:
43843 ** * An in-memory database can only have its journal_mode set to _OFF
43844 ** or _MEMORY.
43846 ** * Temporary databases cannot have _WAL journalmode.
43848 ** The returned indicate the current (possibly updated) journal-mode.
43850 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
43851 u8 eOld = pPager->journalMode; /* Prior journalmode */
43853 #ifdef SQLITE_DEBUG
43854 /* The print_pager_state() routine is intended to be used by the debugger
43855 ** only. We invoke it once here to suppress a compiler warning. */
43856 print_pager_state(pPager);
43857 #endif
43860 /* The eMode parameter is always valid */
43861 assert( eMode==PAGER_JOURNALMODE_DELETE
43862 || eMode==PAGER_JOURNALMODE_TRUNCATE
43863 || eMode==PAGER_JOURNALMODE_PERSIST
43864 || eMode==PAGER_JOURNALMODE_OFF
43865 || eMode==PAGER_JOURNALMODE_WAL
43866 || eMode==PAGER_JOURNALMODE_MEMORY );
43868 /* This routine is only called from the OP_JournalMode opcode, and
43869 ** the logic there will never allow a temporary file to be changed
43870 ** to WAL mode.
43872 assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
43874 /* Do allow the journalmode of an in-memory database to be set to
43875 ** anything other than MEMORY or OFF
43877 if( MEMDB ){
43878 assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
43879 if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
43880 eMode = eOld;
43884 if( eMode!=eOld ){
43886 /* Change the journal mode. */
43887 assert( pPager->eState!=PAGER_ERROR );
43888 pPager->journalMode = (u8)eMode;
43890 /* When transistioning from TRUNCATE or PERSIST to any other journal
43891 ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
43892 ** delete the journal file.
43894 assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
43895 assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
43896 assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
43897 assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
43898 assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
43899 assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
43901 assert( isOpen(pPager->fd) || pPager->exclusiveMode );
43902 if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
43904 /* In this case we would like to delete the journal file. If it is
43905 ** not possible, then that is not a problem. Deleting the journal file
43906 ** here is an optimization only.
43908 ** Before deleting the journal file, obtain a RESERVED lock on the
43909 ** database file. This ensures that the journal file is not deleted
43910 ** while it is in use by some other client.
43912 sqlite3OsClose(pPager->jfd);
43913 if( pPager->eLock>=RESERVED_LOCK ){
43914 sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
43915 }else{
43916 int rc = SQLITE_OK;
43917 int state = pPager->eState;
43918 assert( state==PAGER_OPEN || state==PAGER_READER );
43919 if( state==PAGER_OPEN ){
43920 rc = sqlite3PagerSharedLock(pPager);
43922 if( pPager->eState==PAGER_READER ){
43923 assert( rc==SQLITE_OK );
43924 rc = pagerLockDb(pPager, RESERVED_LOCK);
43926 if( rc==SQLITE_OK ){
43927 sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
43929 if( rc==SQLITE_OK && state==PAGER_READER ){
43930 pagerUnlockDb(pPager, SHARED_LOCK);
43931 }else if( state==PAGER_OPEN ){
43932 pager_unlock(pPager);
43934 assert( state==pPager->eState );
43939 /* Return the new journal mode */
43940 return (int)pPager->journalMode;
43944 ** Return the current journal mode.
43946 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
43947 return (int)pPager->journalMode;
43951 ** Return TRUE if the pager is in a state where it is OK to change the
43952 ** journalmode. Journalmode changes can only happen when the database
43953 ** is unmodified.
43955 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
43956 assert( assert_pager_state(pPager) );
43957 if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
43958 if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
43959 return 1;
43963 ** Get/set the size-limit used for persistent journal files.
43965 ** Setting the size limit to -1 means no limit is enforced.
43966 ** An attempt to set a limit smaller than -1 is a no-op.
43968 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
43969 if( iLimit>=-1 ){
43970 pPager->journalSizeLimit = iLimit;
43971 sqlite3WalLimit(pPager->pWal, iLimit);
43973 return pPager->journalSizeLimit;
43977 ** Return a pointer to the pPager->pBackup variable. The backup module
43978 ** in backup.c maintains the content of this variable. This module
43979 ** uses it opaquely as an argument to sqlite3BackupRestart() and
43980 ** sqlite3BackupUpdate() only.
43982 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
43983 return &pPager->pBackup;
43986 #ifndef SQLITE_OMIT_WAL
43988 ** This function is called when the user invokes "PRAGMA wal_checkpoint",
43989 ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
43990 ** or wal_blocking_checkpoint() API functions.
43992 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
43994 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){
43995 int rc = SQLITE_OK;
43996 if( pPager->pWal ){
43997 rc = sqlite3WalCheckpoint(pPager->pWal, eMode,
43998 pPager->xBusyHandler, pPager->pBusyHandlerArg,
43999 pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
44000 pnLog, pnCkpt
44003 return rc;
44006 SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
44007 return sqlite3WalCallback(pPager->pWal);
44011 ** Return true if the underlying VFS for the given pager supports the
44012 ** primitives necessary for write-ahead logging.
44014 SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
44015 const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
44016 return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
44020 ** Attempt to take an exclusive lock on the database file. If a PENDING lock
44021 ** is obtained instead, immediately release it.
44023 static int pagerExclusiveLock(Pager *pPager){
44024 int rc; /* Return code */
44026 assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
44027 rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
44028 if( rc!=SQLITE_OK ){
44029 /* If the attempt to grab the exclusive lock failed, release the
44030 ** pending lock that may have been obtained instead. */
44031 pagerUnlockDb(pPager, SHARED_LOCK);
44034 return rc;
44038 ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
44039 ** exclusive-locking mode when this function is called, take an EXCLUSIVE
44040 ** lock on the database file and use heap-memory to store the wal-index
44041 ** in. Otherwise, use the normal shared-memory.
44043 static int pagerOpenWal(Pager *pPager){
44044 int rc = SQLITE_OK;
44046 assert( pPager->pWal==0 && pPager->tempFile==0 );
44047 assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK || pPager->noReadlock);
44049 /* If the pager is already in exclusive-mode, the WAL module will use
44050 ** heap-memory for the wal-index instead of the VFS shared-memory
44051 ** implementation. Take the exclusive lock now, before opening the WAL
44052 ** file, to make sure this is safe.
44054 if( pPager->exclusiveMode ){
44055 rc = pagerExclusiveLock(pPager);
44058 /* Open the connection to the log file. If this operation fails,
44059 ** (e.g. due to malloc() failure), return an error code.
44061 if( rc==SQLITE_OK ){
44062 rc = sqlite3WalOpen(pPager->pVfs,
44063 pPager->fd, pPager->zWal, pPager->exclusiveMode,
44064 pPager->journalSizeLimit, &pPager->pWal
44068 return rc;
44073 ** The caller must be holding a SHARED lock on the database file to call
44074 ** this function.
44076 ** If the pager passed as the first argument is open on a real database
44077 ** file (not a temp file or an in-memory database), and the WAL file
44078 ** is not already open, make an attempt to open it now. If successful,
44079 ** return SQLITE_OK. If an error occurs or the VFS used by the pager does
44080 ** not support the xShmXXX() methods, return an error code. *pbOpen is
44081 ** not modified in either case.
44083 ** If the pager is open on a temp-file (or in-memory database), or if
44084 ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
44085 ** without doing anything.
44087 SQLITE_PRIVATE int sqlite3PagerOpenWal(
44088 Pager *pPager, /* Pager object */
44089 int *pbOpen /* OUT: Set to true if call is a no-op */
44091 int rc = SQLITE_OK; /* Return code */
44093 assert( assert_pager_state(pPager) );
44094 assert( pPager->eState==PAGER_OPEN || pbOpen );
44095 assert( pPager->eState==PAGER_READER || !pbOpen );
44096 assert( pbOpen==0 || *pbOpen==0 );
44097 assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
44099 if( !pPager->tempFile && !pPager->pWal ){
44100 if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
44102 /* Close any rollback journal previously open */
44103 sqlite3OsClose(pPager->jfd);
44105 rc = pagerOpenWal(pPager);
44106 if( rc==SQLITE_OK ){
44107 pPager->journalMode = PAGER_JOURNALMODE_WAL;
44108 pPager->eState = PAGER_OPEN;
44110 }else{
44111 *pbOpen = 1;
44114 return rc;
44118 ** This function is called to close the connection to the log file prior
44119 ** to switching from WAL to rollback mode.
44121 ** Before closing the log file, this function attempts to take an
44122 ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
44123 ** error (SQLITE_BUSY) is returned and the log connection is not closed.
44124 ** If successful, the EXCLUSIVE lock is not released before returning.
44126 SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
44127 int rc = SQLITE_OK;
44129 assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
44131 /* If the log file is not already open, but does exist in the file-system,
44132 ** it may need to be checkpointed before the connection can switch to
44133 ** rollback mode. Open it now so this can happen.
44135 if( !pPager->pWal ){
44136 int logexists = 0;
44137 rc = pagerLockDb(pPager, SHARED_LOCK);
44138 if( rc==SQLITE_OK ){
44139 rc = sqlite3OsAccess(
44140 pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
44143 if( rc==SQLITE_OK && logexists ){
44144 rc = pagerOpenWal(pPager);
44148 /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
44149 ** the database file, the log and log-summary files will be deleted.
44151 if( rc==SQLITE_OK && pPager->pWal ){
44152 rc = pagerExclusiveLock(pPager);
44153 if( rc==SQLITE_OK ){
44154 rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
44155 pPager->pageSize, (u8*)pPager->pTmpSpace);
44156 pPager->pWal = 0;
44159 return rc;
44163 ** Unless this is an in-memory or temporary database, clear the pager cache.
44165 SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
44166 if( !MEMDB && pPager->tempFile==0 ) pager_reset(pPager);
44169 #ifdef SQLITE_HAS_CODEC
44171 ** This function is called by the wal module when writing page content
44172 ** into the log file.
44174 ** This function returns a pointer to a buffer containing the encrypted
44175 ** page content. If a malloc fails, this function may return NULL.
44177 SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
44178 void *aData = 0;
44179 CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
44180 return aData;
44182 #endif /* SQLITE_HAS_CODEC */
44184 #endif /* !SQLITE_OMIT_WAL */
44186 #endif /* SQLITE_OMIT_DISKIO */
44188 /************** End of pager.c ***********************************************/
44189 /************** Begin file wal.c *********************************************/
44191 ** 2010 February 1
44193 ** The author disclaims copyright to this source code. In place of
44194 ** a legal notice, here is a blessing:
44196 ** May you do good and not evil.
44197 ** May you find forgiveness for yourself and forgive others.
44198 ** May you share freely, never taking more than you give.
44200 *************************************************************************
44202 ** This file contains the implementation of a write-ahead log (WAL) used in
44203 ** "journal_mode=WAL" mode.
44205 ** WRITE-AHEAD LOG (WAL) FILE FORMAT
44207 ** A WAL file consists of a header followed by zero or more "frames".
44208 ** Each frame records the revised content of a single page from the
44209 ** database file. All changes to the database are recorded by writing
44210 ** frames into the WAL. Transactions commit when a frame is written that
44211 ** contains a commit marker. A single WAL can and usually does record
44212 ** multiple transactions. Periodically, the content of the WAL is
44213 ** transferred back into the database file in an operation called a
44214 ** "checkpoint".
44216 ** A single WAL file can be used multiple times. In other words, the
44217 ** WAL can fill up with frames and then be checkpointed and then new
44218 ** frames can overwrite the old ones. A WAL always grows from beginning
44219 ** toward the end. Checksums and counters attached to each frame are
44220 ** used to determine which frames within the WAL are valid and which
44221 ** are leftovers from prior checkpoints.
44223 ** The WAL header is 32 bytes in size and consists of the following eight
44224 ** big-endian 32-bit unsigned integer values:
44226 ** 0: Magic number. 0x377f0682 or 0x377f0683
44227 ** 4: File format version. Currently 3007000
44228 ** 8: Database page size. Example: 1024
44229 ** 12: Checkpoint sequence number
44230 ** 16: Salt-1, random integer incremented with each checkpoint
44231 ** 20: Salt-2, a different random integer changing with each ckpt
44232 ** 24: Checksum-1 (first part of checksum for first 24 bytes of header).
44233 ** 28: Checksum-2 (second part of checksum for first 24 bytes of header).
44235 ** Immediately following the wal-header are zero or more frames. Each
44236 ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
44237 ** of page data. The frame-header is six big-endian 32-bit unsigned
44238 ** integer values, as follows:
44240 ** 0: Page number.
44241 ** 4: For commit records, the size of the database image in pages
44242 ** after the commit. For all other records, zero.
44243 ** 8: Salt-1 (copied from the header)
44244 ** 12: Salt-2 (copied from the header)
44245 ** 16: Checksum-1.
44246 ** 20: Checksum-2.
44248 ** A frame is considered valid if and only if the following conditions are
44249 ** true:
44251 ** (1) The salt-1 and salt-2 values in the frame-header match
44252 ** salt values in the wal-header
44254 ** (2) The checksum values in the final 8 bytes of the frame-header
44255 ** exactly match the checksum computed consecutively on the
44256 ** WAL header and the first 8 bytes and the content of all frames
44257 ** up to and including the current frame.
44259 ** The checksum is computed using 32-bit big-endian integers if the
44260 ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
44261 ** is computed using little-endian if the magic number is 0x377f0682.
44262 ** The checksum values are always stored in the frame header in a
44263 ** big-endian format regardless of which byte order is used to compute
44264 ** the checksum. The checksum is computed by interpreting the input as
44265 ** an even number of unsigned 32-bit integers: x[0] through x[N]. The
44266 ** algorithm used for the checksum is as follows:
44268 ** for i from 0 to n-1 step 2:
44269 ** s0 += x[i] + s1;
44270 ** s1 += x[i+1] + s0;
44271 ** endfor
44273 ** Note that s0 and s1 are both weighted checksums using fibonacci weights
44274 ** in reverse order (the largest fibonacci weight occurs on the first element
44275 ** of the sequence being summed.) The s1 value spans all 32-bit
44276 ** terms of the sequence whereas s0 omits the final term.
44278 ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
44279 ** WAL is transferred into the database, then the database is VFS.xSync-ed.
44280 ** The VFS.xSync operations serve as write barriers - all writes launched
44281 ** before the xSync must complete before any write that launches after the
44282 ** xSync begins.
44284 ** After each checkpoint, the salt-1 value is incremented and the salt-2
44285 ** value is randomized. This prevents old and new frames in the WAL from
44286 ** being considered valid at the same time and being checkpointing together
44287 ** following a crash.
44289 ** READER ALGORITHM
44291 ** To read a page from the database (call it page number P), a reader
44292 ** first checks the WAL to see if it contains page P. If so, then the
44293 ** last valid instance of page P that is a followed by a commit frame
44294 ** or is a commit frame itself becomes the value read. If the WAL
44295 ** contains no copies of page P that are valid and which are a commit
44296 ** frame or are followed by a commit frame, then page P is read from
44297 ** the database file.
44299 ** To start a read transaction, the reader records the index of the last
44300 ** valid frame in the WAL. The reader uses this recorded "mxFrame" value
44301 ** for all subsequent read operations. New transactions can be appended
44302 ** to the WAL, but as long as the reader uses its original mxFrame value
44303 ** and ignores the newly appended content, it will see a consistent snapshot
44304 ** of the database from a single point in time. This technique allows
44305 ** multiple concurrent readers to view different versions of the database
44306 ** content simultaneously.
44308 ** The reader algorithm in the previous paragraphs works correctly, but
44309 ** because frames for page P can appear anywhere within the WAL, the
44310 ** reader has to scan the entire WAL looking for page P frames. If the
44311 ** WAL is large (multiple megabytes is typical) that scan can be slow,
44312 ** and read performance suffers. To overcome this problem, a separate
44313 ** data structure called the wal-index is maintained to expedite the
44314 ** search for frames of a particular page.
44316 ** WAL-INDEX FORMAT
44318 ** Conceptually, the wal-index is shared memory, though VFS implementations
44319 ** might choose to implement the wal-index using a mmapped file. Because
44320 ** the wal-index is shared memory, SQLite does not support journal_mode=WAL
44321 ** on a network filesystem. All users of the database must be able to
44322 ** share memory.
44324 ** The wal-index is transient. After a crash, the wal-index can (and should
44325 ** be) reconstructed from the original WAL file. In fact, the VFS is required
44326 ** to either truncate or zero the header of the wal-index when the last
44327 ** connection to it closes. Because the wal-index is transient, it can
44328 ** use an architecture-specific format; it does not have to be cross-platform.
44329 ** Hence, unlike the database and WAL file formats which store all values
44330 ** as big endian, the wal-index can store multi-byte values in the native
44331 ** byte order of the host computer.
44333 ** The purpose of the wal-index is to answer this question quickly: Given
44334 ** a page number P, return the index of the last frame for page P in the WAL,
44335 ** or return NULL if there are no frames for page P in the WAL.
44337 ** The wal-index consists of a header region, followed by an one or
44338 ** more index blocks.
44340 ** The wal-index header contains the total number of frames within the WAL
44341 ** in the the mxFrame field.
44343 ** Each index block except for the first contains information on
44344 ** HASHTABLE_NPAGE frames. The first index block contains information on
44345 ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
44346 ** HASHTABLE_NPAGE are selected so that together the wal-index header and
44347 ** first index block are the same size as all other index blocks in the
44348 ** wal-index.
44350 ** Each index block contains two sections, a page-mapping that contains the
44351 ** database page number associated with each wal frame, and a hash-table
44352 ** that allows readers to query an index block for a specific page number.
44353 ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
44354 ** for the first index block) 32-bit page numbers. The first entry in the
44355 ** first index-block contains the database page number corresponding to the
44356 ** first frame in the WAL file. The first entry in the second index block
44357 ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
44358 ** the log, and so on.
44360 ** The last index block in a wal-index usually contains less than the full
44361 ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
44362 ** depending on the contents of the WAL file. This does not change the
44363 ** allocated size of the page-mapping array - the page-mapping array merely
44364 ** contains unused entries.
44366 ** Even without using the hash table, the last frame for page P
44367 ** can be found by scanning the page-mapping sections of each index block
44368 ** starting with the last index block and moving toward the first, and
44369 ** within each index block, starting at the end and moving toward the
44370 ** beginning. The first entry that equals P corresponds to the frame
44371 ** holding the content for that page.
44373 ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
44374 ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
44375 ** hash table for each page number in the mapping section, so the hash
44376 ** table is never more than half full. The expected number of collisions
44377 ** prior to finding a match is 1. Each entry of the hash table is an
44378 ** 1-based index of an entry in the mapping section of the same
44379 ** index block. Let K be the 1-based index of the largest entry in
44380 ** the mapping section. (For index blocks other than the last, K will
44381 ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
44382 ** K will be (mxFrame%HASHTABLE_NPAGE).) Unused slots of the hash table
44383 ** contain a value of 0.
44385 ** To look for page P in the hash table, first compute a hash iKey on
44386 ** P as follows:
44388 ** iKey = (P * 383) % HASHTABLE_NSLOT
44390 ** Then start scanning entries of the hash table, starting with iKey
44391 ** (wrapping around to the beginning when the end of the hash table is
44392 ** reached) until an unused hash slot is found. Let the first unused slot
44393 ** be at index iUnused. (iUnused might be less than iKey if there was
44394 ** wrap-around.) Because the hash table is never more than half full,
44395 ** the search is guaranteed to eventually hit an unused entry. Let
44396 ** iMax be the value between iKey and iUnused, closest to iUnused,
44397 ** where aHash[iMax]==P. If there is no iMax entry (if there exists
44398 ** no hash slot such that aHash[i]==p) then page P is not in the
44399 ** current index block. Otherwise the iMax-th mapping entry of the
44400 ** current index block corresponds to the last entry that references
44401 ** page P.
44403 ** A hash search begins with the last index block and moves toward the
44404 ** first index block, looking for entries corresponding to page P. On
44405 ** average, only two or three slots in each index block need to be
44406 ** examined in order to either find the last entry for page P, or to
44407 ** establish that no such entry exists in the block. Each index block
44408 ** holds over 4000 entries. So two or three index blocks are sufficient
44409 ** to cover a typical 10 megabyte WAL file, assuming 1K pages. 8 or 10
44410 ** comparisons (on average) suffice to either locate a frame in the
44411 ** WAL or to establish that the frame does not exist in the WAL. This
44412 ** is much faster than scanning the entire 10MB WAL.
44414 ** Note that entries are added in order of increasing K. Hence, one
44415 ** reader might be using some value K0 and a second reader that started
44416 ** at a later time (after additional transactions were added to the WAL
44417 ** and to the wal-index) might be using a different value K1, where K1>K0.
44418 ** Both readers can use the same hash table and mapping section to get
44419 ** the correct result. There may be entries in the hash table with
44420 ** K>K0 but to the first reader, those entries will appear to be unused
44421 ** slots in the hash table and so the first reader will get an answer as
44422 ** if no values greater than K0 had ever been inserted into the hash table
44423 ** in the first place - which is what reader one wants. Meanwhile, the
44424 ** second reader using K1 will see additional values that were inserted
44425 ** later, which is exactly what reader two wants.
44427 ** When a rollback occurs, the value of K is decreased. Hash table entries
44428 ** that correspond to frames greater than the new K value are removed
44429 ** from the hash table at this point.
44431 #ifndef SQLITE_OMIT_WAL
44435 ** Trace output macros
44437 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
44438 SQLITE_PRIVATE int sqlite3WalTrace = 0;
44439 # define WALTRACE(X) if(sqlite3WalTrace) sqlite3DebugPrintf X
44440 #else
44441 # define WALTRACE(X)
44442 #endif
44445 ** The maximum (and only) versions of the wal and wal-index formats
44446 ** that may be interpreted by this version of SQLite.
44448 ** If a client begins recovering a WAL file and finds that (a) the checksum
44449 ** values in the wal-header are correct and (b) the version field is not
44450 ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
44452 ** Similarly, if a client successfully reads a wal-index header (i.e. the
44453 ** checksum test is successful) and finds that the version field is not
44454 ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
44455 ** returns SQLITE_CANTOPEN.
44457 #define WAL_MAX_VERSION 3007000
44458 #define WALINDEX_MAX_VERSION 3007000
44461 ** Indices of various locking bytes. WAL_NREADER is the number
44462 ** of available reader locks and should be at least 3.
44464 #define WAL_WRITE_LOCK 0
44465 #define WAL_ALL_BUT_WRITE 1
44466 #define WAL_CKPT_LOCK 1
44467 #define WAL_RECOVER_LOCK 2
44468 #define WAL_READ_LOCK(I) (3+(I))
44469 #define WAL_NREADER (SQLITE_SHM_NLOCK-3)
44472 /* Object declarations */
44473 typedef struct WalIndexHdr WalIndexHdr;
44474 typedef struct WalIterator WalIterator;
44475 typedef struct WalCkptInfo WalCkptInfo;
44479 ** The following object holds a copy of the wal-index header content.
44481 ** The actual header in the wal-index consists of two copies of this
44482 ** object.
44484 ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
44485 ** Or it can be 1 to represent a 65536-byte page. The latter case was
44486 ** added in 3.7.1 when support for 64K pages was added.
44488 struct WalIndexHdr {
44489 u32 iVersion; /* Wal-index version */
44490 u32 unused; /* Unused (padding) field */
44491 u32 iChange; /* Counter incremented each transaction */
44492 u8 isInit; /* 1 when initialized */
44493 u8 bigEndCksum; /* True if checksums in WAL are big-endian */
44494 u16 szPage; /* Database page size in bytes. 1==64K */
44495 u32 mxFrame; /* Index of last valid frame in the WAL */
44496 u32 nPage; /* Size of database in pages */
44497 u32 aFrameCksum[2]; /* Checksum of last frame in log */
44498 u32 aSalt[2]; /* Two salt values copied from WAL header */
44499 u32 aCksum[2]; /* Checksum over all prior fields */
44503 ** A copy of the following object occurs in the wal-index immediately
44504 ** following the second copy of the WalIndexHdr. This object stores
44505 ** information used by checkpoint.
44507 ** nBackfill is the number of frames in the WAL that have been written
44508 ** back into the database. (We call the act of moving content from WAL to
44509 ** database "backfilling".) The nBackfill number is never greater than
44510 ** WalIndexHdr.mxFrame. nBackfill can only be increased by threads
44511 ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
44512 ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
44513 ** mxFrame back to zero when the WAL is reset.
44515 ** There is one entry in aReadMark[] for each reader lock. If a reader
44516 ** holds read-lock K, then the value in aReadMark[K] is no greater than
44517 ** the mxFrame for that reader. The value READMARK_NOT_USED (0xffffffff)
44518 ** for any aReadMark[] means that entry is unused. aReadMark[0] is
44519 ** a special case; its value is never used and it exists as a place-holder
44520 ** to avoid having to offset aReadMark[] indexs by one. Readers holding
44521 ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
44522 ** directly from the database.
44524 ** The value of aReadMark[K] may only be changed by a thread that
44525 ** is holding an exclusive lock on WAL_READ_LOCK(K). Thus, the value of
44526 ** aReadMark[K] cannot changed while there is a reader is using that mark
44527 ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
44529 ** The checkpointer may only transfer frames from WAL to database where
44530 ** the frame numbers are less than or equal to every aReadMark[] that is
44531 ** in use (that is, every aReadMark[j] for which there is a corresponding
44532 ** WAL_READ_LOCK(j)). New readers (usually) pick the aReadMark[] with the
44533 ** largest value and will increase an unused aReadMark[] to mxFrame if there
44534 ** is not already an aReadMark[] equal to mxFrame. The exception to the
44535 ** previous sentence is when nBackfill equals mxFrame (meaning that everything
44536 ** in the WAL has been backfilled into the database) then new readers
44537 ** will choose aReadMark[0] which has value 0 and hence such reader will
44538 ** get all their all content directly from the database file and ignore
44539 ** the WAL.
44541 ** Writers normally append new frames to the end of the WAL. However,
44542 ** if nBackfill equals mxFrame (meaning that all WAL content has been
44543 ** written back into the database) and if no readers are using the WAL
44544 ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
44545 ** the writer will first "reset" the WAL back to the beginning and start
44546 ** writing new content beginning at frame 1.
44548 ** We assume that 32-bit loads are atomic and so no locks are needed in
44549 ** order to read from any aReadMark[] entries.
44551 struct WalCkptInfo {
44552 u32 nBackfill; /* Number of WAL frames backfilled into DB */
44553 u32 aReadMark[WAL_NREADER]; /* Reader marks */
44555 #define READMARK_NOT_USED 0xffffffff
44558 /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
44559 ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
44560 ** only support mandatory file-locks, we do not read or write data
44561 ** from the region of the file on which locks are applied.
44563 #define WALINDEX_LOCK_OFFSET (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
44564 #define WALINDEX_LOCK_RESERVED 16
44565 #define WALINDEX_HDR_SIZE (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
44567 /* Size of header before each frame in wal */
44568 #define WAL_FRAME_HDRSIZE 24
44570 /* Size of write ahead log header, including checksum. */
44571 /* #define WAL_HDRSIZE 24 */
44572 #define WAL_HDRSIZE 32
44574 /* WAL magic value. Either this value, or the same value with the least
44575 ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
44576 ** big-endian format in the first 4 bytes of a WAL file.
44578 ** If the LSB is set, then the checksums for each frame within the WAL
44579 ** file are calculated by treating all data as an array of 32-bit
44580 ** big-endian words. Otherwise, they are calculated by interpreting
44581 ** all data as 32-bit little-endian words.
44583 #define WAL_MAGIC 0x377f0682
44586 ** Return the offset of frame iFrame in the write-ahead log file,
44587 ** assuming a database page size of szPage bytes. The offset returned
44588 ** is to the start of the write-ahead log frame-header.
44590 #define walFrameOffset(iFrame, szPage) ( \
44591 WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE) \
44595 ** An open write-ahead log file is represented by an instance of the
44596 ** following object.
44598 struct Wal {
44599 sqlite3_vfs *pVfs; /* The VFS used to create pDbFd */
44600 sqlite3_file *pDbFd; /* File handle for the database file */
44601 sqlite3_file *pWalFd; /* File handle for WAL file */
44602 u32 iCallback; /* Value to pass to log callback (or 0) */
44603 i64 mxWalSize; /* Truncate WAL to this size upon reset */
44604 int nWiData; /* Size of array apWiData */
44605 volatile u32 **apWiData; /* Pointer to wal-index content in memory */
44606 u32 szPage; /* Database page size */
44607 i16 readLock; /* Which read lock is being held. -1 for none */
44608 u8 exclusiveMode; /* Non-zero if connection is in exclusive mode */
44609 u8 writeLock; /* True if in a write transaction */
44610 u8 ckptLock; /* True if holding a checkpoint lock */
44611 u8 readOnly; /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
44612 WalIndexHdr hdr; /* Wal-index header for current transaction */
44613 const char *zWalName; /* Name of WAL file */
44614 u32 nCkpt; /* Checkpoint sequence counter in the wal-header */
44615 #ifdef SQLITE_DEBUG
44616 u8 lockError; /* True if a locking error has occurred */
44617 #endif
44621 ** Candidate values for Wal.exclusiveMode.
44623 #define WAL_NORMAL_MODE 0
44624 #define WAL_EXCLUSIVE_MODE 1
44625 #define WAL_HEAPMEMORY_MODE 2
44628 ** Possible values for WAL.readOnly
44630 #define WAL_RDWR 0 /* Normal read/write connection */
44631 #define WAL_RDONLY 1 /* The WAL file is readonly */
44632 #define WAL_SHM_RDONLY 2 /* The SHM file is readonly */
44635 ** Each page of the wal-index mapping contains a hash-table made up of
44636 ** an array of HASHTABLE_NSLOT elements of the following type.
44638 typedef u16 ht_slot;
44641 ** This structure is used to implement an iterator that loops through
44642 ** all frames in the WAL in database page order. Where two or more frames
44643 ** correspond to the same database page, the iterator visits only the
44644 ** frame most recently written to the WAL (in other words, the frame with
44645 ** the largest index).
44647 ** The internals of this structure are only accessed by:
44649 ** walIteratorInit() - Create a new iterator,
44650 ** walIteratorNext() - Step an iterator,
44651 ** walIteratorFree() - Free an iterator.
44653 ** This functionality is used by the checkpoint code (see walCheckpoint()).
44655 struct WalIterator {
44656 int iPrior; /* Last result returned from the iterator */
44657 int nSegment; /* Number of entries in aSegment[] */
44658 struct WalSegment {
44659 int iNext; /* Next slot in aIndex[] not yet returned */
44660 ht_slot *aIndex; /* i0, i1, i2... such that aPgno[iN] ascend */
44661 u32 *aPgno; /* Array of page numbers. */
44662 int nEntry; /* Nr. of entries in aPgno[] and aIndex[] */
44663 int iZero; /* Frame number associated with aPgno[0] */
44664 } aSegment[1]; /* One for every 32KB page in the wal-index */
44668 ** Define the parameters of the hash tables in the wal-index file. There
44669 ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
44670 ** wal-index.
44672 ** Changing any of these constants will alter the wal-index format and
44673 ** create incompatibilities.
44675 #define HASHTABLE_NPAGE 4096 /* Must be power of 2 */
44676 #define HASHTABLE_HASH_1 383 /* Should be prime */
44677 #define HASHTABLE_NSLOT (HASHTABLE_NPAGE*2) /* Must be a power of 2 */
44680 ** The block of page numbers associated with the first hash-table in a
44681 ** wal-index is smaller than usual. This is so that there is a complete
44682 ** hash-table on each aligned 32KB page of the wal-index.
44684 #define HASHTABLE_NPAGE_ONE (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
44686 /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
44687 #define WALINDEX_PGSZ ( \
44688 sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
44692 ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
44693 ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
44694 ** numbered from zero.
44696 ** If this call is successful, *ppPage is set to point to the wal-index
44697 ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
44698 ** then an SQLite error code is returned and *ppPage is set to 0.
44700 static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
44701 int rc = SQLITE_OK;
44703 /* Enlarge the pWal->apWiData[] array if required */
44704 if( pWal->nWiData<=iPage ){
44705 int nByte = sizeof(u32*)*(iPage+1);
44706 volatile u32 **apNew;
44707 apNew = (volatile u32 **)sqlite3_realloc((void *)pWal->apWiData, nByte);
44708 if( !apNew ){
44709 *ppPage = 0;
44710 return SQLITE_NOMEM;
44712 memset((void*)&apNew[pWal->nWiData], 0,
44713 sizeof(u32*)*(iPage+1-pWal->nWiData));
44714 pWal->apWiData = apNew;
44715 pWal->nWiData = iPage+1;
44718 /* Request a pointer to the required page from the VFS */
44719 if( pWal->apWiData[iPage]==0 ){
44720 if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
44721 pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
44722 if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM;
44723 }else{
44724 rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
44725 pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
44727 if( rc==SQLITE_READONLY ){
44728 pWal->readOnly |= WAL_SHM_RDONLY;
44729 rc = SQLITE_OK;
44734 *ppPage = pWal->apWiData[iPage];
44735 assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
44736 return rc;
44740 ** Return a pointer to the WalCkptInfo structure in the wal-index.
44742 static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
44743 assert( pWal->nWiData>0 && pWal->apWiData[0] );
44744 return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
44748 ** Return a pointer to the WalIndexHdr structure in the wal-index.
44750 static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
44751 assert( pWal->nWiData>0 && pWal->apWiData[0] );
44752 return (volatile WalIndexHdr*)pWal->apWiData[0];
44756 ** The argument to this macro must be of type u32. On a little-endian
44757 ** architecture, it returns the u32 value that results from interpreting
44758 ** the 4 bytes as a big-endian value. On a big-endian architecture, it
44759 ** returns the value that would be produced by intepreting the 4 bytes
44760 ** of the input value as a little-endian integer.
44762 #define BYTESWAP32(x) ( \
44763 (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8) \
44764 + (((x)&0x00FF0000)>>8) + (((x)&0xFF000000)>>24) \
44768 ** Generate or extend an 8 byte checksum based on the data in
44769 ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
44770 ** initial values of 0 and 0 if aIn==NULL).
44772 ** The checksum is written back into aOut[] before returning.
44774 ** nByte must be a positive multiple of 8.
44776 static void walChecksumBytes(
44777 int nativeCksum, /* True for native byte-order, false for non-native */
44778 u8 *a, /* Content to be checksummed */
44779 int nByte, /* Bytes of content in a[]. Must be a multiple of 8. */
44780 const u32 *aIn, /* Initial checksum value input */
44781 u32 *aOut /* OUT: Final checksum value output */
44783 u32 s1, s2;
44784 u32 *aData = (u32 *)a;
44785 u32 *aEnd = (u32 *)&a[nByte];
44787 if( aIn ){
44788 s1 = aIn[0];
44789 s2 = aIn[1];
44790 }else{
44791 s1 = s2 = 0;
44794 assert( nByte>=8 );
44795 assert( (nByte&0x00000007)==0 );
44797 if( nativeCksum ){
44798 do {
44799 s1 += *aData++ + s2;
44800 s2 += *aData++ + s1;
44801 }while( aData<aEnd );
44802 }else{
44803 do {
44804 s1 += BYTESWAP32(aData[0]) + s2;
44805 s2 += BYTESWAP32(aData[1]) + s1;
44806 aData += 2;
44807 }while( aData<aEnd );
44810 aOut[0] = s1;
44811 aOut[1] = s2;
44814 static void walShmBarrier(Wal *pWal){
44815 if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
44816 sqlite3OsShmBarrier(pWal->pDbFd);
44821 ** Write the header information in pWal->hdr into the wal-index.
44823 ** The checksum on pWal->hdr is updated before it is written.
44825 static void walIndexWriteHdr(Wal *pWal){
44826 volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
44827 const int nCksum = offsetof(WalIndexHdr, aCksum);
44829 assert( pWal->writeLock );
44830 pWal->hdr.isInit = 1;
44831 pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
44832 walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
44833 memcpy((void *)&aHdr[1], (void *)&pWal->hdr, sizeof(WalIndexHdr));
44834 walShmBarrier(pWal);
44835 memcpy((void *)&aHdr[0], (void *)&pWal->hdr, sizeof(WalIndexHdr));
44839 ** This function encodes a single frame header and writes it to a buffer
44840 ** supplied by the caller. A frame-header is made up of a series of
44841 ** 4-byte big-endian integers, as follows:
44843 ** 0: Page number.
44844 ** 4: For commit records, the size of the database image in pages
44845 ** after the commit. For all other records, zero.
44846 ** 8: Salt-1 (copied from the wal-header)
44847 ** 12: Salt-2 (copied from the wal-header)
44848 ** 16: Checksum-1.
44849 ** 20: Checksum-2.
44851 static void walEncodeFrame(
44852 Wal *pWal, /* The write-ahead log */
44853 u32 iPage, /* Database page number for frame */
44854 u32 nTruncate, /* New db size (or 0 for non-commit frames) */
44855 u8 *aData, /* Pointer to page data */
44856 u8 *aFrame /* OUT: Write encoded frame here */
44858 int nativeCksum; /* True for native byte-order checksums */
44859 u32 *aCksum = pWal->hdr.aFrameCksum;
44860 assert( WAL_FRAME_HDRSIZE==24 );
44861 sqlite3Put4byte(&aFrame[0], iPage);
44862 sqlite3Put4byte(&aFrame[4], nTruncate);
44863 memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
44865 nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
44866 walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
44867 walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
44869 sqlite3Put4byte(&aFrame[16], aCksum[0]);
44870 sqlite3Put4byte(&aFrame[20], aCksum[1]);
44874 ** Check to see if the frame with header in aFrame[] and content
44875 ** in aData[] is valid. If it is a valid frame, fill *piPage and
44876 ** *pnTruncate and return true. Return if the frame is not valid.
44878 static int walDecodeFrame(
44879 Wal *pWal, /* The write-ahead log */
44880 u32 *piPage, /* OUT: Database page number for frame */
44881 u32 *pnTruncate, /* OUT: New db size (or 0 if not commit) */
44882 u8 *aData, /* Pointer to page data (for checksum) */
44883 u8 *aFrame /* Frame data */
44885 int nativeCksum; /* True for native byte-order checksums */
44886 u32 *aCksum = pWal->hdr.aFrameCksum;
44887 u32 pgno; /* Page number of the frame */
44888 assert( WAL_FRAME_HDRSIZE==24 );
44890 /* A frame is only valid if the salt values in the frame-header
44891 ** match the salt values in the wal-header.
44893 if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
44894 return 0;
44897 /* A frame is only valid if the page number is creater than zero.
44899 pgno = sqlite3Get4byte(&aFrame[0]);
44900 if( pgno==0 ){
44901 return 0;
44904 /* A frame is only valid if a checksum of the WAL header,
44905 ** all prior frams, the first 16 bytes of this frame-header,
44906 ** and the frame-data matches the checksum in the last 8
44907 ** bytes of this frame-header.
44909 nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
44910 walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
44911 walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
44912 if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
44913 || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
44915 /* Checksum failed. */
44916 return 0;
44919 /* If we reach this point, the frame is valid. Return the page number
44920 ** and the new database size.
44922 *piPage = pgno;
44923 *pnTruncate = sqlite3Get4byte(&aFrame[4]);
44924 return 1;
44928 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
44930 ** Names of locks. This routine is used to provide debugging output and is not
44931 ** a part of an ordinary build.
44933 static const char *walLockName(int lockIdx){
44934 if( lockIdx==WAL_WRITE_LOCK ){
44935 return "WRITE-LOCK";
44936 }else if( lockIdx==WAL_CKPT_LOCK ){
44937 return "CKPT-LOCK";
44938 }else if( lockIdx==WAL_RECOVER_LOCK ){
44939 return "RECOVER-LOCK";
44940 }else{
44941 static char zName[15];
44942 sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
44943 lockIdx-WAL_READ_LOCK(0));
44944 return zName;
44947 #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
44951 ** Set or release locks on the WAL. Locks are either shared or exclusive.
44952 ** A lock cannot be moved directly between shared and exclusive - it must go
44953 ** through the unlocked state first.
44955 ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
44957 static int walLockShared(Wal *pWal, int lockIdx){
44958 int rc;
44959 if( pWal->exclusiveMode ) return SQLITE_OK;
44960 rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
44961 SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
44962 WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
44963 walLockName(lockIdx), rc ? "failed" : "ok"));
44964 VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
44965 return rc;
44967 static void walUnlockShared(Wal *pWal, int lockIdx){
44968 if( pWal->exclusiveMode ) return;
44969 (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
44970 SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
44971 WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
44973 static int walLockExclusive(Wal *pWal, int lockIdx, int n){
44974 int rc;
44975 if( pWal->exclusiveMode ) return SQLITE_OK;
44976 rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
44977 SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
44978 WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
44979 walLockName(lockIdx), n, rc ? "failed" : "ok"));
44980 VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
44981 return rc;
44983 static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
44984 if( pWal->exclusiveMode ) return;
44985 (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
44986 SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
44987 WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
44988 walLockName(lockIdx), n));
44992 ** Compute a hash on a page number. The resulting hash value must land
44993 ** between 0 and (HASHTABLE_NSLOT-1). The walHashNext() function advances
44994 ** the hash to the next value in the event of a collision.
44996 static int walHash(u32 iPage){
44997 assert( iPage>0 );
44998 assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
44999 return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
45001 static int walNextHash(int iPriorHash){
45002 return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
45006 ** Return pointers to the hash table and page number array stored on
45007 ** page iHash of the wal-index. The wal-index is broken into 32KB pages
45008 ** numbered starting from 0.
45010 ** Set output variable *paHash to point to the start of the hash table
45011 ** in the wal-index file. Set *piZero to one less than the frame
45012 ** number of the first frame indexed by this hash table. If a
45013 ** slot in the hash table is set to N, it refers to frame number
45014 ** (*piZero+N) in the log.
45016 ** Finally, set *paPgno so that *paPgno[1] is the page number of the
45017 ** first frame indexed by the hash table, frame (*piZero+1).
45019 static int walHashGet(
45020 Wal *pWal, /* WAL handle */
45021 int iHash, /* Find the iHash'th table */
45022 volatile ht_slot **paHash, /* OUT: Pointer to hash index */
45023 volatile u32 **paPgno, /* OUT: Pointer to page number array */
45024 u32 *piZero /* OUT: Frame associated with *paPgno[0] */
45026 int rc; /* Return code */
45027 volatile u32 *aPgno;
45029 rc = walIndexPage(pWal, iHash, &aPgno);
45030 assert( rc==SQLITE_OK || iHash>0 );
45032 if( rc==SQLITE_OK ){
45033 u32 iZero;
45034 volatile ht_slot *aHash;
45036 aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
45037 if( iHash==0 ){
45038 aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
45039 iZero = 0;
45040 }else{
45041 iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
45044 *paPgno = &aPgno[-1];
45045 *paHash = aHash;
45046 *piZero = iZero;
45048 return rc;
45052 ** Return the number of the wal-index page that contains the hash-table
45053 ** and page-number array that contain entries corresponding to WAL frame
45054 ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
45055 ** are numbered starting from 0.
45057 static int walFramePage(u32 iFrame){
45058 int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
45059 assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
45060 && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
45061 && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
45062 && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
45063 && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
45065 return iHash;
45069 ** Return the page number associated with frame iFrame in this WAL.
45071 static u32 walFramePgno(Wal *pWal, u32 iFrame){
45072 int iHash = walFramePage(iFrame);
45073 if( iHash==0 ){
45074 return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
45076 return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
45080 ** Remove entries from the hash table that point to WAL slots greater
45081 ** than pWal->hdr.mxFrame.
45083 ** This function is called whenever pWal->hdr.mxFrame is decreased due
45084 ** to a rollback or savepoint.
45086 ** At most only the hash table containing pWal->hdr.mxFrame needs to be
45087 ** updated. Any later hash tables will be automatically cleared when
45088 ** pWal->hdr.mxFrame advances to the point where those hash tables are
45089 ** actually needed.
45091 static void walCleanupHash(Wal *pWal){
45092 volatile ht_slot *aHash = 0; /* Pointer to hash table to clear */
45093 volatile u32 *aPgno = 0; /* Page number array for hash table */
45094 u32 iZero = 0; /* frame == (aHash[x]+iZero) */
45095 int iLimit = 0; /* Zero values greater than this */
45096 int nByte; /* Number of bytes to zero in aPgno[] */
45097 int i; /* Used to iterate through aHash[] */
45099 assert( pWal->writeLock );
45100 testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
45101 testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
45102 testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
45104 if( pWal->hdr.mxFrame==0 ) return;
45106 /* Obtain pointers to the hash-table and page-number array containing
45107 ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
45108 ** that the page said hash-table and array reside on is already mapped.
45110 assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
45111 assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
45112 walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
45114 /* Zero all hash-table entries that correspond to frame numbers greater
45115 ** than pWal->hdr.mxFrame.
45117 iLimit = pWal->hdr.mxFrame - iZero;
45118 assert( iLimit>0 );
45119 for(i=0; i<HASHTABLE_NSLOT; i++){
45120 if( aHash[i]>iLimit ){
45121 aHash[i] = 0;
45125 /* Zero the entries in the aPgno array that correspond to frames with
45126 ** frame numbers greater than pWal->hdr.mxFrame.
45128 nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
45129 memset((void *)&aPgno[iLimit+1], 0, nByte);
45131 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
45132 /* Verify that the every entry in the mapping region is still reachable
45133 ** via the hash table even after the cleanup.
45135 if( iLimit ){
45136 int i; /* Loop counter */
45137 int iKey; /* Hash key */
45138 for(i=1; i<=iLimit; i++){
45139 for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
45140 if( aHash[iKey]==i ) break;
45142 assert( aHash[iKey]==i );
45145 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
45150 ** Set an entry in the wal-index that will map database page number
45151 ** pPage into WAL frame iFrame.
45153 static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
45154 int rc; /* Return code */
45155 u32 iZero = 0; /* One less than frame number of aPgno[1] */
45156 volatile u32 *aPgno = 0; /* Page number array */
45157 volatile ht_slot *aHash = 0; /* Hash table */
45159 rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
45161 /* Assuming the wal-index file was successfully mapped, populate the
45162 ** page number array and hash table entry.
45164 if( rc==SQLITE_OK ){
45165 int iKey; /* Hash table key */
45166 int idx; /* Value to write to hash-table slot */
45167 int nCollide; /* Number of hash collisions */
45169 idx = iFrame - iZero;
45170 assert( idx <= HASHTABLE_NSLOT/2 + 1 );
45172 /* If this is the first entry to be added to this hash-table, zero the
45173 ** entire hash table and aPgno[] array before proceding.
45175 if( idx==1 ){
45176 int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
45177 memset((void*)&aPgno[1], 0, nByte);
45180 /* If the entry in aPgno[] is already set, then the previous writer
45181 ** must have exited unexpectedly in the middle of a transaction (after
45182 ** writing one or more dirty pages to the WAL to free up memory).
45183 ** Remove the remnants of that writers uncommitted transaction from
45184 ** the hash-table before writing any new entries.
45186 if( aPgno[idx] ){
45187 walCleanupHash(pWal);
45188 assert( !aPgno[idx] );
45191 /* Write the aPgno[] array entry and the hash-table slot. */
45192 nCollide = idx;
45193 for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
45194 if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
45196 aPgno[idx] = iPage;
45197 aHash[iKey] = (ht_slot)idx;
45199 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
45200 /* Verify that the number of entries in the hash table exactly equals
45201 ** the number of entries in the mapping region.
45204 int i; /* Loop counter */
45205 int nEntry = 0; /* Number of entries in the hash table */
45206 for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
45207 assert( nEntry==idx );
45210 /* Verify that the every entry in the mapping region is reachable
45211 ** via the hash table. This turns out to be a really, really expensive
45212 ** thing to check, so only do this occasionally - not on every
45213 ** iteration.
45215 if( (idx&0x3ff)==0 ){
45216 int i; /* Loop counter */
45217 for(i=1; i<=idx; i++){
45218 for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
45219 if( aHash[iKey]==i ) break;
45221 assert( aHash[iKey]==i );
45224 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
45228 return rc;
45233 ** Recover the wal-index by reading the write-ahead log file.
45235 ** This routine first tries to establish an exclusive lock on the
45236 ** wal-index to prevent other threads/processes from doing anything
45237 ** with the WAL or wal-index while recovery is running. The
45238 ** WAL_RECOVER_LOCK is also held so that other threads will know
45239 ** that this thread is running recovery. If unable to establish
45240 ** the necessary locks, this routine returns SQLITE_BUSY.
45242 static int walIndexRecover(Wal *pWal){
45243 int rc; /* Return Code */
45244 i64 nSize; /* Size of log file */
45245 u32 aFrameCksum[2] = {0, 0};
45246 int iLock; /* Lock offset to lock for checkpoint */
45247 int nLock; /* Number of locks to hold */
45249 /* Obtain an exclusive lock on all byte in the locking range not already
45250 ** locked by the caller. The caller is guaranteed to have locked the
45251 ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
45252 ** If successful, the same bytes that are locked here are unlocked before
45253 ** this function returns.
45255 assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
45256 assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
45257 assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
45258 assert( pWal->writeLock );
45259 iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
45260 nLock = SQLITE_SHM_NLOCK - iLock;
45261 rc = walLockExclusive(pWal, iLock, nLock);
45262 if( rc ){
45263 return rc;
45265 WALTRACE(("WAL%p: recovery begin...\n", pWal));
45267 memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
45269 rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
45270 if( rc!=SQLITE_OK ){
45271 goto recovery_error;
45274 if( nSize>WAL_HDRSIZE ){
45275 u8 aBuf[WAL_HDRSIZE]; /* Buffer to load WAL header into */
45276 u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */
45277 int szFrame; /* Number of bytes in buffer aFrame[] */
45278 u8 *aData; /* Pointer to data part of aFrame buffer */
45279 int iFrame; /* Index of last frame read */
45280 i64 iOffset; /* Next offset to read from log file */
45281 int szPage; /* Page size according to the log */
45282 u32 magic; /* Magic value read from WAL header */
45283 u32 version; /* Magic value read from WAL header */
45285 /* Read in the WAL header. */
45286 rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
45287 if( rc!=SQLITE_OK ){
45288 goto recovery_error;
45291 /* If the database page size is not a power of two, or is greater than
45292 ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
45293 ** data. Similarly, if the 'magic' value is invalid, ignore the whole
45294 ** WAL file.
45296 magic = sqlite3Get4byte(&aBuf[0]);
45297 szPage = sqlite3Get4byte(&aBuf[8]);
45298 if( (magic&0xFFFFFFFE)!=WAL_MAGIC
45299 || szPage&(szPage-1)
45300 || szPage>SQLITE_MAX_PAGE_SIZE
45301 || szPage<512
45303 goto finished;
45305 pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
45306 pWal->szPage = szPage;
45307 pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
45308 memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
45310 /* Verify that the WAL header checksum is correct */
45311 walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
45312 aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
45314 if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
45315 || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
45317 goto finished;
45320 /* Verify that the version number on the WAL format is one that
45321 ** are able to understand */
45322 version = sqlite3Get4byte(&aBuf[4]);
45323 if( version!=WAL_MAX_VERSION ){
45324 rc = SQLITE_CANTOPEN_BKPT;
45325 goto finished;
45328 /* Malloc a buffer to read frames into. */
45329 szFrame = szPage + WAL_FRAME_HDRSIZE;
45330 aFrame = (u8 *)sqlite3_malloc(szFrame);
45331 if( !aFrame ){
45332 rc = SQLITE_NOMEM;
45333 goto recovery_error;
45335 aData = &aFrame[WAL_FRAME_HDRSIZE];
45337 /* Read all frames from the log file. */
45338 iFrame = 0;
45339 for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
45340 u32 pgno; /* Database page number for frame */
45341 u32 nTruncate; /* dbsize field from frame header */
45342 int isValid; /* True if this frame is valid */
45344 /* Read and decode the next log frame. */
45345 rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
45346 if( rc!=SQLITE_OK ) break;
45347 isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
45348 if( !isValid ) break;
45349 rc = walIndexAppend(pWal, ++iFrame, pgno);
45350 if( rc!=SQLITE_OK ) break;
45352 /* If nTruncate is non-zero, this is a commit record. */
45353 if( nTruncate ){
45354 pWal->hdr.mxFrame = iFrame;
45355 pWal->hdr.nPage = nTruncate;
45356 pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
45357 testcase( szPage<=32768 );
45358 testcase( szPage>=65536 );
45359 aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
45360 aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
45364 sqlite3_free(aFrame);
45367 finished:
45368 if( rc==SQLITE_OK ){
45369 volatile WalCkptInfo *pInfo;
45370 int i;
45371 pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
45372 pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
45373 walIndexWriteHdr(pWal);
45375 /* Reset the checkpoint-header. This is safe because this thread is
45376 ** currently holding locks that exclude all other readers, writers and
45377 ** checkpointers.
45379 pInfo = walCkptInfo(pWal);
45380 pInfo->nBackfill = 0;
45381 pInfo->aReadMark[0] = 0;
45382 for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
45384 /* If more than one frame was recovered from the log file, report an
45385 ** event via sqlite3_log(). This is to help with identifying performance
45386 ** problems caused by applications routinely shutting down without
45387 ** checkpointing the log file.
45389 if( pWal->hdr.nPage ){
45390 sqlite3_log(SQLITE_OK, "Recovered %d frames from WAL file %s",
45391 pWal->hdr.nPage, pWal->zWalName
45396 recovery_error:
45397 WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
45398 walUnlockExclusive(pWal, iLock, nLock);
45399 return rc;
45403 ** Close an open wal-index.
45405 static void walIndexClose(Wal *pWal, int isDelete){
45406 if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
45407 int i;
45408 for(i=0; i<pWal->nWiData; i++){
45409 sqlite3_free((void *)pWal->apWiData[i]);
45410 pWal->apWiData[i] = 0;
45412 }else{
45413 sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
45418 ** Open a connection to the WAL file zWalName. The database file must
45419 ** already be opened on connection pDbFd. The buffer that zWalName points
45420 ** to must remain valid for the lifetime of the returned Wal* handle.
45422 ** A SHARED lock should be held on the database file when this function
45423 ** is called. The purpose of this SHARED lock is to prevent any other
45424 ** client from unlinking the WAL or wal-index file. If another process
45425 ** were to do this just after this client opened one of these files, the
45426 ** system would be badly broken.
45428 ** If the log file is successfully opened, SQLITE_OK is returned and
45429 ** *ppWal is set to point to a new WAL handle. If an error occurs,
45430 ** an SQLite error code is returned and *ppWal is left unmodified.
45432 SQLITE_PRIVATE int sqlite3WalOpen(
45433 sqlite3_vfs *pVfs, /* vfs module to open wal and wal-index */
45434 sqlite3_file *pDbFd, /* The open database file */
45435 const char *zWalName, /* Name of the WAL file */
45436 int bNoShm, /* True to run in heap-memory mode */
45437 i64 mxWalSize, /* Truncate WAL to this size on reset */
45438 Wal **ppWal /* OUT: Allocated Wal handle */
45440 int rc; /* Return Code */
45441 Wal *pRet; /* Object to allocate and return */
45442 int flags; /* Flags passed to OsOpen() */
45444 assert( zWalName && zWalName[0] );
45445 assert( pDbFd );
45447 /* In the amalgamation, the os_unix.c and os_win.c source files come before
45448 ** this source file. Verify that the #defines of the locking byte offsets
45449 ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
45451 #ifdef WIN_SHM_BASE
45452 assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
45453 #endif
45454 #ifdef UNIX_SHM_BASE
45455 assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
45456 #endif
45459 /* Allocate an instance of struct Wal to return. */
45460 *ppWal = 0;
45461 pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
45462 if( !pRet ){
45463 return SQLITE_NOMEM;
45466 pRet->pVfs = pVfs;
45467 pRet->pWalFd = (sqlite3_file *)&pRet[1];
45468 pRet->pDbFd = pDbFd;
45469 pRet->readLock = -1;
45470 pRet->mxWalSize = mxWalSize;
45471 pRet->zWalName = zWalName;
45472 pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
45474 /* Open file handle on the write-ahead log file. */
45475 flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
45476 rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
45477 if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
45478 pRet->readOnly = WAL_RDONLY;
45481 if( rc!=SQLITE_OK ){
45482 walIndexClose(pRet, 0);
45483 sqlite3OsClose(pRet->pWalFd);
45484 sqlite3_free(pRet);
45485 }else{
45486 *ppWal = pRet;
45487 WALTRACE(("WAL%d: opened\n", pRet));
45489 return rc;
45493 ** Change the size to which the WAL file is trucated on each reset.
45495 SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
45496 if( pWal ) pWal->mxWalSize = iLimit;
45500 ** Find the smallest page number out of all pages held in the WAL that
45501 ** has not been returned by any prior invocation of this method on the
45502 ** same WalIterator object. Write into *piFrame the frame index where
45503 ** that page was last written into the WAL. Write into *piPage the page
45504 ** number.
45506 ** Return 0 on success. If there are no pages in the WAL with a page
45507 ** number larger than *piPage, then return 1.
45509 static int walIteratorNext(
45510 WalIterator *p, /* Iterator */
45511 u32 *piPage, /* OUT: The page number of the next page */
45512 u32 *piFrame /* OUT: Wal frame index of next page */
45514 u32 iMin; /* Result pgno must be greater than iMin */
45515 u32 iRet = 0xFFFFFFFF; /* 0xffffffff is never a valid page number */
45516 int i; /* For looping through segments */
45518 iMin = p->iPrior;
45519 assert( iMin<0xffffffff );
45520 for(i=p->nSegment-1; i>=0; i--){
45521 struct WalSegment *pSegment = &p->aSegment[i];
45522 while( pSegment->iNext<pSegment->nEntry ){
45523 u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
45524 if( iPg>iMin ){
45525 if( iPg<iRet ){
45526 iRet = iPg;
45527 *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
45529 break;
45531 pSegment->iNext++;
45535 *piPage = p->iPrior = iRet;
45536 return (iRet==0xFFFFFFFF);
45540 ** This function merges two sorted lists into a single sorted list.
45542 ** aLeft[] and aRight[] are arrays of indices. The sort key is
45543 ** aContent[aLeft[]] and aContent[aRight[]]. Upon entry, the following
45544 ** is guaranteed for all J<K:
45546 ** aContent[aLeft[J]] < aContent[aLeft[K]]
45547 ** aContent[aRight[J]] < aContent[aRight[K]]
45549 ** This routine overwrites aRight[] with a new (probably longer) sequence
45550 ** of indices such that the aRight[] contains every index that appears in
45551 ** either aLeft[] or the old aRight[] and such that the second condition
45552 ** above is still met.
45554 ** The aContent[aLeft[X]] values will be unique for all X. And the
45555 ** aContent[aRight[X]] values will be unique too. But there might be
45556 ** one or more combinations of X and Y such that
45558 ** aLeft[X]!=aRight[Y] && aContent[aLeft[X]] == aContent[aRight[Y]]
45560 ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
45562 static void walMerge(
45563 const u32 *aContent, /* Pages in wal - keys for the sort */
45564 ht_slot *aLeft, /* IN: Left hand input list */
45565 int nLeft, /* IN: Elements in array *paLeft */
45566 ht_slot **paRight, /* IN/OUT: Right hand input list */
45567 int *pnRight, /* IN/OUT: Elements in *paRight */
45568 ht_slot *aTmp /* Temporary buffer */
45570 int iLeft = 0; /* Current index in aLeft */
45571 int iRight = 0; /* Current index in aRight */
45572 int iOut = 0; /* Current index in output buffer */
45573 int nRight = *pnRight;
45574 ht_slot *aRight = *paRight;
45576 assert( nLeft>0 && nRight>0 );
45577 while( iRight<nRight || iLeft<nLeft ){
45578 ht_slot logpage;
45579 Pgno dbpage;
45581 if( (iLeft<nLeft)
45582 && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
45584 logpage = aLeft[iLeft++];
45585 }else{
45586 logpage = aRight[iRight++];
45588 dbpage = aContent[logpage];
45590 aTmp[iOut++] = logpage;
45591 if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
45593 assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
45594 assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
45597 *paRight = aLeft;
45598 *pnRight = iOut;
45599 memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
45603 ** Sort the elements in list aList using aContent[] as the sort key.
45604 ** Remove elements with duplicate keys, preferring to keep the
45605 ** larger aList[] values.
45607 ** The aList[] entries are indices into aContent[]. The values in
45608 ** aList[] are to be sorted so that for all J<K:
45610 ** aContent[aList[J]] < aContent[aList[K]]
45612 ** For any X and Y such that
45614 ** aContent[aList[X]] == aContent[aList[Y]]
45616 ** Keep the larger of the two values aList[X] and aList[Y] and discard
45617 ** the smaller.
45619 static void walMergesort(
45620 const u32 *aContent, /* Pages in wal */
45621 ht_slot *aBuffer, /* Buffer of at least *pnList items to use */
45622 ht_slot *aList, /* IN/OUT: List to sort */
45623 int *pnList /* IN/OUT: Number of elements in aList[] */
45625 struct Sublist {
45626 int nList; /* Number of elements in aList */
45627 ht_slot *aList; /* Pointer to sub-list content */
45630 const int nList = *pnList; /* Size of input list */
45631 int nMerge = 0; /* Number of elements in list aMerge */
45632 ht_slot *aMerge = 0; /* List to be merged */
45633 int iList; /* Index into input list */
45634 int iSub = 0; /* Index into aSub array */
45635 struct Sublist aSub[13]; /* Array of sub-lists */
45637 memset(aSub, 0, sizeof(aSub));
45638 assert( nList<=HASHTABLE_NPAGE && nList>0 );
45639 assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
45641 for(iList=0; iList<nList; iList++){
45642 nMerge = 1;
45643 aMerge = &aList[iList];
45644 for(iSub=0; iList & (1<<iSub); iSub++){
45645 struct Sublist *p = &aSub[iSub];
45646 assert( p->aList && p->nList<=(1<<iSub) );
45647 assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
45648 walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
45650 aSub[iSub].aList = aMerge;
45651 aSub[iSub].nList = nMerge;
45654 for(iSub++; iSub<ArraySize(aSub); iSub++){
45655 if( nList & (1<<iSub) ){
45656 struct Sublist *p = &aSub[iSub];
45657 assert( p->nList<=(1<<iSub) );
45658 assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
45659 walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
45662 assert( aMerge==aList );
45663 *pnList = nMerge;
45665 #ifdef SQLITE_DEBUG
45667 int i;
45668 for(i=1; i<*pnList; i++){
45669 assert( aContent[aList[i]] > aContent[aList[i-1]] );
45672 #endif
45676 ** Free an iterator allocated by walIteratorInit().
45678 static void walIteratorFree(WalIterator *p){
45679 sqlite3ScratchFree(p);
45683 ** Construct a WalInterator object that can be used to loop over all
45684 ** pages in the WAL in ascending order. The caller must hold the checkpoint
45685 ** lock.
45687 ** On success, make *pp point to the newly allocated WalInterator object
45688 ** return SQLITE_OK. Otherwise, return an error code. If this routine
45689 ** returns an error, the value of *pp is undefined.
45691 ** The calling routine should invoke walIteratorFree() to destroy the
45692 ** WalIterator object when it has finished with it.
45694 static int walIteratorInit(Wal *pWal, WalIterator **pp){
45695 WalIterator *p; /* Return value */
45696 int nSegment; /* Number of segments to merge */
45697 u32 iLast; /* Last frame in log */
45698 int nByte; /* Number of bytes to allocate */
45699 int i; /* Iterator variable */
45700 ht_slot *aTmp; /* Temp space used by merge-sort */
45701 int rc = SQLITE_OK; /* Return Code */
45703 /* This routine only runs while holding the checkpoint lock. And
45704 ** it only runs if there is actually content in the log (mxFrame>0).
45706 assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
45707 iLast = pWal->hdr.mxFrame;
45709 /* Allocate space for the WalIterator object. */
45710 nSegment = walFramePage(iLast) + 1;
45711 nByte = sizeof(WalIterator)
45712 + (nSegment-1)*sizeof(struct WalSegment)
45713 + iLast*sizeof(ht_slot);
45714 p = (WalIterator *)sqlite3ScratchMalloc(nByte);
45715 if( !p ){
45716 return SQLITE_NOMEM;
45718 memset(p, 0, nByte);
45719 p->nSegment = nSegment;
45721 /* Allocate temporary space used by the merge-sort routine. This block
45722 ** of memory will be freed before this function returns.
45724 aTmp = (ht_slot *)sqlite3ScratchMalloc(
45725 sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
45727 if( !aTmp ){
45728 rc = SQLITE_NOMEM;
45731 for(i=0; rc==SQLITE_OK && i<nSegment; i++){
45732 volatile ht_slot *aHash;
45733 u32 iZero;
45734 volatile u32 *aPgno;
45736 rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
45737 if( rc==SQLITE_OK ){
45738 int j; /* Counter variable */
45739 int nEntry; /* Number of entries in this segment */
45740 ht_slot *aIndex; /* Sorted index for this segment */
45742 aPgno++;
45743 if( (i+1)==nSegment ){
45744 nEntry = (int)(iLast - iZero);
45745 }else{
45746 nEntry = (int)((u32*)aHash - (u32*)aPgno);
45748 aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
45749 iZero++;
45751 for(j=0; j<nEntry; j++){
45752 aIndex[j] = (ht_slot)j;
45754 walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
45755 p->aSegment[i].iZero = iZero;
45756 p->aSegment[i].nEntry = nEntry;
45757 p->aSegment[i].aIndex = aIndex;
45758 p->aSegment[i].aPgno = (u32 *)aPgno;
45761 sqlite3ScratchFree(aTmp);
45763 if( rc!=SQLITE_OK ){
45764 walIteratorFree(p);
45766 *pp = p;
45767 return rc;
45771 ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
45772 ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
45773 ** busy-handler function. Invoke it and retry the lock until either the
45774 ** lock is successfully obtained or the busy-handler returns 0.
45776 static int walBusyLock(
45777 Wal *pWal, /* WAL connection */
45778 int (*xBusy)(void*), /* Function to call when busy */
45779 void *pBusyArg, /* Context argument for xBusyHandler */
45780 int lockIdx, /* Offset of first byte to lock */
45781 int n /* Number of bytes to lock */
45783 int rc;
45784 do {
45785 rc = walLockExclusive(pWal, lockIdx, n);
45786 }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
45787 return rc;
45791 ** The cache of the wal-index header must be valid to call this function.
45792 ** Return the page-size in bytes used by the database.
45794 static int walPagesize(Wal *pWal){
45795 return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
45799 ** Copy as much content as we can from the WAL back into the database file
45800 ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
45802 ** The amount of information copies from WAL to database might be limited
45803 ** by active readers. This routine will never overwrite a database page
45804 ** that a concurrent reader might be using.
45806 ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
45807 ** SQLite is in WAL-mode in synchronous=NORMAL. That means that if
45808 ** checkpoints are always run by a background thread or background
45809 ** process, foreground threads will never block on a lengthy fsync call.
45811 ** Fsync is called on the WAL before writing content out of the WAL and
45812 ** into the database. This ensures that if the new content is persistent
45813 ** in the WAL and can be recovered following a power-loss or hard reset.
45815 ** Fsync is also called on the database file if (and only if) the entire
45816 ** WAL content is copied into the database file. This second fsync makes
45817 ** it safe to delete the WAL since the new content will persist in the
45818 ** database file.
45820 ** This routine uses and updates the nBackfill field of the wal-index header.
45821 ** This is the only routine tha will increase the value of nBackfill.
45822 ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
45823 ** its value.)
45825 ** The caller must be holding sufficient locks to ensure that no other
45826 ** checkpoint is running (in any other thread or process) at the same
45827 ** time.
45829 static int walCheckpoint(
45830 Wal *pWal, /* Wal connection */
45831 int eMode, /* One of PASSIVE, FULL or RESTART */
45832 int (*xBusyCall)(void*), /* Function to call when busy */
45833 void *pBusyArg, /* Context argument for xBusyHandler */
45834 int sync_flags, /* Flags for OsSync() (or 0) */
45835 u8 *zBuf /* Temporary buffer to use */
45837 int rc; /* Return code */
45838 int szPage; /* Database page-size */
45839 WalIterator *pIter = 0; /* Wal iterator context */
45840 u32 iDbpage = 0; /* Next database page to write */
45841 u32 iFrame = 0; /* Wal frame containing data for iDbpage */
45842 u32 mxSafeFrame; /* Max frame that can be backfilled */
45843 u32 mxPage; /* Max database page to write */
45844 int i; /* Loop counter */
45845 volatile WalCkptInfo *pInfo; /* The checkpoint status information */
45846 int (*xBusy)(void*) = 0; /* Function to call when waiting for locks */
45848 szPage = walPagesize(pWal);
45849 testcase( szPage<=32768 );
45850 testcase( szPage>=65536 );
45851 pInfo = walCkptInfo(pWal);
45852 if( pInfo->nBackfill>=pWal->hdr.mxFrame ) return SQLITE_OK;
45854 /* Allocate the iterator */
45855 rc = walIteratorInit(pWal, &pIter);
45856 if( rc!=SQLITE_OK ){
45857 return rc;
45859 assert( pIter );
45861 if( eMode!=SQLITE_CHECKPOINT_PASSIVE ) xBusy = xBusyCall;
45863 /* Compute in mxSafeFrame the index of the last frame of the WAL that is
45864 ** safe to write into the database. Frames beyond mxSafeFrame might
45865 ** overwrite database pages that are in use by active readers and thus
45866 ** cannot be backfilled from the WAL.
45868 mxSafeFrame = pWal->hdr.mxFrame;
45869 mxPage = pWal->hdr.nPage;
45870 for(i=1; i<WAL_NREADER; i++){
45871 u32 y = pInfo->aReadMark[i];
45872 if( mxSafeFrame>y ){
45873 assert( y<=pWal->hdr.mxFrame );
45874 rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
45875 if( rc==SQLITE_OK ){
45876 pInfo->aReadMark[i] = READMARK_NOT_USED;
45877 walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
45878 }else if( rc==SQLITE_BUSY ){
45879 mxSafeFrame = y;
45880 xBusy = 0;
45881 }else{
45882 goto walcheckpoint_out;
45887 if( pInfo->nBackfill<mxSafeFrame
45888 && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0), 1))==SQLITE_OK
45890 i64 nSize; /* Current size of database file */
45891 u32 nBackfill = pInfo->nBackfill;
45893 /* Sync the WAL to disk */
45894 if( sync_flags ){
45895 rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
45898 /* If the database file may grow as a result of this checkpoint, hint
45899 ** about the eventual size of the db file to the VFS layer.
45901 if( rc==SQLITE_OK ){
45902 i64 nReq = ((i64)mxPage * szPage);
45903 rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
45904 if( rc==SQLITE_OK && nSize<nReq ){
45905 sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
45909 /* Iterate through the contents of the WAL, copying data to the db file. */
45910 while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
45911 i64 iOffset;
45912 assert( walFramePgno(pWal, iFrame)==iDbpage );
45913 if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ) continue;
45914 iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
45915 /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
45916 rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
45917 if( rc!=SQLITE_OK ) break;
45918 iOffset = (iDbpage-1)*(i64)szPage;
45919 testcase( IS_BIG_INT(iOffset) );
45920 rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
45921 if( rc!=SQLITE_OK ) break;
45924 /* If work was actually accomplished... */
45925 if( rc==SQLITE_OK ){
45926 if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
45927 i64 szDb = pWal->hdr.nPage*(i64)szPage;
45928 testcase( IS_BIG_INT(szDb) );
45929 rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
45930 if( rc==SQLITE_OK && sync_flags ){
45931 rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
45934 if( rc==SQLITE_OK ){
45935 pInfo->nBackfill = mxSafeFrame;
45939 /* Release the reader lock held while backfilling */
45940 walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
45943 if( rc==SQLITE_BUSY ){
45944 /* Reset the return code so as not to report a checkpoint failure
45945 ** just because there are active readers. */
45946 rc = SQLITE_OK;
45949 /* If this is an SQLITE_CHECKPOINT_RESTART operation, and the entire wal
45950 ** file has been copied into the database file, then block until all
45951 ** readers have finished using the wal file. This ensures that the next
45952 ** process to write to the database restarts the wal file.
45954 if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
45955 assert( pWal->writeLock );
45956 if( pInfo->nBackfill<pWal->hdr.mxFrame ){
45957 rc = SQLITE_BUSY;
45958 }else if( eMode==SQLITE_CHECKPOINT_RESTART ){
45959 assert( mxSafeFrame==pWal->hdr.mxFrame );
45960 rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
45961 if( rc==SQLITE_OK ){
45962 walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
45967 walcheckpoint_out:
45968 walIteratorFree(pIter);
45969 return rc;
45973 ** Close a connection to a log file.
45975 SQLITE_PRIVATE int sqlite3WalClose(
45976 Wal *pWal, /* Wal to close */
45977 int sync_flags, /* Flags to pass to OsSync() (or 0) */
45978 int nBuf,
45979 u8 *zBuf /* Buffer of at least nBuf bytes */
45981 int rc = SQLITE_OK;
45982 if( pWal ){
45983 int isDelete = 0; /* True to unlink wal and wal-index files */
45985 /* If an EXCLUSIVE lock can be obtained on the database file (using the
45986 ** ordinary, rollback-mode locking methods, this guarantees that the
45987 ** connection associated with this log file is the only connection to
45988 ** the database. In this case checkpoint the database and unlink both
45989 ** the wal and wal-index files.
45991 ** The EXCLUSIVE lock is not released before returning.
45993 rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
45994 if( rc==SQLITE_OK ){
45995 int bPersistWal = -1;
45996 if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
45997 pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
45999 rc = sqlite3WalCheckpoint(
46000 pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
46002 sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersistWal);
46003 if( rc==SQLITE_OK && bPersistWal!=1 ){
46004 isDelete = 1;
46008 walIndexClose(pWal, isDelete);
46009 sqlite3OsClose(pWal->pWalFd);
46010 if( isDelete ){
46011 sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
46013 WALTRACE(("WAL%p: closed\n", pWal));
46014 sqlite3_free((void *)pWal->apWiData);
46015 sqlite3_free(pWal);
46017 return rc;
46021 ** Try to read the wal-index header. Return 0 on success and 1 if
46022 ** there is a problem.
46024 ** The wal-index is in shared memory. Another thread or process might
46025 ** be writing the header at the same time this procedure is trying to
46026 ** read it, which might result in inconsistency. A dirty read is detected
46027 ** by verifying that both copies of the header are the same and also by
46028 ** a checksum on the header.
46030 ** If and only if the read is consistent and the header is different from
46031 ** pWal->hdr, then pWal->hdr is updated to the content of the new header
46032 ** and *pChanged is set to 1.
46034 ** If the checksum cannot be verified return non-zero. If the header
46035 ** is read successfully and the checksum verified, return zero.
46037 static int walIndexTryHdr(Wal *pWal, int *pChanged){
46038 u32 aCksum[2]; /* Checksum on the header content */
46039 WalIndexHdr h1, h2; /* Two copies of the header content */
46040 WalIndexHdr volatile *aHdr; /* Header in shared memory */
46042 /* The first page of the wal-index must be mapped at this point. */
46043 assert( pWal->nWiData>0 && pWal->apWiData[0] );
46045 /* Read the header. This might happen concurrently with a write to the
46046 ** same area of shared memory on a different CPU in a SMP,
46047 ** meaning it is possible that an inconsistent snapshot is read
46048 ** from the file. If this happens, return non-zero.
46050 ** There are two copies of the header at the beginning of the wal-index.
46051 ** When reading, read [0] first then [1]. Writes are in the reverse order.
46052 ** Memory barriers are used to prevent the compiler or the hardware from
46053 ** reordering the reads and writes.
46055 aHdr = walIndexHdr(pWal);
46056 memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
46057 walShmBarrier(pWal);
46058 memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
46060 if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
46061 return 1; /* Dirty read */
46063 if( h1.isInit==0 ){
46064 return 1; /* Malformed header - probably all zeros */
46066 walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
46067 if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
46068 return 1; /* Checksum does not match */
46071 if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
46072 *pChanged = 1;
46073 memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
46074 pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
46075 testcase( pWal->szPage<=32768 );
46076 testcase( pWal->szPage>=65536 );
46079 /* The header was successfully read. Return zero. */
46080 return 0;
46084 ** Read the wal-index header from the wal-index and into pWal->hdr.
46085 ** If the wal-header appears to be corrupt, try to reconstruct the
46086 ** wal-index from the WAL before returning.
46088 ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
46089 ** changed by this opertion. If pWal->hdr is unchanged, set *pChanged
46090 ** to 0.
46092 ** If the wal-index header is successfully read, return SQLITE_OK.
46093 ** Otherwise an SQLite error code.
46095 static int walIndexReadHdr(Wal *pWal, int *pChanged){
46096 int rc; /* Return code */
46097 int badHdr; /* True if a header read failed */
46098 volatile u32 *page0; /* Chunk of wal-index containing header */
46100 /* Ensure that page 0 of the wal-index (the page that contains the
46101 ** wal-index header) is mapped. Return early if an error occurs here.
46103 assert( pChanged );
46104 rc = walIndexPage(pWal, 0, &page0);
46105 if( rc!=SQLITE_OK ){
46106 return rc;
46108 assert( page0 || pWal->writeLock==0 );
46110 /* If the first page of the wal-index has been mapped, try to read the
46111 ** wal-index header immediately, without holding any lock. This usually
46112 ** works, but may fail if the wal-index header is corrupt or currently
46113 ** being modified by another thread or process.
46115 badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
46117 /* If the first attempt failed, it might have been due to a race
46118 ** with a writer. So get a WRITE lock and try again.
46120 assert( badHdr==0 || pWal->writeLock==0 );
46121 if( badHdr ){
46122 if( pWal->readOnly & WAL_SHM_RDONLY ){
46123 if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
46124 walUnlockShared(pWal, WAL_WRITE_LOCK);
46125 rc = SQLITE_READONLY_RECOVERY;
46127 }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
46128 pWal->writeLock = 1;
46129 if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
46130 badHdr = walIndexTryHdr(pWal, pChanged);
46131 if( badHdr ){
46132 /* If the wal-index header is still malformed even while holding
46133 ** a WRITE lock, it can only mean that the header is corrupted and
46134 ** needs to be reconstructed. So run recovery to do exactly that.
46136 rc = walIndexRecover(pWal);
46137 *pChanged = 1;
46140 pWal->writeLock = 0;
46141 walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
46145 /* If the header is read successfully, check the version number to make
46146 ** sure the wal-index was not constructed with some future format that
46147 ** this version of SQLite cannot understand.
46149 if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
46150 rc = SQLITE_CANTOPEN_BKPT;
46153 return rc;
46157 ** This is the value that walTryBeginRead returns when it needs to
46158 ** be retried.
46160 #define WAL_RETRY (-1)
46163 ** Attempt to start a read transaction. This might fail due to a race or
46164 ** other transient condition. When that happens, it returns WAL_RETRY to
46165 ** indicate to the caller that it is safe to retry immediately.
46167 ** On success return SQLITE_OK. On a permanent failure (such an
46168 ** I/O error or an SQLITE_BUSY because another process is running
46169 ** recovery) return a positive error code.
46171 ** The useWal parameter is true to force the use of the WAL and disable
46172 ** the case where the WAL is bypassed because it has been completely
46173 ** checkpointed. If useWal==0 then this routine calls walIndexReadHdr()
46174 ** to make a copy of the wal-index header into pWal->hdr. If the
46175 ** wal-index header has changed, *pChanged is set to 1 (as an indication
46176 ** to the caller that the local paget cache is obsolete and needs to be
46177 ** flushed.) When useWal==1, the wal-index header is assumed to already
46178 ** be loaded and the pChanged parameter is unused.
46180 ** The caller must set the cnt parameter to the number of prior calls to
46181 ** this routine during the current read attempt that returned WAL_RETRY.
46182 ** This routine will start taking more aggressive measures to clear the
46183 ** race conditions after multiple WAL_RETRY returns, and after an excessive
46184 ** number of errors will ultimately return SQLITE_PROTOCOL. The
46185 ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
46186 ** and is not honoring the locking protocol. There is a vanishingly small
46187 ** chance that SQLITE_PROTOCOL could be returned because of a run of really
46188 ** bad luck when there is lots of contention for the wal-index, but that
46189 ** possibility is so small that it can be safely neglected, we believe.
46191 ** On success, this routine obtains a read lock on
46192 ** WAL_READ_LOCK(pWal->readLock). The pWal->readLock integer is
46193 ** in the range 0 <= pWal->readLock < WAL_NREADER. If pWal->readLock==(-1)
46194 ** that means the Wal does not hold any read lock. The reader must not
46195 ** access any database page that is modified by a WAL frame up to and
46196 ** including frame number aReadMark[pWal->readLock]. The reader will
46197 ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
46198 ** Or if pWal->readLock==0, then the reader will ignore the WAL
46199 ** completely and get all content directly from the database file.
46200 ** If the useWal parameter is 1 then the WAL will never be ignored and
46201 ** this routine will always set pWal->readLock>0 on success.
46202 ** When the read transaction is completed, the caller must release the
46203 ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
46205 ** This routine uses the nBackfill and aReadMark[] fields of the header
46206 ** to select a particular WAL_READ_LOCK() that strives to let the
46207 ** checkpoint process do as much work as possible. This routine might
46208 ** update values of the aReadMark[] array in the header, but if it does
46209 ** so it takes care to hold an exclusive lock on the corresponding
46210 ** WAL_READ_LOCK() while changing values.
46212 static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
46213 volatile WalCkptInfo *pInfo; /* Checkpoint information in wal-index */
46214 u32 mxReadMark; /* Largest aReadMark[] value */
46215 int mxI; /* Index of largest aReadMark[] value */
46216 int i; /* Loop counter */
46217 int rc = SQLITE_OK; /* Return code */
46219 assert( pWal->readLock<0 ); /* Not currently locked */
46221 /* Take steps to avoid spinning forever if there is a protocol error.
46223 ** Circumstances that cause a RETRY should only last for the briefest
46224 ** instances of time. No I/O or other system calls are done while the
46225 ** locks are held, so the locks should not be held for very long. But
46226 ** if we are unlucky, another process that is holding a lock might get
46227 ** paged out or take a page-fault that is time-consuming to resolve,
46228 ** during the few nanoseconds that it is holding the lock. In that case,
46229 ** it might take longer than normal for the lock to free.
46231 ** After 5 RETRYs, we begin calling sqlite3OsSleep(). The first few
46232 ** calls to sqlite3OsSleep() have a delay of 1 microsecond. Really this
46233 ** is more of a scheduler yield than an actual delay. But on the 10th
46234 ** an subsequent retries, the delays start becoming longer and longer,
46235 ** so that on the 100th (and last) RETRY we delay for 21 milliseconds.
46236 ** The total delay time before giving up is less than 1 second.
46238 if( cnt>5 ){
46239 int nDelay = 1; /* Pause time in microseconds */
46240 if( cnt>100 ){
46241 VVA_ONLY( pWal->lockError = 1; )
46242 return SQLITE_PROTOCOL;
46244 if( cnt>=10 ) nDelay = (cnt-9)*238; /* Max delay 21ms. Total delay 996ms */
46245 sqlite3OsSleep(pWal->pVfs, nDelay);
46248 if( !useWal ){
46249 rc = walIndexReadHdr(pWal, pChanged);
46250 if( rc==SQLITE_BUSY ){
46251 /* If there is not a recovery running in another thread or process
46252 ** then convert BUSY errors to WAL_RETRY. If recovery is known to
46253 ** be running, convert BUSY to BUSY_RECOVERY. There is a race here
46254 ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
46255 ** would be technically correct. But the race is benign since with
46256 ** WAL_RETRY this routine will be called again and will probably be
46257 ** right on the second iteration.
46259 if( pWal->apWiData[0]==0 ){
46260 /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
46261 ** We assume this is a transient condition, so return WAL_RETRY. The
46262 ** xShmMap() implementation used by the default unix and win32 VFS
46263 ** modules may return SQLITE_BUSY due to a race condition in the
46264 ** code that determines whether or not the shared-memory region
46265 ** must be zeroed before the requested page is returned.
46267 rc = WAL_RETRY;
46268 }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
46269 walUnlockShared(pWal, WAL_RECOVER_LOCK);
46270 rc = WAL_RETRY;
46271 }else if( rc==SQLITE_BUSY ){
46272 rc = SQLITE_BUSY_RECOVERY;
46275 if( rc!=SQLITE_OK ){
46276 return rc;
46280 pInfo = walCkptInfo(pWal);
46281 if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
46282 /* The WAL has been completely backfilled (or it is empty).
46283 ** and can be safely ignored.
46285 rc = walLockShared(pWal, WAL_READ_LOCK(0));
46286 walShmBarrier(pWal);
46287 if( rc==SQLITE_OK ){
46288 if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
46289 /* It is not safe to allow the reader to continue here if frames
46290 ** may have been appended to the log before READ_LOCK(0) was obtained.
46291 ** When holding READ_LOCK(0), the reader ignores the entire log file,
46292 ** which implies that the database file contains a trustworthy
46293 ** snapshoT. Since holding READ_LOCK(0) prevents a checkpoint from
46294 ** happening, this is usually correct.
46296 ** However, if frames have been appended to the log (or if the log
46297 ** is wrapped and written for that matter) before the READ_LOCK(0)
46298 ** is obtained, that is not necessarily true. A checkpointer may
46299 ** have started to backfill the appended frames but crashed before
46300 ** it finished. Leaving a corrupt image in the database file.
46302 walUnlockShared(pWal, WAL_READ_LOCK(0));
46303 return WAL_RETRY;
46305 pWal->readLock = 0;
46306 return SQLITE_OK;
46307 }else if( rc!=SQLITE_BUSY ){
46308 return rc;
46312 /* If we get this far, it means that the reader will want to use
46313 ** the WAL to get at content from recent commits. The job now is
46314 ** to select one of the aReadMark[] entries that is closest to
46315 ** but not exceeding pWal->hdr.mxFrame and lock that entry.
46317 mxReadMark = 0;
46318 mxI = 0;
46319 for(i=1; i<WAL_NREADER; i++){
46320 u32 thisMark = pInfo->aReadMark[i];
46321 if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){
46322 assert( thisMark!=READMARK_NOT_USED );
46323 mxReadMark = thisMark;
46324 mxI = i;
46327 /* There was once an "if" here. The extra "{" is to preserve indentation. */
46329 if( (pWal->readOnly & WAL_SHM_RDONLY)==0
46330 && (mxReadMark<pWal->hdr.mxFrame || mxI==0)
46332 for(i=1; i<WAL_NREADER; i++){
46333 rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
46334 if( rc==SQLITE_OK ){
46335 mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame;
46336 mxI = i;
46337 walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
46338 break;
46339 }else if( rc!=SQLITE_BUSY ){
46340 return rc;
46344 if( mxI==0 ){
46345 assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
46346 return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK;
46349 rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
46350 if( rc ){
46351 return rc==SQLITE_BUSY ? WAL_RETRY : rc;
46353 /* Now that the read-lock has been obtained, check that neither the
46354 ** value in the aReadMark[] array or the contents of the wal-index
46355 ** header have changed.
46357 ** It is necessary to check that the wal-index header did not change
46358 ** between the time it was read and when the shared-lock was obtained
46359 ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
46360 ** that the log file may have been wrapped by a writer, or that frames
46361 ** that occur later in the log than pWal->hdr.mxFrame may have been
46362 ** copied into the database by a checkpointer. If either of these things
46363 ** happened, then reading the database with the current value of
46364 ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
46365 ** instead.
46367 ** This does not guarantee that the copy of the wal-index header is up to
46368 ** date before proceeding. That would not be possible without somehow
46369 ** blocking writers. It only guarantees that a dangerous checkpoint or
46370 ** log-wrap (either of which would require an exclusive lock on
46371 ** WAL_READ_LOCK(mxI)) has not occurred since the snapshot was valid.
46373 walShmBarrier(pWal);
46374 if( pInfo->aReadMark[mxI]!=mxReadMark
46375 || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
46377 walUnlockShared(pWal, WAL_READ_LOCK(mxI));
46378 return WAL_RETRY;
46379 }else{
46380 assert( mxReadMark<=pWal->hdr.mxFrame );
46381 pWal->readLock = (i16)mxI;
46384 return rc;
46388 ** Begin a read transaction on the database.
46390 ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
46391 ** it takes a snapshot of the state of the WAL and wal-index for the current
46392 ** instant in time. The current thread will continue to use this snapshot.
46393 ** Other threads might append new content to the WAL and wal-index but
46394 ** that extra content is ignored by the current thread.
46396 ** If the database contents have changes since the previous read
46397 ** transaction, then *pChanged is set to 1 before returning. The
46398 ** Pager layer will use this to know that is cache is stale and
46399 ** needs to be flushed.
46401 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
46402 int rc; /* Return code */
46403 int cnt = 0; /* Number of TryBeginRead attempts */
46406 rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
46407 }while( rc==WAL_RETRY );
46408 testcase( (rc&0xff)==SQLITE_BUSY );
46409 testcase( (rc&0xff)==SQLITE_IOERR );
46410 testcase( rc==SQLITE_PROTOCOL );
46411 testcase( rc==SQLITE_OK );
46412 return rc;
46416 ** Finish with a read transaction. All this does is release the
46417 ** read-lock.
46419 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
46420 sqlite3WalEndWriteTransaction(pWal);
46421 if( pWal->readLock>=0 ){
46422 walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
46423 pWal->readLock = -1;
46428 ** Read a page from the WAL, if it is present in the WAL and if the
46429 ** current read transaction is configured to use the WAL.
46431 ** The *pInWal is set to 1 if the requested page is in the WAL and
46432 ** has been loaded. Or *pInWal is set to 0 if the page was not in
46433 ** the WAL and needs to be read out of the database.
46435 SQLITE_PRIVATE int sqlite3WalRead(
46436 Wal *pWal, /* WAL handle */
46437 Pgno pgno, /* Database page number to read data for */
46438 int *pInWal, /* OUT: True if data is read from WAL */
46439 int nOut, /* Size of buffer pOut in bytes */
46440 u8 *pOut /* Buffer to write page data to */
46442 u32 iRead = 0; /* If !=0, WAL frame to return data from */
46443 u32 iLast = pWal->hdr.mxFrame; /* Last page in WAL for this reader */
46444 int iHash; /* Used to loop through N hash tables */
46446 /* This routine is only be called from within a read transaction. */
46447 assert( pWal->readLock>=0 || pWal->lockError );
46449 /* If the "last page" field of the wal-index header snapshot is 0, then
46450 ** no data will be read from the wal under any circumstances. Return early
46451 ** in this case as an optimization. Likewise, if pWal->readLock==0,
46452 ** then the WAL is ignored by the reader so return early, as if the
46453 ** WAL were empty.
46455 if( iLast==0 || pWal->readLock==0 ){
46456 *pInWal = 0;
46457 return SQLITE_OK;
46460 /* Search the hash table or tables for an entry matching page number
46461 ** pgno. Each iteration of the following for() loop searches one
46462 ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
46464 ** This code might run concurrently to the code in walIndexAppend()
46465 ** that adds entries to the wal-index (and possibly to this hash
46466 ** table). This means the value just read from the hash
46467 ** slot (aHash[iKey]) may have been added before or after the
46468 ** current read transaction was opened. Values added after the
46469 ** read transaction was opened may have been written incorrectly -
46470 ** i.e. these slots may contain garbage data. However, we assume
46471 ** that any slots written before the current read transaction was
46472 ** opened remain unmodified.
46474 ** For the reasons above, the if(...) condition featured in the inner
46475 ** loop of the following block is more stringent that would be required
46476 ** if we had exclusive access to the hash-table:
46478 ** (aPgno[iFrame]==pgno):
46479 ** This condition filters out normal hash-table collisions.
46481 ** (iFrame<=iLast):
46482 ** This condition filters out entries that were added to the hash
46483 ** table after the current read-transaction had started.
46485 for(iHash=walFramePage(iLast); iHash>=0 && iRead==0; iHash--){
46486 volatile ht_slot *aHash; /* Pointer to hash table */
46487 volatile u32 *aPgno; /* Pointer to array of page numbers */
46488 u32 iZero; /* Frame number corresponding to aPgno[0] */
46489 int iKey; /* Hash slot index */
46490 int nCollide; /* Number of hash collisions remaining */
46491 int rc; /* Error code */
46493 rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
46494 if( rc!=SQLITE_OK ){
46495 return rc;
46497 nCollide = HASHTABLE_NSLOT;
46498 for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
46499 u32 iFrame = aHash[iKey] + iZero;
46500 if( iFrame<=iLast && aPgno[aHash[iKey]]==pgno ){
46501 assert( iFrame>iRead );
46502 iRead = iFrame;
46504 if( (nCollide--)==0 ){
46505 return SQLITE_CORRUPT_BKPT;
46510 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
46511 /* If expensive assert() statements are available, do a linear search
46512 ** of the wal-index file content. Make sure the results agree with the
46513 ** result obtained using the hash indexes above. */
46515 u32 iRead2 = 0;
46516 u32 iTest;
46517 for(iTest=iLast; iTest>0; iTest--){
46518 if( walFramePgno(pWal, iTest)==pgno ){
46519 iRead2 = iTest;
46520 break;
46523 assert( iRead==iRead2 );
46525 #endif
46527 /* If iRead is non-zero, then it is the log frame number that contains the
46528 ** required page. Read and return data from the log file.
46530 if( iRead ){
46531 int sz;
46532 i64 iOffset;
46533 sz = pWal->hdr.szPage;
46534 sz = (sz&0xfe00) + ((sz&0x0001)<<16);
46535 testcase( sz<=32768 );
46536 testcase( sz>=65536 );
46537 iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
46538 *pInWal = 1;
46539 /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
46540 return sqlite3OsRead(pWal->pWalFd, pOut, nOut, iOffset);
46543 *pInWal = 0;
46544 return SQLITE_OK;
46549 ** Return the size of the database in pages (or zero, if unknown).
46551 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
46552 if( pWal && ALWAYS(pWal->readLock>=0) ){
46553 return pWal->hdr.nPage;
46555 return 0;
46560 ** This function starts a write transaction on the WAL.
46562 ** A read transaction must have already been started by a prior call
46563 ** to sqlite3WalBeginReadTransaction().
46565 ** If another thread or process has written into the database since
46566 ** the read transaction was started, then it is not possible for this
46567 ** thread to write as doing so would cause a fork. So this routine
46568 ** returns SQLITE_BUSY in that case and no write transaction is started.
46570 ** There can only be a single writer active at a time.
46572 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
46573 int rc;
46575 /* Cannot start a write transaction without first holding a read
46576 ** transaction. */
46577 assert( pWal->readLock>=0 );
46579 if( pWal->readOnly ){
46580 return SQLITE_READONLY;
46583 /* Only one writer allowed at a time. Get the write lock. Return
46584 ** SQLITE_BUSY if unable.
46586 rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
46587 if( rc ){
46588 return rc;
46590 pWal->writeLock = 1;
46592 /* If another connection has written to the database file since the
46593 ** time the read transaction on this connection was started, then
46594 ** the write is disallowed.
46596 if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
46597 walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
46598 pWal->writeLock = 0;
46599 rc = SQLITE_BUSY;
46602 return rc;
46606 ** End a write transaction. The commit has already been done. This
46607 ** routine merely releases the lock.
46609 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
46610 if( pWal->writeLock ){
46611 walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
46612 pWal->writeLock = 0;
46614 return SQLITE_OK;
46618 ** If any data has been written (but not committed) to the log file, this
46619 ** function moves the write-pointer back to the start of the transaction.
46621 ** Additionally, the callback function is invoked for each frame written
46622 ** to the WAL since the start of the transaction. If the callback returns
46623 ** other than SQLITE_OK, it is not invoked again and the error code is
46624 ** returned to the caller.
46626 ** Otherwise, if the callback function does not return an error, this
46627 ** function returns SQLITE_OK.
46629 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
46630 int rc = SQLITE_OK;
46631 if( ALWAYS(pWal->writeLock) ){
46632 Pgno iMax = pWal->hdr.mxFrame;
46633 Pgno iFrame;
46635 /* Restore the clients cache of the wal-index header to the state it
46636 ** was in before the client began writing to the database.
46638 memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
46640 for(iFrame=pWal->hdr.mxFrame+1;
46641 ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
46642 iFrame++
46644 /* This call cannot fail. Unless the page for which the page number
46645 ** is passed as the second argument is (a) in the cache and
46646 ** (b) has an outstanding reference, then xUndo is either a no-op
46647 ** (if (a) is false) or simply expels the page from the cache (if (b)
46648 ** is false).
46650 ** If the upper layer is doing a rollback, it is guaranteed that there
46651 ** are no outstanding references to any page other than page 1. And
46652 ** page 1 is never written to the log until the transaction is
46653 ** committed. As a result, the call to xUndo may not fail.
46655 assert( walFramePgno(pWal, iFrame)!=1 );
46656 rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
46658 walCleanupHash(pWal);
46660 assert( rc==SQLITE_OK );
46661 return rc;
46665 ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
46666 ** values. This function populates the array with values required to
46667 ** "rollback" the write position of the WAL handle back to the current
46668 ** point in the event of a savepoint rollback (via WalSavepointUndo()).
46670 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
46671 assert( pWal->writeLock );
46672 aWalData[0] = pWal->hdr.mxFrame;
46673 aWalData[1] = pWal->hdr.aFrameCksum[0];
46674 aWalData[2] = pWal->hdr.aFrameCksum[1];
46675 aWalData[3] = pWal->nCkpt;
46679 ** Move the write position of the WAL back to the point identified by
46680 ** the values in the aWalData[] array. aWalData must point to an array
46681 ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
46682 ** by a call to WalSavepoint().
46684 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
46685 int rc = SQLITE_OK;
46687 assert( pWal->writeLock );
46688 assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
46690 if( aWalData[3]!=pWal->nCkpt ){
46691 /* This savepoint was opened immediately after the write-transaction
46692 ** was started. Right after that, the writer decided to wrap around
46693 ** to the start of the log. Update the savepoint values to match.
46695 aWalData[0] = 0;
46696 aWalData[3] = pWal->nCkpt;
46699 if( aWalData[0]<pWal->hdr.mxFrame ){
46700 pWal->hdr.mxFrame = aWalData[0];
46701 pWal->hdr.aFrameCksum[0] = aWalData[1];
46702 pWal->hdr.aFrameCksum[1] = aWalData[2];
46703 walCleanupHash(pWal);
46706 return rc;
46710 ** This function is called just before writing a set of frames to the log
46711 ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
46712 ** to the current log file, it is possible to overwrite the start of the
46713 ** existing log file with the new frames (i.e. "reset" the log). If so,
46714 ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
46715 ** unchanged.
46717 ** SQLITE_OK is returned if no error is encountered (regardless of whether
46718 ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
46719 ** if an error occurs.
46721 static int walRestartLog(Wal *pWal){
46722 int rc = SQLITE_OK;
46723 int cnt;
46725 if( pWal->readLock==0 ){
46726 volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
46727 assert( pInfo->nBackfill==pWal->hdr.mxFrame );
46728 if( pInfo->nBackfill>0 ){
46729 u32 salt1;
46730 sqlite3_randomness(4, &salt1);
46731 rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
46732 if( rc==SQLITE_OK ){
46733 /* If all readers are using WAL_READ_LOCK(0) (in other words if no
46734 ** readers are currently using the WAL), then the transactions
46735 ** frames will overwrite the start of the existing log. Update the
46736 ** wal-index header to reflect this.
46738 ** In theory it would be Ok to update the cache of the header only
46739 ** at this point. But updating the actual wal-index header is also
46740 ** safe and means there is no special case for sqlite3WalUndo()
46741 ** to handle if this transaction is rolled back.
46743 int i; /* Loop counter */
46744 u32 *aSalt = pWal->hdr.aSalt; /* Big-endian salt values */
46746 /* Limit the size of WAL file if the journal_size_limit PRAGMA is
46747 ** set to a non-negative value. Log errors encountered
46748 ** during the truncation attempt. */
46749 if( pWal->mxWalSize>=0 ){
46750 i64 sz;
46751 int rx;
46752 sqlite3BeginBenignMalloc();
46753 rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
46754 if( rx==SQLITE_OK && (sz > pWal->mxWalSize) ){
46755 rx = sqlite3OsTruncate(pWal->pWalFd, pWal->mxWalSize);
46757 sqlite3EndBenignMalloc();
46758 if( rx ){
46759 sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
46763 pWal->nCkpt++;
46764 pWal->hdr.mxFrame = 0;
46765 sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
46766 aSalt[1] = salt1;
46767 walIndexWriteHdr(pWal);
46768 pInfo->nBackfill = 0;
46769 for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
46770 assert( pInfo->aReadMark[0]==0 );
46771 walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
46772 }else if( rc!=SQLITE_BUSY ){
46773 return rc;
46776 walUnlockShared(pWal, WAL_READ_LOCK(0));
46777 pWal->readLock = -1;
46778 cnt = 0;
46780 int notUsed;
46781 rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
46782 }while( rc==WAL_RETRY );
46783 assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
46784 testcase( (rc&0xff)==SQLITE_IOERR );
46785 testcase( rc==SQLITE_PROTOCOL );
46786 testcase( rc==SQLITE_OK );
46788 return rc;
46792 ** Write a set of frames to the log. The caller must hold the write-lock
46793 ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
46795 SQLITE_PRIVATE int sqlite3WalFrames(
46796 Wal *pWal, /* Wal handle to write to */
46797 int szPage, /* Database page-size in bytes */
46798 PgHdr *pList, /* List of dirty pages to write */
46799 Pgno nTruncate, /* Database size after this commit */
46800 int isCommit, /* True if this is a commit */
46801 int sync_flags /* Flags to pass to OsSync() (or 0) */
46803 int rc; /* Used to catch return codes */
46804 u32 iFrame; /* Next frame address */
46805 u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-header in */
46806 PgHdr *p; /* Iterator to run through pList with. */
46807 PgHdr *pLast = 0; /* Last frame in list */
46808 int nLast = 0; /* Number of extra copies of last page */
46810 assert( pList );
46811 assert( pWal->writeLock );
46813 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
46814 { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
46815 WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
46816 pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
46818 #endif
46820 /* See if it is possible to write these frames into the start of the
46821 ** log file, instead of appending to it at pWal->hdr.mxFrame.
46823 if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
46824 return rc;
46827 /* If this is the first frame written into the log, write the WAL
46828 ** header to the start of the WAL file. See comments at the top of
46829 ** this source file for a description of the WAL header format.
46831 iFrame = pWal->hdr.mxFrame;
46832 if( iFrame==0 ){
46833 u8 aWalHdr[WAL_HDRSIZE]; /* Buffer to assemble wal-header in */
46834 u32 aCksum[2]; /* Checksum for wal-header */
46836 sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
46837 sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
46838 sqlite3Put4byte(&aWalHdr[8], szPage);
46839 sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
46840 sqlite3_randomness(8, pWal->hdr.aSalt);
46841 memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
46842 walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
46843 sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
46844 sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
46846 pWal->szPage = szPage;
46847 pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
46848 pWal->hdr.aFrameCksum[0] = aCksum[0];
46849 pWal->hdr.aFrameCksum[1] = aCksum[1];
46851 rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
46852 WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
46853 if( rc!=SQLITE_OK ){
46854 return rc;
46857 assert( (int)pWal->szPage==szPage );
46859 /* Write the log file. */
46860 for(p=pList; p; p=p->pDirty){
46861 u32 nDbsize; /* Db-size field for frame header */
46862 i64 iOffset; /* Write offset in log file */
46863 void *pData;
46865 iOffset = walFrameOffset(++iFrame, szPage);
46866 /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
46868 /* Populate and write the frame header */
46869 nDbsize = (isCommit && p->pDirty==0) ? nTruncate : 0;
46870 #if defined(SQLITE_HAS_CODEC)
46871 if( (pData = sqlite3PagerCodec(p))==0 ) return SQLITE_NOMEM;
46872 #else
46873 pData = p->pData;
46874 #endif
46875 walEncodeFrame(pWal, p->pgno, nDbsize, pData, aFrame);
46876 rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOffset);
46877 if( rc!=SQLITE_OK ){
46878 return rc;
46881 /* Write the page data */
46882 rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOffset+sizeof(aFrame));
46883 if( rc!=SQLITE_OK ){
46884 return rc;
46886 pLast = p;
46889 /* Sync the log file if the 'isSync' flag was specified. */
46890 if( sync_flags ){
46891 i64 iSegment = sqlite3OsSectorSize(pWal->pWalFd);
46892 i64 iOffset = walFrameOffset(iFrame+1, szPage);
46894 assert( isCommit );
46895 assert( iSegment>0 );
46897 iSegment = (((iOffset+iSegment-1)/iSegment) * iSegment);
46898 while( iOffset<iSegment ){
46899 void *pData;
46900 #if defined(SQLITE_HAS_CODEC)
46901 if( (pData = sqlite3PagerCodec(pLast))==0 ) return SQLITE_NOMEM;
46902 #else
46903 pData = pLast->pData;
46904 #endif
46905 walEncodeFrame(pWal, pLast->pgno, nTruncate, pData, aFrame);
46906 /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
46907 rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOffset);
46908 if( rc!=SQLITE_OK ){
46909 return rc;
46911 iOffset += WAL_FRAME_HDRSIZE;
46912 rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOffset);
46913 if( rc!=SQLITE_OK ){
46914 return rc;
46916 nLast++;
46917 iOffset += szPage;
46920 rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
46923 /* Append data to the wal-index. It is not necessary to lock the
46924 ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
46925 ** guarantees that there are no other writers, and no data that may
46926 ** be in use by existing readers is being overwritten.
46928 iFrame = pWal->hdr.mxFrame;
46929 for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
46930 iFrame++;
46931 rc = walIndexAppend(pWal, iFrame, p->pgno);
46933 while( nLast>0 && rc==SQLITE_OK ){
46934 iFrame++;
46935 nLast--;
46936 rc = walIndexAppend(pWal, iFrame, pLast->pgno);
46939 if( rc==SQLITE_OK ){
46940 /* Update the private copy of the header. */
46941 pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
46942 testcase( szPage<=32768 );
46943 testcase( szPage>=65536 );
46944 pWal->hdr.mxFrame = iFrame;
46945 if( isCommit ){
46946 pWal->hdr.iChange++;
46947 pWal->hdr.nPage = nTruncate;
46949 /* If this is a commit, update the wal-index header too. */
46950 if( isCommit ){
46951 walIndexWriteHdr(pWal);
46952 pWal->iCallback = iFrame;
46956 WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
46957 return rc;
46961 ** This routine is called to implement sqlite3_wal_checkpoint() and
46962 ** related interfaces.
46964 ** Obtain a CHECKPOINT lock and then backfill as much information as
46965 ** we can from WAL into the database.
46967 ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
46968 ** callback. In this case this function runs a blocking checkpoint.
46970 SQLITE_PRIVATE int sqlite3WalCheckpoint(
46971 Wal *pWal, /* Wal connection */
46972 int eMode, /* PASSIVE, FULL or RESTART */
46973 int (*xBusy)(void*), /* Function to call when busy */
46974 void *pBusyArg, /* Context argument for xBusyHandler */
46975 int sync_flags, /* Flags to sync db file with (or 0) */
46976 int nBuf, /* Size of temporary buffer */
46977 u8 *zBuf, /* Temporary buffer to use */
46978 int *pnLog, /* OUT: Number of frames in WAL */
46979 int *pnCkpt /* OUT: Number of backfilled frames in WAL */
46981 int rc; /* Return code */
46982 int isChanged = 0; /* True if a new wal-index header is loaded */
46983 int eMode2 = eMode; /* Mode to pass to walCheckpoint() */
46985 assert( pWal->ckptLock==0 );
46986 assert( pWal->writeLock==0 );
46988 if( pWal->readOnly ) return SQLITE_READONLY;
46989 WALTRACE(("WAL%p: checkpoint begins\n", pWal));
46990 rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
46991 if( rc ){
46992 /* Usually this is SQLITE_BUSY meaning that another thread or process
46993 ** is already running a checkpoint, or maybe a recovery. But it might
46994 ** also be SQLITE_IOERR. */
46995 return rc;
46997 pWal->ckptLock = 1;
46999 /* If this is a blocking-checkpoint, then obtain the write-lock as well
47000 ** to prevent any writers from running while the checkpoint is underway.
47001 ** This has to be done before the call to walIndexReadHdr() below.
47003 ** If the writer lock cannot be obtained, then a passive checkpoint is
47004 ** run instead. Since the checkpointer is not holding the writer lock,
47005 ** there is no point in blocking waiting for any readers. Assuming no
47006 ** other error occurs, this function will return SQLITE_BUSY to the caller.
47008 if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
47009 rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
47010 if( rc==SQLITE_OK ){
47011 pWal->writeLock = 1;
47012 }else if( rc==SQLITE_BUSY ){
47013 eMode2 = SQLITE_CHECKPOINT_PASSIVE;
47014 rc = SQLITE_OK;
47018 /* Read the wal-index header. */
47019 if( rc==SQLITE_OK ){
47020 rc = walIndexReadHdr(pWal, &isChanged);
47023 /* Copy data from the log to the database file. */
47024 if( rc==SQLITE_OK ){
47025 if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
47026 rc = SQLITE_CORRUPT_BKPT;
47027 }else{
47028 rc = walCheckpoint(pWal, eMode2, xBusy, pBusyArg, sync_flags, zBuf);
47031 /* If no error occurred, set the output variables. */
47032 if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
47033 if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
47034 if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
47038 if( isChanged ){
47039 /* If a new wal-index header was loaded before the checkpoint was
47040 ** performed, then the pager-cache associated with pWal is now
47041 ** out of date. So zero the cached wal-index header to ensure that
47042 ** next time the pager opens a snapshot on this database it knows that
47043 ** the cache needs to be reset.
47045 memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
47048 /* Release the locks. */
47049 sqlite3WalEndWriteTransaction(pWal);
47050 walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
47051 pWal->ckptLock = 0;
47052 WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
47053 return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
47056 /* Return the value to pass to a sqlite3_wal_hook callback, the
47057 ** number of frames in the WAL at the point of the last commit since
47058 ** sqlite3WalCallback() was called. If no commits have occurred since
47059 ** the last call, then return 0.
47061 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
47062 u32 ret = 0;
47063 if( pWal ){
47064 ret = pWal->iCallback;
47065 pWal->iCallback = 0;
47067 return (int)ret;
47071 ** This function is called to change the WAL subsystem into or out
47072 ** of locking_mode=EXCLUSIVE.
47074 ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
47075 ** into locking_mode=NORMAL. This means that we must acquire a lock
47076 ** on the pWal->readLock byte. If the WAL is already in locking_mode=NORMAL
47077 ** or if the acquisition of the lock fails, then return 0. If the
47078 ** transition out of exclusive-mode is successful, return 1. This
47079 ** operation must occur while the pager is still holding the exclusive
47080 ** lock on the main database file.
47082 ** If op is one, then change from locking_mode=NORMAL into
47083 ** locking_mode=EXCLUSIVE. This means that the pWal->readLock must
47084 ** be released. Return 1 if the transition is made and 0 if the
47085 ** WAL is already in exclusive-locking mode - meaning that this
47086 ** routine is a no-op. The pager must already hold the exclusive lock
47087 ** on the main database file before invoking this operation.
47089 ** If op is negative, then do a dry-run of the op==1 case but do
47090 ** not actually change anything. The pager uses this to see if it
47091 ** should acquire the database exclusive lock prior to invoking
47092 ** the op==1 case.
47094 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
47095 int rc;
47096 assert( pWal->writeLock==0 );
47097 assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
47099 /* pWal->readLock is usually set, but might be -1 if there was a
47100 ** prior error while attempting to acquire are read-lock. This cannot
47101 ** happen if the connection is actually in exclusive mode (as no xShmLock
47102 ** locks are taken in this case). Nor should the pager attempt to
47103 ** upgrade to exclusive-mode following such an error.
47105 assert( pWal->readLock>=0 || pWal->lockError );
47106 assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
47108 if( op==0 ){
47109 if( pWal->exclusiveMode ){
47110 pWal->exclusiveMode = 0;
47111 if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
47112 pWal->exclusiveMode = 1;
47114 rc = pWal->exclusiveMode==0;
47115 }else{
47116 /* Already in locking_mode=NORMAL */
47117 rc = 0;
47119 }else if( op>0 ){
47120 assert( pWal->exclusiveMode==0 );
47121 assert( pWal->readLock>=0 );
47122 walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
47123 pWal->exclusiveMode = 1;
47124 rc = 1;
47125 }else{
47126 rc = pWal->exclusiveMode==0;
47128 return rc;
47132 ** Return true if the argument is non-NULL and the WAL module is using
47133 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
47134 ** WAL module is using shared-memory, return false.
47136 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
47137 return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
47140 #endif /* #ifndef SQLITE_OMIT_WAL */
47142 /************** End of wal.c *************************************************/
47143 /************** Begin file btmutex.c *****************************************/
47145 ** 2007 August 27
47147 ** The author disclaims copyright to this source code. In place of
47148 ** a legal notice, here is a blessing:
47150 ** May you do good and not evil.
47151 ** May you find forgiveness for yourself and forgive others.
47152 ** May you share freely, never taking more than you give.
47154 *************************************************************************
47156 ** This file contains code used to implement mutexes on Btree objects.
47157 ** This code really belongs in btree.c. But btree.c is getting too
47158 ** big and we want to break it down some. This packaged seemed like
47159 ** a good breakout.
47161 /************** Include btreeInt.h in the middle of btmutex.c ****************/
47162 /************** Begin file btreeInt.h ****************************************/
47164 ** 2004 April 6
47166 ** The author disclaims copyright to this source code. In place of
47167 ** a legal notice, here is a blessing:
47169 ** May you do good and not evil.
47170 ** May you find forgiveness for yourself and forgive others.
47171 ** May you share freely, never taking more than you give.
47173 *************************************************************************
47174 ** This file implements a external (disk-based) database using BTrees.
47175 ** For a detailed discussion of BTrees, refer to
47177 ** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
47178 ** "Sorting And Searching", pages 473-480. Addison-Wesley
47179 ** Publishing Company, Reading, Massachusetts.
47181 ** The basic idea is that each page of the file contains N database
47182 ** entries and N+1 pointers to subpages.
47184 ** ----------------------------------------------------------------
47185 ** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
47186 ** ----------------------------------------------------------------
47188 ** All of the keys on the page that Ptr(0) points to have values less
47189 ** than Key(0). All of the keys on page Ptr(1) and its subpages have
47190 ** values greater than Key(0) and less than Key(1). All of the keys
47191 ** on Ptr(N) and its subpages have values greater than Key(N-1). And
47192 ** so forth.
47194 ** Finding a particular key requires reading O(log(M)) pages from the
47195 ** disk where M is the number of entries in the tree.
47197 ** In this implementation, a single file can hold one or more separate
47198 ** BTrees. Each BTree is identified by the index of its root page. The
47199 ** key and data for any entry are combined to form the "payload". A
47200 ** fixed amount of payload can be carried directly on the database
47201 ** page. If the payload is larger than the preset amount then surplus
47202 ** bytes are stored on overflow pages. The payload for an entry
47203 ** and the preceding pointer are combined to form a "Cell". Each
47204 ** page has a small header which contains the Ptr(N) pointer and other
47205 ** information such as the size of key and data.
47207 ** FORMAT DETAILS
47209 ** The file is divided into pages. The first page is called page 1,
47210 ** the second is page 2, and so forth. A page number of zero indicates
47211 ** "no such page". The page size can be any power of 2 between 512 and 65536.
47212 ** Each page can be either a btree page, a freelist page, an overflow
47213 ** page, or a pointer-map page.
47215 ** The first page is always a btree page. The first 100 bytes of the first
47216 ** page contain a special header (the "file header") that describes the file.
47217 ** The format of the file header is as follows:
47219 ** OFFSET SIZE DESCRIPTION
47220 ** 0 16 Header string: "SQLite format 3\000"
47221 ** 16 2 Page size in bytes.
47222 ** 18 1 File format write version
47223 ** 19 1 File format read version
47224 ** 20 1 Bytes of unused space at the end of each page
47225 ** 21 1 Max embedded payload fraction
47226 ** 22 1 Min embedded payload fraction
47227 ** 23 1 Min leaf payload fraction
47228 ** 24 4 File change counter
47229 ** 28 4 Reserved for future use
47230 ** 32 4 First freelist page
47231 ** 36 4 Number of freelist pages in the file
47232 ** 40 60 15 4-byte meta values passed to higher layers
47234 ** 40 4 Schema cookie
47235 ** 44 4 File format of schema layer
47236 ** 48 4 Size of page cache
47237 ** 52 4 Largest root-page (auto/incr_vacuum)
47238 ** 56 4 1=UTF-8 2=UTF16le 3=UTF16be
47239 ** 60 4 User version
47240 ** 64 4 Incremental vacuum mode
47241 ** 68 4 unused
47242 ** 72 4 unused
47243 ** 76 4 unused
47245 ** All of the integer values are big-endian (most significant byte first).
47247 ** The file change counter is incremented when the database is changed
47248 ** This counter allows other processes to know when the file has changed
47249 ** and thus when they need to flush their cache.
47251 ** The max embedded payload fraction is the amount of the total usable
47252 ** space in a page that can be consumed by a single cell for standard
47253 ** B-tree (non-LEAFDATA) tables. A value of 255 means 100%. The default
47254 ** is to limit the maximum cell size so that at least 4 cells will fit
47255 ** on one page. Thus the default max embedded payload fraction is 64.
47257 ** If the payload for a cell is larger than the max payload, then extra
47258 ** payload is spilled to overflow pages. Once an overflow page is allocated,
47259 ** as many bytes as possible are moved into the overflow pages without letting
47260 ** the cell size drop below the min embedded payload fraction.
47262 ** The min leaf payload fraction is like the min embedded payload fraction
47263 ** except that it applies to leaf nodes in a LEAFDATA tree. The maximum
47264 ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
47265 ** not specified in the header.
47267 ** Each btree pages is divided into three sections: The header, the
47268 ** cell pointer array, and the cell content area. Page 1 also has a 100-byte
47269 ** file header that occurs before the page header.
47271 ** |----------------|
47272 ** | file header | 100 bytes. Page 1 only.
47273 ** |----------------|
47274 ** | page header | 8 bytes for leaves. 12 bytes for interior nodes
47275 ** |----------------|
47276 ** | cell pointer | | 2 bytes per cell. Sorted order.
47277 ** | array | | Grows downward
47278 ** | | v
47279 ** |----------------|
47280 ** | unallocated |
47281 ** | space |
47282 ** |----------------| ^ Grows upwards
47283 ** | cell content | | Arbitrary order interspersed with freeblocks.
47284 ** | area | | and free space fragments.
47285 ** |----------------|
47287 ** The page headers looks like this:
47289 ** OFFSET SIZE DESCRIPTION
47290 ** 0 1 Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
47291 ** 1 2 byte offset to the first freeblock
47292 ** 3 2 number of cells on this page
47293 ** 5 2 first byte of the cell content area
47294 ** 7 1 number of fragmented free bytes
47295 ** 8 4 Right child (the Ptr(N) value). Omitted on leaves.
47297 ** The flags define the format of this btree page. The leaf flag means that
47298 ** this page has no children. The zerodata flag means that this page carries
47299 ** only keys and no data. The intkey flag means that the key is a integer
47300 ** which is stored in the key size entry of the cell header rather than in
47301 ** the payload area.
47303 ** The cell pointer array begins on the first byte after the page header.
47304 ** The cell pointer array contains zero or more 2-byte numbers which are
47305 ** offsets from the beginning of the page to the cell content in the cell
47306 ** content area. The cell pointers occur in sorted order. The system strives
47307 ** to keep free space after the last cell pointer so that new cells can
47308 ** be easily added without having to defragment the page.
47310 ** Cell content is stored at the very end of the page and grows toward the
47311 ** beginning of the page.
47313 ** Unused space within the cell content area is collected into a linked list of
47314 ** freeblocks. Each freeblock is at least 4 bytes in size. The byte offset
47315 ** to the first freeblock is given in the header. Freeblocks occur in
47316 ** increasing order. Because a freeblock must be at least 4 bytes in size,
47317 ** any group of 3 or fewer unused bytes in the cell content area cannot
47318 ** exist on the freeblock chain. A group of 3 or fewer free bytes is called
47319 ** a fragment. The total number of bytes in all fragments is recorded.
47320 ** in the page header at offset 7.
47322 ** SIZE DESCRIPTION
47323 ** 2 Byte offset of the next freeblock
47324 ** 2 Bytes in this freeblock
47326 ** Cells are of variable length. Cells are stored in the cell content area at
47327 ** the end of the page. Pointers to the cells are in the cell pointer array
47328 ** that immediately follows the page header. Cells is not necessarily
47329 ** contiguous or in order, but cell pointers are contiguous and in order.
47331 ** Cell content makes use of variable length integers. A variable
47332 ** length integer is 1 to 9 bytes where the lower 7 bits of each
47333 ** byte are used. The integer consists of all bytes that have bit 8 set and
47334 ** the first byte with bit 8 clear. The most significant byte of the integer
47335 ** appears first. A variable-length integer may not be more than 9 bytes long.
47336 ** As a special case, all 8 bytes of the 9th byte are used as data. This
47337 ** allows a 64-bit integer to be encoded in 9 bytes.
47339 ** 0x00 becomes 0x00000000
47340 ** 0x7f becomes 0x0000007f
47341 ** 0x81 0x00 becomes 0x00000080
47342 ** 0x82 0x00 becomes 0x00000100
47343 ** 0x80 0x7f becomes 0x0000007f
47344 ** 0x8a 0x91 0xd1 0xac 0x78 becomes 0x12345678
47345 ** 0x81 0x81 0x81 0x81 0x01 becomes 0x10204081
47347 ** Variable length integers are used for rowids and to hold the number of
47348 ** bytes of key and data in a btree cell.
47350 ** The content of a cell looks like this:
47352 ** SIZE DESCRIPTION
47353 ** 4 Page number of the left child. Omitted if leaf flag is set.
47354 ** var Number of bytes of data. Omitted if the zerodata flag is set.
47355 ** var Number of bytes of key. Or the key itself if intkey flag is set.
47356 ** * Payload
47357 ** 4 First page of the overflow chain. Omitted if no overflow
47359 ** Overflow pages form a linked list. Each page except the last is completely
47360 ** filled with data (pagesize - 4 bytes). The last page can have as little
47361 ** as 1 byte of data.
47363 ** SIZE DESCRIPTION
47364 ** 4 Page number of next overflow page
47365 ** * Data
47367 ** Freelist pages come in two subtypes: trunk pages and leaf pages. The
47368 ** file header points to the first in a linked list of trunk page. Each trunk
47369 ** page points to multiple leaf pages. The content of a leaf page is
47370 ** unspecified. A trunk page looks like this:
47372 ** SIZE DESCRIPTION
47373 ** 4 Page number of next trunk page
47374 ** 4 Number of leaf pointers on this page
47375 ** * zero or more pages numbers of leaves
47379 /* The following value is the maximum cell size assuming a maximum page
47380 ** size give above.
47382 #define MX_CELL_SIZE(pBt) ((int)(pBt->pageSize-8))
47384 /* The maximum number of cells on a single page of the database. This
47385 ** assumes a minimum cell size of 6 bytes (4 bytes for the cell itself
47386 ** plus 2 bytes for the index to the cell in the page header). Such
47387 ** small cells will be rare, but they are possible.
47389 #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
47391 /* Forward declarations */
47392 typedef struct MemPage MemPage;
47393 typedef struct BtLock BtLock;
47396 ** This is a magic string that appears at the beginning of every
47397 ** SQLite database in order to identify the file as a real database.
47399 ** You can change this value at compile-time by specifying a
47400 ** -DSQLITE_FILE_HEADER="..." on the compiler command-line. The
47401 ** header must be exactly 16 bytes including the zero-terminator so
47402 ** the string itself should be 15 characters long. If you change
47403 ** the header, then your custom library will not be able to read
47404 ** databases generated by the standard tools and the standard tools
47405 ** will not be able to read databases created by your custom library.
47407 #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
47408 # define SQLITE_FILE_HEADER "SQLite format 3"
47409 #endif
47412 ** Page type flags. An ORed combination of these flags appear as the
47413 ** first byte of on-disk image of every BTree page.
47415 #define PTF_INTKEY 0x01
47416 #define PTF_ZERODATA 0x02
47417 #define PTF_LEAFDATA 0x04
47418 #define PTF_LEAF 0x08
47421 ** As each page of the file is loaded into memory, an instance of the following
47422 ** structure is appended and initialized to zero. This structure stores
47423 ** information about the page that is decoded from the raw file page.
47425 ** The pParent field points back to the parent page. This allows us to
47426 ** walk up the BTree from any leaf to the root. Care must be taken to
47427 ** unref() the parent page pointer when this page is no longer referenced.
47428 ** The pageDestructor() routine handles that chore.
47430 ** Access to all fields of this structure is controlled by the mutex
47431 ** stored in MemPage.pBt->mutex.
47433 struct MemPage {
47434 u8 isInit; /* True if previously initialized. MUST BE FIRST! */
47435 u8 nOverflow; /* Number of overflow cell bodies in aCell[] */
47436 u8 intKey; /* True if intkey flag is set */
47437 u8 leaf; /* True if leaf flag is set */
47438 u8 hasData; /* True if this page stores data */
47439 u8 hdrOffset; /* 100 for page 1. 0 otherwise */
47440 u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */
47441 u16 maxLocal; /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
47442 u16 minLocal; /* Copy of BtShared.minLocal or BtShared.minLeaf */
47443 u16 cellOffset; /* Index in aData of first cell pointer */
47444 u16 nFree; /* Number of free bytes on the page */
47445 u16 nCell; /* Number of cells on this page, local and ovfl */
47446 u16 maskPage; /* Mask for page offset */
47447 struct _OvflCell { /* Cells that will not fit on aData[] */
47448 u8 *pCell; /* Pointers to the body of the overflow cell */
47449 u16 idx; /* Insert this cell before idx-th non-overflow cell */
47450 } aOvfl[5];
47451 BtShared *pBt; /* Pointer to BtShared that this page is part of */
47452 u8 *aData; /* Pointer to disk image of the page data */
47453 DbPage *pDbPage; /* Pager page handle */
47454 Pgno pgno; /* Page number for this page */
47458 ** The in-memory image of a disk page has the auxiliary information appended
47459 ** to the end. EXTRA_SIZE is the number of bytes of space needed to hold
47460 ** that extra information.
47462 #define EXTRA_SIZE sizeof(MemPage)
47465 ** A linked list of the following structures is stored at BtShared.pLock.
47466 ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
47467 ** is opened on the table with root page BtShared.iTable. Locks are removed
47468 ** from this list when a transaction is committed or rolled back, or when
47469 ** a btree handle is closed.
47471 struct BtLock {
47472 Btree *pBtree; /* Btree handle holding this lock */
47473 Pgno iTable; /* Root page of table */
47474 u8 eLock; /* READ_LOCK or WRITE_LOCK */
47475 BtLock *pNext; /* Next in BtShared.pLock list */
47478 /* Candidate values for BtLock.eLock */
47479 #define READ_LOCK 1
47480 #define WRITE_LOCK 2
47482 /* A Btree handle
47484 ** A database connection contains a pointer to an instance of
47485 ** this object for every database file that it has open. This structure
47486 ** is opaque to the database connection. The database connection cannot
47487 ** see the internals of this structure and only deals with pointers to
47488 ** this structure.
47490 ** For some database files, the same underlying database cache might be
47491 ** shared between multiple connections. In that case, each connection
47492 ** has it own instance of this object. But each instance of this object
47493 ** points to the same BtShared object. The database cache and the
47494 ** schema associated with the database file are all contained within
47495 ** the BtShared object.
47497 ** All fields in this structure are accessed under sqlite3.mutex.
47498 ** The pBt pointer itself may not be changed while there exists cursors
47499 ** in the referenced BtShared that point back to this Btree since those
47500 ** cursors have to go through this Btree to find their BtShared and
47501 ** they often do so without holding sqlite3.mutex.
47503 struct Btree {
47504 sqlite3 *db; /* The database connection holding this btree */
47505 BtShared *pBt; /* Sharable content of this btree */
47506 u8 inTrans; /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
47507 u8 sharable; /* True if we can share pBt with another db */
47508 u8 locked; /* True if db currently has pBt locked */
47509 int wantToLock; /* Number of nested calls to sqlite3BtreeEnter() */
47510 int nBackup; /* Number of backup operations reading this btree */
47511 Btree *pNext; /* List of other sharable Btrees from the same db */
47512 Btree *pPrev; /* Back pointer of the same list */
47513 #ifndef SQLITE_OMIT_SHARED_CACHE
47514 BtLock lock; /* Object used to lock page 1 */
47515 #endif
47519 ** Btree.inTrans may take one of the following values.
47521 ** If the shared-data extension is enabled, there may be multiple users
47522 ** of the Btree structure. At most one of these may open a write transaction,
47523 ** but any number may have active read transactions.
47525 #define TRANS_NONE 0
47526 #define TRANS_READ 1
47527 #define TRANS_WRITE 2
47530 ** An instance of this object represents a single database file.
47532 ** A single database file can be in use as the same time by two
47533 ** or more database connections. When two or more connections are
47534 ** sharing the same database file, each connection has it own
47535 ** private Btree object for the file and each of those Btrees points
47536 ** to this one BtShared object. BtShared.nRef is the number of
47537 ** connections currently sharing this database file.
47539 ** Fields in this structure are accessed under the BtShared.mutex
47540 ** mutex, except for nRef and pNext which are accessed under the
47541 ** global SQLITE_MUTEX_STATIC_MASTER mutex. The pPager field
47542 ** may not be modified once it is initially set as long as nRef>0.
47543 ** The pSchema field may be set once under BtShared.mutex and
47544 ** thereafter is unchanged as long as nRef>0.
47546 ** isPending:
47548 ** If a BtShared client fails to obtain a write-lock on a database
47549 ** table (because there exists one or more read-locks on the table),
47550 ** the shared-cache enters 'pending-lock' state and isPending is
47551 ** set to true.
47553 ** The shared-cache leaves the 'pending lock' state when either of
47554 ** the following occur:
47556 ** 1) The current writer (BtShared.pWriter) concludes its transaction, OR
47557 ** 2) The number of locks held by other connections drops to zero.
47559 ** while in the 'pending-lock' state, no connection may start a new
47560 ** transaction.
47562 ** This feature is included to help prevent writer-starvation.
47564 struct BtShared {
47565 Pager *pPager; /* The page cache */
47566 sqlite3 *db; /* Database connection currently using this Btree */
47567 BtCursor *pCursor; /* A list of all open cursors */
47568 MemPage *pPage1; /* First page of the database */
47569 u8 readOnly; /* True if the underlying file is readonly */
47570 u8 pageSizeFixed; /* True if the page size can no longer be changed */
47571 u8 secureDelete; /* True if secure_delete is enabled */
47572 u8 initiallyEmpty; /* Database is empty at start of transaction */
47573 u8 openFlags; /* Flags to sqlite3BtreeOpen() */
47574 #ifndef SQLITE_OMIT_AUTOVACUUM
47575 u8 autoVacuum; /* True if auto-vacuum is enabled */
47576 u8 incrVacuum; /* True if incr-vacuum is enabled */
47577 #endif
47578 u8 inTransaction; /* Transaction state */
47579 u8 doNotUseWAL; /* If true, do not open write-ahead-log file */
47580 u16 maxLocal; /* Maximum local payload in non-LEAFDATA tables */
47581 u16 minLocal; /* Minimum local payload in non-LEAFDATA tables */
47582 u16 maxLeaf; /* Maximum local payload in a LEAFDATA table */
47583 u16 minLeaf; /* Minimum local payload in a LEAFDATA table */
47584 u32 pageSize; /* Total number of bytes on a page */
47585 u32 usableSize; /* Number of usable bytes on each page */
47586 int nTransaction; /* Number of open transactions (read + write) */
47587 u32 nPage; /* Number of pages in the database */
47588 void *pSchema; /* Pointer to space allocated by sqlite3BtreeSchema() */
47589 void (*xFreeSchema)(void*); /* Destructor for BtShared.pSchema */
47590 sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
47591 Bitvec *pHasContent; /* Set of pages moved to free-list this transaction */
47592 #ifndef SQLITE_OMIT_SHARED_CACHE
47593 int nRef; /* Number of references to this structure */
47594 BtShared *pNext; /* Next on a list of sharable BtShared structs */
47595 BtLock *pLock; /* List of locks held on this shared-btree struct */
47596 Btree *pWriter; /* Btree with currently open write transaction */
47597 u8 isExclusive; /* True if pWriter has an EXCLUSIVE lock on the db */
47598 u8 isPending; /* If waiting for read-locks to clear */
47599 #endif
47600 u8 *pTmpSpace; /* BtShared.pageSize bytes of space for tmp use */
47604 ** An instance of the following structure is used to hold information
47605 ** about a cell. The parseCellPtr() function fills in this structure
47606 ** based on information extract from the raw disk page.
47608 typedef struct CellInfo CellInfo;
47609 struct CellInfo {
47610 i64 nKey; /* The key for INTKEY tables, or number of bytes in key */
47611 u8 *pCell; /* Pointer to the start of cell content */
47612 u32 nData; /* Number of bytes of data */
47613 u32 nPayload; /* Total amount of payload */
47614 u16 nHeader; /* Size of the cell content header in bytes */
47615 u16 nLocal; /* Amount of payload held locally */
47616 u16 iOverflow; /* Offset to overflow page number. Zero if no overflow */
47617 u16 nSize; /* Size of the cell content on the main b-tree page */
47621 ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
47622 ** this will be declared corrupt. This value is calculated based on a
47623 ** maximum database size of 2^31 pages a minimum fanout of 2 for a
47624 ** root-node and 3 for all other internal nodes.
47626 ** If a tree that appears to be taller than this is encountered, it is
47627 ** assumed that the database is corrupt.
47629 #define BTCURSOR_MAX_DEPTH 20
47632 ** A cursor is a pointer to a particular entry within a particular
47633 ** b-tree within a database file.
47635 ** The entry is identified by its MemPage and the index in
47636 ** MemPage.aCell[] of the entry.
47638 ** A single database file can shared by two more database connections,
47639 ** but cursors cannot be shared. Each cursor is associated with a
47640 ** particular database connection identified BtCursor.pBtree.db.
47642 ** Fields in this structure are accessed under the BtShared.mutex
47643 ** found at self->pBt->mutex.
47645 struct BtCursor {
47646 Btree *pBtree; /* The Btree to which this cursor belongs */
47647 BtShared *pBt; /* The BtShared this cursor points to */
47648 BtCursor *pNext, *pPrev; /* Forms a linked list of all cursors */
47649 struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
47650 Pgno pgnoRoot; /* The root page of this tree */
47651 sqlite3_int64 cachedRowid; /* Next rowid cache. 0 means not valid */
47652 CellInfo info; /* A parse of the cell we are pointing at */
47653 i64 nKey; /* Size of pKey, or last integer key */
47654 void *pKey; /* Saved key that was cursor's last known position */
47655 int skipNext; /* Prev() is noop if negative. Next() is noop if positive */
47656 u8 wrFlag; /* True if writable */
47657 u8 atLast; /* Cursor pointing to the last entry */
47658 u8 validNKey; /* True if info.nKey is valid */
47659 u8 eState; /* One of the CURSOR_XXX constants (see below) */
47660 #ifndef SQLITE_OMIT_INCRBLOB
47661 Pgno *aOverflow; /* Cache of overflow page locations */
47662 u8 isIncrblobHandle; /* True if this cursor is an incr. io handle */
47663 #endif
47664 i16 iPage; /* Index of current page in apPage */
47665 u16 aiIdx[BTCURSOR_MAX_DEPTH]; /* Current index in apPage[i] */
47666 MemPage *apPage[BTCURSOR_MAX_DEPTH]; /* Pages from root to current page */
47670 ** Potential values for BtCursor.eState.
47672 ** CURSOR_VALID:
47673 ** Cursor points to a valid entry. getPayload() etc. may be called.
47675 ** CURSOR_INVALID:
47676 ** Cursor does not point to a valid entry. This can happen (for example)
47677 ** because the table is empty or because BtreeCursorFirst() has not been
47678 ** called.
47680 ** CURSOR_REQUIRESEEK:
47681 ** The table that this cursor was opened on still exists, but has been
47682 ** modified since the cursor was last used. The cursor position is saved
47683 ** in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
47684 ** this state, restoreCursorPosition() can be called to attempt to
47685 ** seek the cursor to the saved position.
47687 ** CURSOR_FAULT:
47688 ** A unrecoverable error (an I/O error or a malloc failure) has occurred
47689 ** on a different connection that shares the BtShared cache with this
47690 ** cursor. The error has left the cache in an inconsistent state.
47691 ** Do nothing else with this cursor. Any attempt to use the cursor
47692 ** should return the error code stored in BtCursor.skip
47694 #define CURSOR_INVALID 0
47695 #define CURSOR_VALID 1
47696 #define CURSOR_REQUIRESEEK 2
47697 #define CURSOR_FAULT 3
47700 ** The database page the PENDING_BYTE occupies. This page is never used.
47702 # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
47705 ** These macros define the location of the pointer-map entry for a
47706 ** database page. The first argument to each is the number of usable
47707 ** bytes on each page of the database (often 1024). The second is the
47708 ** page number to look up in the pointer map.
47710 ** PTRMAP_PAGENO returns the database page number of the pointer-map
47711 ** page that stores the required pointer. PTRMAP_PTROFFSET returns
47712 ** the offset of the requested map entry.
47714 ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
47715 ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
47716 ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
47717 ** this test.
47719 #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
47720 #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
47721 #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
47724 ** The pointer map is a lookup table that identifies the parent page for
47725 ** each child page in the database file. The parent page is the page that
47726 ** contains a pointer to the child. Every page in the database contains
47727 ** 0 or 1 parent pages. (In this context 'database page' refers
47728 ** to any page that is not part of the pointer map itself.) Each pointer map
47729 ** entry consists of a single byte 'type' and a 4 byte parent page number.
47730 ** The PTRMAP_XXX identifiers below are the valid types.
47732 ** The purpose of the pointer map is to facility moving pages from one
47733 ** position in the file to another as part of autovacuum. When a page
47734 ** is moved, the pointer in its parent must be updated to point to the
47735 ** new location. The pointer map is used to locate the parent page quickly.
47737 ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
47738 ** used in this case.
47740 ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
47741 ** is not used in this case.
47743 ** PTRMAP_OVERFLOW1: The database page is the first page in a list of
47744 ** overflow pages. The page number identifies the page that
47745 ** contains the cell with a pointer to this overflow page.
47747 ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
47748 ** overflow pages. The page-number identifies the previous
47749 ** page in the overflow page list.
47751 ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
47752 ** identifies the parent page in the btree.
47754 #define PTRMAP_ROOTPAGE 1
47755 #define PTRMAP_FREEPAGE 2
47756 #define PTRMAP_OVERFLOW1 3
47757 #define PTRMAP_OVERFLOW2 4
47758 #define PTRMAP_BTREE 5
47760 /* A bunch of assert() statements to check the transaction state variables
47761 ** of handle p (type Btree*) are internally consistent.
47763 #define btreeIntegrity(p) \
47764 assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
47765 assert( p->pBt->inTransaction>=p->inTrans );
47769 ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
47770 ** if the database supports auto-vacuum or not. Because it is used
47771 ** within an expression that is an argument to another macro
47772 ** (sqliteMallocRaw), it is not possible to use conditional compilation.
47773 ** So, this macro is defined instead.
47775 #ifndef SQLITE_OMIT_AUTOVACUUM
47776 #define ISAUTOVACUUM (pBt->autoVacuum)
47777 #else
47778 #define ISAUTOVACUUM 0
47779 #endif
47783 ** This structure is passed around through all the sanity checking routines
47784 ** in order to keep track of some global state information.
47786 typedef struct IntegrityCk IntegrityCk;
47787 struct IntegrityCk {
47788 BtShared *pBt; /* The tree being checked out */
47789 Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
47790 Pgno nPage; /* Number of pages in the database */
47791 int *anRef; /* Number of times each page is referenced */
47792 int mxErr; /* Stop accumulating errors when this reaches zero */
47793 int nErr; /* Number of messages written to zErrMsg so far */
47794 int mallocFailed; /* A memory allocation error has occurred */
47795 StrAccum errMsg; /* Accumulate the error message text here */
47799 ** Read or write a two- and four-byte big-endian integer values.
47801 #define get2byte(x) ((x)[0]<<8 | (x)[1])
47802 #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
47803 #define get4byte sqlite3Get4byte
47804 #define put4byte sqlite3Put4byte
47806 /************** End of btreeInt.h ********************************************/
47807 /************** Continuing where we left off in btmutex.c ********************/
47808 #ifndef SQLITE_OMIT_SHARED_CACHE
47809 #if SQLITE_THREADSAFE
47812 ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
47813 ** set BtShared.db to the database handle associated with p and the
47814 ** p->locked boolean to true.
47816 static void lockBtreeMutex(Btree *p){
47817 assert( p->locked==0 );
47818 assert( sqlite3_mutex_notheld(p->pBt->mutex) );
47819 assert( sqlite3_mutex_held(p->db->mutex) );
47821 sqlite3_mutex_enter(p->pBt->mutex);
47822 p->pBt->db = p->db;
47823 p->locked = 1;
47827 ** Release the BtShared mutex associated with B-Tree handle p and
47828 ** clear the p->locked boolean.
47830 static void unlockBtreeMutex(Btree *p){
47831 BtShared *pBt = p->pBt;
47832 assert( p->locked==1 );
47833 assert( sqlite3_mutex_held(pBt->mutex) );
47834 assert( sqlite3_mutex_held(p->db->mutex) );
47835 assert( p->db==pBt->db );
47837 sqlite3_mutex_leave(pBt->mutex);
47838 p->locked = 0;
47842 ** Enter a mutex on the given BTree object.
47844 ** If the object is not sharable, then no mutex is ever required
47845 ** and this routine is a no-op. The underlying mutex is non-recursive.
47846 ** But we keep a reference count in Btree.wantToLock so the behavior
47847 ** of this interface is recursive.
47849 ** To avoid deadlocks, multiple Btrees are locked in the same order
47850 ** by all database connections. The p->pNext is a list of other
47851 ** Btrees belonging to the same database connection as the p Btree
47852 ** which need to be locked after p. If we cannot get a lock on
47853 ** p, then first unlock all of the others on p->pNext, then wait
47854 ** for the lock to become available on p, then relock all of the
47855 ** subsequent Btrees that desire a lock.
47857 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
47858 Btree *pLater;
47860 /* Some basic sanity checking on the Btree. The list of Btrees
47861 ** connected by pNext and pPrev should be in sorted order by
47862 ** Btree.pBt value. All elements of the list should belong to
47863 ** the same connection. Only shared Btrees are on the list. */
47864 assert( p->pNext==0 || p->pNext->pBt>p->pBt );
47865 assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
47866 assert( p->pNext==0 || p->pNext->db==p->db );
47867 assert( p->pPrev==0 || p->pPrev->db==p->db );
47868 assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
47870 /* Check for locking consistency */
47871 assert( !p->locked || p->wantToLock>0 );
47872 assert( p->sharable || p->wantToLock==0 );
47874 /* We should already hold a lock on the database connection */
47875 assert( sqlite3_mutex_held(p->db->mutex) );
47877 /* Unless the database is sharable and unlocked, then BtShared.db
47878 ** should already be set correctly. */
47879 assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
47881 if( !p->sharable ) return;
47882 p->wantToLock++;
47883 if( p->locked ) return;
47885 /* In most cases, we should be able to acquire the lock we
47886 ** want without having to go throught the ascending lock
47887 ** procedure that follows. Just be sure not to block.
47889 if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
47890 p->pBt->db = p->db;
47891 p->locked = 1;
47892 return;
47895 /* To avoid deadlock, first release all locks with a larger
47896 ** BtShared address. Then acquire our lock. Then reacquire
47897 ** the other BtShared locks that we used to hold in ascending
47898 ** order.
47900 for(pLater=p->pNext; pLater; pLater=pLater->pNext){
47901 assert( pLater->sharable );
47902 assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
47903 assert( !pLater->locked || pLater->wantToLock>0 );
47904 if( pLater->locked ){
47905 unlockBtreeMutex(pLater);
47908 lockBtreeMutex(p);
47909 for(pLater=p->pNext; pLater; pLater=pLater->pNext){
47910 if( pLater->wantToLock ){
47911 lockBtreeMutex(pLater);
47917 ** Exit the recursive mutex on a Btree.
47919 SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
47920 if( p->sharable ){
47921 assert( p->wantToLock>0 );
47922 p->wantToLock--;
47923 if( p->wantToLock==0 ){
47924 unlockBtreeMutex(p);
47929 #ifndef NDEBUG
47931 ** Return true if the BtShared mutex is held on the btree, or if the
47932 ** B-Tree is not marked as sharable.
47934 ** This routine is used only from within assert() statements.
47936 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
47937 assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
47938 assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
47939 assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
47940 assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
47942 return (p->sharable==0 || p->locked);
47944 #endif
47947 #ifndef SQLITE_OMIT_INCRBLOB
47949 ** Enter and leave a mutex on a Btree given a cursor owned by that
47950 ** Btree. These entry points are used by incremental I/O and can be
47951 ** omitted if that module is not used.
47953 SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
47954 sqlite3BtreeEnter(pCur->pBtree);
47956 SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
47957 sqlite3BtreeLeave(pCur->pBtree);
47959 #endif /* SQLITE_OMIT_INCRBLOB */
47963 ** Enter the mutex on every Btree associated with a database
47964 ** connection. This is needed (for example) prior to parsing
47965 ** a statement since we will be comparing table and column names
47966 ** against all schemas and we do not want those schemas being
47967 ** reset out from under us.
47969 ** There is a corresponding leave-all procedures.
47971 ** Enter the mutexes in accending order by BtShared pointer address
47972 ** to avoid the possibility of deadlock when two threads with
47973 ** two or more btrees in common both try to lock all their btrees
47974 ** at the same instant.
47976 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
47977 int i;
47978 Btree *p;
47979 assert( sqlite3_mutex_held(db->mutex) );
47980 for(i=0; i<db->nDb; i++){
47981 p = db->aDb[i].pBt;
47982 if( p ) sqlite3BtreeEnter(p);
47985 SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
47986 int i;
47987 Btree *p;
47988 assert( sqlite3_mutex_held(db->mutex) );
47989 for(i=0; i<db->nDb; i++){
47990 p = db->aDb[i].pBt;
47991 if( p ) sqlite3BtreeLeave(p);
47996 ** Return true if a particular Btree requires a lock. Return FALSE if
47997 ** no lock is ever required since it is not sharable.
47999 SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
48000 return p->sharable;
48003 #ifndef NDEBUG
48005 ** Return true if the current thread holds the database connection
48006 ** mutex and all required BtShared mutexes.
48008 ** This routine is used inside assert() statements only.
48010 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
48011 int i;
48012 if( !sqlite3_mutex_held(db->mutex) ){
48013 return 0;
48015 for(i=0; i<db->nDb; i++){
48016 Btree *p;
48017 p = db->aDb[i].pBt;
48018 if( p && p->sharable &&
48019 (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
48020 return 0;
48023 return 1;
48025 #endif /* NDEBUG */
48027 #ifndef NDEBUG
48029 ** Return true if the correct mutexes are held for accessing the
48030 ** db->aDb[iDb].pSchema structure. The mutexes required for schema
48031 ** access are:
48033 ** (1) The mutex on db
48034 ** (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
48036 ** If pSchema is not NULL, then iDb is computed from pSchema and
48037 ** db using sqlite3SchemaToIndex().
48039 SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
48040 Btree *p;
48041 assert( db!=0 );
48042 if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
48043 assert( iDb>=0 && iDb<db->nDb );
48044 if( !sqlite3_mutex_held(db->mutex) ) return 0;
48045 if( iDb==1 ) return 1;
48046 p = db->aDb[iDb].pBt;
48047 assert( p!=0 );
48048 return p->sharable==0 || p->locked==1;
48050 #endif /* NDEBUG */
48052 #else /* SQLITE_THREADSAFE>0 above. SQLITE_THREADSAFE==0 below */
48054 ** The following are special cases for mutex enter routines for use
48055 ** in single threaded applications that use shared cache. Except for
48056 ** these two routines, all mutex operations are no-ops in that case and
48057 ** are null #defines in btree.h.
48059 ** If shared cache is disabled, then all btree mutex routines, including
48060 ** the ones below, are no-ops and are null #defines in btree.h.
48063 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
48064 p->pBt->db = p->db;
48066 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
48067 int i;
48068 for(i=0; i<db->nDb; i++){
48069 Btree *p = db->aDb[i].pBt;
48070 if( p ){
48071 p->pBt->db = p->db;
48075 #endif /* if SQLITE_THREADSAFE */
48076 #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
48078 /************** End of btmutex.c *********************************************/
48079 /************** Begin file btree.c *******************************************/
48081 ** 2004 April 6
48083 ** The author disclaims copyright to this source code. In place of
48084 ** a legal notice, here is a blessing:
48086 ** May you do good and not evil.
48087 ** May you find forgiveness for yourself and forgive others.
48088 ** May you share freely, never taking more than you give.
48090 *************************************************************************
48091 ** This file implements a external (disk-based) database using BTrees.
48092 ** See the header comment on "btreeInt.h" for additional information.
48093 ** Including a description of file format and an overview of operation.
48097 ** The header string that appears at the beginning of every
48098 ** SQLite database.
48100 static const char zMagicHeader[] = SQLITE_FILE_HEADER;
48103 ** Set this global variable to 1 to enable tracing using the TRACE
48104 ** macro.
48106 #if 0
48107 int sqlite3BtreeTrace=1; /* True to enable tracing */
48108 # define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);}
48109 #else
48110 # define TRACE(X)
48111 #endif
48114 ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
48115 ** But if the value is zero, make it 65536.
48117 ** This routine is used to extract the "offset to cell content area" value
48118 ** from the header of a btree page. If the page size is 65536 and the page
48119 ** is empty, the offset should be 65536, but the 2-byte value stores zero.
48120 ** This routine makes the necessary adjustment to 65536.
48122 #define get2byteNotZero(X) (((((int)get2byte(X))-1)&0xffff)+1)
48124 #ifndef SQLITE_OMIT_SHARED_CACHE
48126 ** A list of BtShared objects that are eligible for participation
48127 ** in shared cache. This variable has file scope during normal builds,
48128 ** but the test harness needs to access it so we make it global for
48129 ** test builds.
48131 ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
48133 #ifdef SQLITE_TEST
48134 SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
48135 #else
48136 static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
48137 #endif
48138 #endif /* SQLITE_OMIT_SHARED_CACHE */
48140 #ifndef SQLITE_OMIT_SHARED_CACHE
48142 ** Enable or disable the shared pager and schema features.
48144 ** This routine has no effect on existing database connections.
48145 ** The shared cache setting effects only future calls to
48146 ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
48148 SQLITE_API int sqlite3_enable_shared_cache(int enable){
48149 sqlite3GlobalConfig.sharedCacheEnabled = enable;
48150 return SQLITE_OK;
48152 #endif
48156 #ifdef SQLITE_OMIT_SHARED_CACHE
48158 ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
48159 ** and clearAllSharedCacheTableLocks()
48160 ** manipulate entries in the BtShared.pLock linked list used to store
48161 ** shared-cache table level locks. If the library is compiled with the
48162 ** shared-cache feature disabled, then there is only ever one user
48163 ** of each BtShared structure and so this locking is not necessary.
48164 ** So define the lock related functions as no-ops.
48166 #define querySharedCacheTableLock(a,b,c) SQLITE_OK
48167 #define setSharedCacheTableLock(a,b,c) SQLITE_OK
48168 #define clearAllSharedCacheTableLocks(a)
48169 #define downgradeAllSharedCacheTableLocks(a)
48170 #define hasSharedCacheTableLock(a,b,c,d) 1
48171 #define hasReadConflicts(a, b) 0
48172 #endif
48174 #ifndef SQLITE_OMIT_SHARED_CACHE
48176 #ifdef SQLITE_DEBUG
48178 **** This function is only used as part of an assert() statement. ***
48180 ** Check to see if pBtree holds the required locks to read or write to the
48181 ** table with root page iRoot. Return 1 if it does and 0 if not.
48183 ** For example, when writing to a table with root-page iRoot via
48184 ** Btree connection pBtree:
48186 ** assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
48188 ** When writing to an index that resides in a sharable database, the
48189 ** caller should have first obtained a lock specifying the root page of
48190 ** the corresponding table. This makes things a bit more complicated,
48191 ** as this module treats each table as a separate structure. To determine
48192 ** the table corresponding to the index being written, this
48193 ** function has to search through the database schema.
48195 ** Instead of a lock on the table/index rooted at page iRoot, the caller may
48196 ** hold a write-lock on the schema table (root page 1). This is also
48197 ** acceptable.
48199 static int hasSharedCacheTableLock(
48200 Btree *pBtree, /* Handle that must hold lock */
48201 Pgno iRoot, /* Root page of b-tree */
48202 int isIndex, /* True if iRoot is the root of an index b-tree */
48203 int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */
48205 Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
48206 Pgno iTab = 0;
48207 BtLock *pLock;
48209 /* If this database is not shareable, or if the client is reading
48210 ** and has the read-uncommitted flag set, then no lock is required.
48211 ** Return true immediately.
48213 if( (pBtree->sharable==0)
48214 || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
48216 return 1;
48219 /* If the client is reading or writing an index and the schema is
48220 ** not loaded, then it is too difficult to actually check to see if
48221 ** the correct locks are held. So do not bother - just return true.
48222 ** This case does not come up very often anyhow.
48224 if( isIndex && (!pSchema || (pSchema->flags&DB_SchemaLoaded)==0) ){
48225 return 1;
48228 /* Figure out the root-page that the lock should be held on. For table
48229 ** b-trees, this is just the root page of the b-tree being read or
48230 ** written. For index b-trees, it is the root page of the associated
48231 ** table. */
48232 if( isIndex ){
48233 HashElem *p;
48234 for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
48235 Index *pIdx = (Index *)sqliteHashData(p);
48236 if( pIdx->tnum==(int)iRoot ){
48237 iTab = pIdx->pTable->tnum;
48240 }else{
48241 iTab = iRoot;
48244 /* Search for the required lock. Either a write-lock on root-page iTab, a
48245 ** write-lock on the schema table, or (if the client is reading) a
48246 ** read-lock on iTab will suffice. Return 1 if any of these are found. */
48247 for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
48248 if( pLock->pBtree==pBtree
48249 && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
48250 && pLock->eLock>=eLockType
48252 return 1;
48256 /* Failed to find the required lock. */
48257 return 0;
48259 #endif /* SQLITE_DEBUG */
48261 #ifdef SQLITE_DEBUG
48263 **** This function may be used as part of assert() statements only. ****
48265 ** Return true if it would be illegal for pBtree to write into the
48266 ** table or index rooted at iRoot because other shared connections are
48267 ** simultaneously reading that same table or index.
48269 ** It is illegal for pBtree to write if some other Btree object that
48270 ** shares the same BtShared object is currently reading or writing
48271 ** the iRoot table. Except, if the other Btree object has the
48272 ** read-uncommitted flag set, then it is OK for the other object to
48273 ** have a read cursor.
48275 ** For example, before writing to any part of the table or index
48276 ** rooted at page iRoot, one should call:
48278 ** assert( !hasReadConflicts(pBtree, iRoot) );
48280 static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
48281 BtCursor *p;
48282 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
48283 if( p->pgnoRoot==iRoot
48284 && p->pBtree!=pBtree
48285 && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
48287 return 1;
48290 return 0;
48292 #endif /* #ifdef SQLITE_DEBUG */
48295 ** Query to see if Btree handle p may obtain a lock of type eLock
48296 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
48297 ** SQLITE_OK if the lock may be obtained (by calling
48298 ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
48300 static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
48301 BtShared *pBt = p->pBt;
48302 BtLock *pIter;
48304 assert( sqlite3BtreeHoldsMutex(p) );
48305 assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
48306 assert( p->db!=0 );
48307 assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
48309 /* If requesting a write-lock, then the Btree must have an open write
48310 ** transaction on this file. And, obviously, for this to be so there
48311 ** must be an open write transaction on the file itself.
48313 assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
48314 assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
48316 /* This routine is a no-op if the shared-cache is not enabled */
48317 if( !p->sharable ){
48318 return SQLITE_OK;
48321 /* If some other connection is holding an exclusive lock, the
48322 ** requested lock may not be obtained.
48324 if( pBt->pWriter!=p && pBt->isExclusive ){
48325 sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
48326 return SQLITE_LOCKED_SHAREDCACHE;
48329 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
48330 /* The condition (pIter->eLock!=eLock) in the following if(...)
48331 ** statement is a simplification of:
48333 ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
48335 ** since we know that if eLock==WRITE_LOCK, then no other connection
48336 ** may hold a WRITE_LOCK on any table in this file (since there can
48337 ** only be a single writer).
48339 assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
48340 assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
48341 if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
48342 sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
48343 if( eLock==WRITE_LOCK ){
48344 assert( p==pBt->pWriter );
48345 pBt->isPending = 1;
48347 return SQLITE_LOCKED_SHAREDCACHE;
48350 return SQLITE_OK;
48352 #endif /* !SQLITE_OMIT_SHARED_CACHE */
48354 #ifndef SQLITE_OMIT_SHARED_CACHE
48356 ** Add a lock on the table with root-page iTable to the shared-btree used
48357 ** by Btree handle p. Parameter eLock must be either READ_LOCK or
48358 ** WRITE_LOCK.
48360 ** This function assumes the following:
48362 ** (a) The specified Btree object p is connected to a sharable
48363 ** database (one with the BtShared.sharable flag set), and
48365 ** (b) No other Btree objects hold a lock that conflicts
48366 ** with the requested lock (i.e. querySharedCacheTableLock() has
48367 ** already been called and returned SQLITE_OK).
48369 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
48370 ** is returned if a malloc attempt fails.
48372 static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
48373 BtShared *pBt = p->pBt;
48374 BtLock *pLock = 0;
48375 BtLock *pIter;
48377 assert( sqlite3BtreeHoldsMutex(p) );
48378 assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
48379 assert( p->db!=0 );
48381 /* A connection with the read-uncommitted flag set will never try to
48382 ** obtain a read-lock using this function. The only read-lock obtained
48383 ** by a connection in read-uncommitted mode is on the sqlite_master
48384 ** table, and that lock is obtained in BtreeBeginTrans(). */
48385 assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
48387 /* This function should only be called on a sharable b-tree after it
48388 ** has been determined that no other b-tree holds a conflicting lock. */
48389 assert( p->sharable );
48390 assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
48392 /* First search the list for an existing lock on this table. */
48393 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
48394 if( pIter->iTable==iTable && pIter->pBtree==p ){
48395 pLock = pIter;
48396 break;
48400 /* If the above search did not find a BtLock struct associating Btree p
48401 ** with table iTable, allocate one and link it into the list.
48403 if( !pLock ){
48404 pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
48405 if( !pLock ){
48406 return SQLITE_NOMEM;
48408 pLock->iTable = iTable;
48409 pLock->pBtree = p;
48410 pLock->pNext = pBt->pLock;
48411 pBt->pLock = pLock;
48414 /* Set the BtLock.eLock variable to the maximum of the current lock
48415 ** and the requested lock. This means if a write-lock was already held
48416 ** and a read-lock requested, we don't incorrectly downgrade the lock.
48418 assert( WRITE_LOCK>READ_LOCK );
48419 if( eLock>pLock->eLock ){
48420 pLock->eLock = eLock;
48423 return SQLITE_OK;
48425 #endif /* !SQLITE_OMIT_SHARED_CACHE */
48427 #ifndef SQLITE_OMIT_SHARED_CACHE
48429 ** Release all the table locks (locks obtained via calls to
48430 ** the setSharedCacheTableLock() procedure) held by Btree object p.
48432 ** This function assumes that Btree p has an open read or write
48433 ** transaction. If it does not, then the BtShared.isPending variable
48434 ** may be incorrectly cleared.
48436 static void clearAllSharedCacheTableLocks(Btree *p){
48437 BtShared *pBt = p->pBt;
48438 BtLock **ppIter = &pBt->pLock;
48440 assert( sqlite3BtreeHoldsMutex(p) );
48441 assert( p->sharable || 0==*ppIter );
48442 assert( p->inTrans>0 );
48444 while( *ppIter ){
48445 BtLock *pLock = *ppIter;
48446 assert( pBt->isExclusive==0 || pBt->pWriter==pLock->pBtree );
48447 assert( pLock->pBtree->inTrans>=pLock->eLock );
48448 if( pLock->pBtree==p ){
48449 *ppIter = pLock->pNext;
48450 assert( pLock->iTable!=1 || pLock==&p->lock );
48451 if( pLock->iTable!=1 ){
48452 sqlite3_free(pLock);
48454 }else{
48455 ppIter = &pLock->pNext;
48459 assert( pBt->isPending==0 || pBt->pWriter );
48460 if( pBt->pWriter==p ){
48461 pBt->pWriter = 0;
48462 pBt->isExclusive = 0;
48463 pBt->isPending = 0;
48464 }else if( pBt->nTransaction==2 ){
48465 /* This function is called when Btree p is concluding its
48466 ** transaction. If there currently exists a writer, and p is not
48467 ** that writer, then the number of locks held by connections other
48468 ** than the writer must be about to drop to zero. In this case
48469 ** set the isPending flag to 0.
48471 ** If there is not currently a writer, then BtShared.isPending must
48472 ** be zero already. So this next line is harmless in that case.
48474 pBt->isPending = 0;
48479 ** This function changes all write-locks held by Btree p into read-locks.
48481 static void downgradeAllSharedCacheTableLocks(Btree *p){
48482 BtShared *pBt = p->pBt;
48483 if( pBt->pWriter==p ){
48484 BtLock *pLock;
48485 pBt->pWriter = 0;
48486 pBt->isExclusive = 0;
48487 pBt->isPending = 0;
48488 for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
48489 assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
48490 pLock->eLock = READ_LOCK;
48495 #endif /* SQLITE_OMIT_SHARED_CACHE */
48497 static void releasePage(MemPage *pPage); /* Forward reference */
48500 ***** This routine is used inside of assert() only ****
48502 ** Verify that the cursor holds the mutex on its BtShared
48504 #ifdef SQLITE_DEBUG
48505 static int cursorHoldsMutex(BtCursor *p){
48506 return sqlite3_mutex_held(p->pBt->mutex);
48508 #endif
48511 #ifndef SQLITE_OMIT_INCRBLOB
48513 ** Invalidate the overflow page-list cache for cursor pCur, if any.
48515 static void invalidateOverflowCache(BtCursor *pCur){
48516 assert( cursorHoldsMutex(pCur) );
48517 sqlite3_free(pCur->aOverflow);
48518 pCur->aOverflow = 0;
48522 ** Invalidate the overflow page-list cache for all cursors opened
48523 ** on the shared btree structure pBt.
48525 static void invalidateAllOverflowCache(BtShared *pBt){
48526 BtCursor *p;
48527 assert( sqlite3_mutex_held(pBt->mutex) );
48528 for(p=pBt->pCursor; p; p=p->pNext){
48529 invalidateOverflowCache(p);
48534 ** This function is called before modifying the contents of a table
48535 ** to invalidate any incrblob cursors that are open on the
48536 ** row or one of the rows being modified.
48538 ** If argument isClearTable is true, then the entire contents of the
48539 ** table is about to be deleted. In this case invalidate all incrblob
48540 ** cursors open on any row within the table with root-page pgnoRoot.
48542 ** Otherwise, if argument isClearTable is false, then the row with
48543 ** rowid iRow is being replaced or deleted. In this case invalidate
48544 ** only those incrblob cursors open on that specific row.
48546 static void invalidateIncrblobCursors(
48547 Btree *pBtree, /* The database file to check */
48548 i64 iRow, /* The rowid that might be changing */
48549 int isClearTable /* True if all rows are being deleted */
48551 BtCursor *p;
48552 BtShared *pBt = pBtree->pBt;
48553 assert( sqlite3BtreeHoldsMutex(pBtree) );
48554 for(p=pBt->pCursor; p; p=p->pNext){
48555 if( p->isIncrblobHandle && (isClearTable || p->info.nKey==iRow) ){
48556 p->eState = CURSOR_INVALID;
48561 #else
48562 /* Stub functions when INCRBLOB is omitted */
48563 #define invalidateOverflowCache(x)
48564 #define invalidateAllOverflowCache(x)
48565 #define invalidateIncrblobCursors(x,y,z)
48566 #endif /* SQLITE_OMIT_INCRBLOB */
48569 ** Set bit pgno of the BtShared.pHasContent bitvec. This is called
48570 ** when a page that previously contained data becomes a free-list leaf
48571 ** page.
48573 ** The BtShared.pHasContent bitvec exists to work around an obscure
48574 ** bug caused by the interaction of two useful IO optimizations surrounding
48575 ** free-list leaf pages:
48577 ** 1) When all data is deleted from a page and the page becomes
48578 ** a free-list leaf page, the page is not written to the database
48579 ** (as free-list leaf pages contain no meaningful data). Sometimes
48580 ** such a page is not even journalled (as it will not be modified,
48581 ** why bother journalling it?).
48583 ** 2) When a free-list leaf page is reused, its content is not read
48584 ** from the database or written to the journal file (why should it
48585 ** be, if it is not at all meaningful?).
48587 ** By themselves, these optimizations work fine and provide a handy
48588 ** performance boost to bulk delete or insert operations. However, if
48589 ** a page is moved to the free-list and then reused within the same
48590 ** transaction, a problem comes up. If the page is not journalled when
48591 ** it is moved to the free-list and it is also not journalled when it
48592 ** is extracted from the free-list and reused, then the original data
48593 ** may be lost. In the event of a rollback, it may not be possible
48594 ** to restore the database to its original configuration.
48596 ** The solution is the BtShared.pHasContent bitvec. Whenever a page is
48597 ** moved to become a free-list leaf page, the corresponding bit is
48598 ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
48599 ** optimization 2 above is omitted if the corresponding bit is already
48600 ** set in BtShared.pHasContent. The contents of the bitvec are cleared
48601 ** at the end of every transaction.
48603 static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
48604 int rc = SQLITE_OK;
48605 if( !pBt->pHasContent ){
48606 assert( pgno<=pBt->nPage );
48607 pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
48608 if( !pBt->pHasContent ){
48609 rc = SQLITE_NOMEM;
48612 if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
48613 rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
48615 return rc;
48619 ** Query the BtShared.pHasContent vector.
48621 ** This function is called when a free-list leaf page is removed from the
48622 ** free-list for reuse. It returns false if it is safe to retrieve the
48623 ** page from the pager layer with the 'no-content' flag set. True otherwise.
48625 static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
48626 Bitvec *p = pBt->pHasContent;
48627 return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
48631 ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
48632 ** invoked at the conclusion of each write-transaction.
48634 static void btreeClearHasContent(BtShared *pBt){
48635 sqlite3BitvecDestroy(pBt->pHasContent);
48636 pBt->pHasContent = 0;
48640 ** Save the current cursor position in the variables BtCursor.nKey
48641 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
48643 ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
48644 ** prior to calling this routine.
48646 static int saveCursorPosition(BtCursor *pCur){
48647 int rc;
48649 assert( CURSOR_VALID==pCur->eState );
48650 assert( 0==pCur->pKey );
48651 assert( cursorHoldsMutex(pCur) );
48653 rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
48654 assert( rc==SQLITE_OK ); /* KeySize() cannot fail */
48656 /* If this is an intKey table, then the above call to BtreeKeySize()
48657 ** stores the integer key in pCur->nKey. In this case this value is
48658 ** all that is required. Otherwise, if pCur is not open on an intKey
48659 ** table, then malloc space for and store the pCur->nKey bytes of key
48660 ** data.
48662 if( 0==pCur->apPage[0]->intKey ){
48663 void *pKey = sqlite3Malloc( (int)pCur->nKey );
48664 if( pKey ){
48665 rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
48666 if( rc==SQLITE_OK ){
48667 pCur->pKey = pKey;
48668 }else{
48669 sqlite3_free(pKey);
48671 }else{
48672 rc = SQLITE_NOMEM;
48675 assert( !pCur->apPage[0]->intKey || !pCur->pKey );
48677 if( rc==SQLITE_OK ){
48678 int i;
48679 for(i=0; i<=pCur->iPage; i++){
48680 releasePage(pCur->apPage[i]);
48681 pCur->apPage[i] = 0;
48683 pCur->iPage = -1;
48684 pCur->eState = CURSOR_REQUIRESEEK;
48687 invalidateOverflowCache(pCur);
48688 return rc;
48692 ** Save the positions of all cursors (except pExcept) that are open on
48693 ** the table with root-page iRoot. Usually, this is called just before cursor
48694 ** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
48696 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
48697 BtCursor *p;
48698 assert( sqlite3_mutex_held(pBt->mutex) );
48699 assert( pExcept==0 || pExcept->pBt==pBt );
48700 for(p=pBt->pCursor; p; p=p->pNext){
48701 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) &&
48702 p->eState==CURSOR_VALID ){
48703 int rc = saveCursorPosition(p);
48704 if( SQLITE_OK!=rc ){
48705 return rc;
48709 return SQLITE_OK;
48713 ** Clear the current cursor position.
48715 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
48716 assert( cursorHoldsMutex(pCur) );
48717 sqlite3_free(pCur->pKey);
48718 pCur->pKey = 0;
48719 pCur->eState = CURSOR_INVALID;
48723 ** In this version of BtreeMoveto, pKey is a packed index record
48724 ** such as is generated by the OP_MakeRecord opcode. Unpack the
48725 ** record and then call BtreeMovetoUnpacked() to do the work.
48727 static int btreeMoveto(
48728 BtCursor *pCur, /* Cursor open on the btree to be searched */
48729 const void *pKey, /* Packed key if the btree is an index */
48730 i64 nKey, /* Integer key for tables. Size of pKey for indices */
48731 int bias, /* Bias search to the high end */
48732 int *pRes /* Write search results here */
48734 int rc; /* Status code */
48735 UnpackedRecord *pIdxKey; /* Unpacked index key */
48736 char aSpace[150]; /* Temp space for pIdxKey - to avoid a malloc */
48737 char *pFree = 0;
48739 if( pKey ){
48740 assert( nKey==(i64)(int)nKey );
48741 pIdxKey = sqlite3VdbeAllocUnpackedRecord(
48742 pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree
48744 if( pIdxKey==0 ) return SQLITE_NOMEM;
48745 sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
48746 }else{
48747 pIdxKey = 0;
48749 rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
48750 if( pFree ){
48751 sqlite3DbFree(pCur->pKeyInfo->db, pFree);
48753 return rc;
48757 ** Restore the cursor to the position it was in (or as close to as possible)
48758 ** when saveCursorPosition() was called. Note that this call deletes the
48759 ** saved position info stored by saveCursorPosition(), so there can be
48760 ** at most one effective restoreCursorPosition() call after each
48761 ** saveCursorPosition().
48763 static int btreeRestoreCursorPosition(BtCursor *pCur){
48764 int rc;
48765 assert( cursorHoldsMutex(pCur) );
48766 assert( pCur->eState>=CURSOR_REQUIRESEEK );
48767 if( pCur->eState==CURSOR_FAULT ){
48768 return pCur->skipNext;
48770 pCur->eState = CURSOR_INVALID;
48771 rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
48772 if( rc==SQLITE_OK ){
48773 sqlite3_free(pCur->pKey);
48774 pCur->pKey = 0;
48775 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
48777 return rc;
48780 #define restoreCursorPosition(p) \
48781 (p->eState>=CURSOR_REQUIRESEEK ? \
48782 btreeRestoreCursorPosition(p) : \
48783 SQLITE_OK)
48786 ** Determine whether or not a cursor has moved from the position it
48787 ** was last placed at. Cursors can move when the row they are pointing
48788 ** at is deleted out from under them.
48790 ** This routine returns an error code if something goes wrong. The
48791 ** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
48793 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
48794 int rc;
48796 rc = restoreCursorPosition(pCur);
48797 if( rc ){
48798 *pHasMoved = 1;
48799 return rc;
48801 if( pCur->eState!=CURSOR_VALID || pCur->skipNext!=0 ){
48802 *pHasMoved = 1;
48803 }else{
48804 *pHasMoved = 0;
48806 return SQLITE_OK;
48809 #ifndef SQLITE_OMIT_AUTOVACUUM
48811 ** Given a page number of a regular database page, return the page
48812 ** number for the pointer-map page that contains the entry for the
48813 ** input page number.
48815 ** Return 0 (not a valid page) for pgno==1 since there is
48816 ** no pointer map associated with page 1. The integrity_check logic
48817 ** requires that ptrmapPageno(*,1)!=1.
48819 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
48820 int nPagesPerMapPage;
48821 Pgno iPtrMap, ret;
48822 assert( sqlite3_mutex_held(pBt->mutex) );
48823 if( pgno<2 ) return 0;
48824 nPagesPerMapPage = (pBt->usableSize/5)+1;
48825 iPtrMap = (pgno-2)/nPagesPerMapPage;
48826 ret = (iPtrMap*nPagesPerMapPage) + 2;
48827 if( ret==PENDING_BYTE_PAGE(pBt) ){
48828 ret++;
48830 return ret;
48834 ** Write an entry into the pointer map.
48836 ** This routine updates the pointer map entry for page number 'key'
48837 ** so that it maps to type 'eType' and parent page number 'pgno'.
48839 ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
48840 ** a no-op. If an error occurs, the appropriate error code is written
48841 ** into *pRC.
48843 static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
48844 DbPage *pDbPage; /* The pointer map page */
48845 u8 *pPtrmap; /* The pointer map data */
48846 Pgno iPtrmap; /* The pointer map page number */
48847 int offset; /* Offset in pointer map page */
48848 int rc; /* Return code from subfunctions */
48850 if( *pRC ) return;
48852 assert( sqlite3_mutex_held(pBt->mutex) );
48853 /* The master-journal page number must never be used as a pointer map page */
48854 assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
48856 assert( pBt->autoVacuum );
48857 if( key==0 ){
48858 *pRC = SQLITE_CORRUPT_BKPT;
48859 return;
48861 iPtrmap = PTRMAP_PAGENO(pBt, key);
48862 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
48863 if( rc!=SQLITE_OK ){
48864 *pRC = rc;
48865 return;
48867 offset = PTRMAP_PTROFFSET(iPtrmap, key);
48868 if( offset<0 ){
48869 *pRC = SQLITE_CORRUPT_BKPT;
48870 goto ptrmap_exit;
48872 assert( offset <= (int)pBt->usableSize-5 );
48873 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
48875 if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
48876 TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
48877 *pRC= rc = sqlite3PagerWrite(pDbPage);
48878 if( rc==SQLITE_OK ){
48879 pPtrmap[offset] = eType;
48880 put4byte(&pPtrmap[offset+1], parent);
48884 ptrmap_exit:
48885 sqlite3PagerUnref(pDbPage);
48889 ** Read an entry from the pointer map.
48891 ** This routine retrieves the pointer map entry for page 'key', writing
48892 ** the type and parent page number to *pEType and *pPgno respectively.
48893 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
48895 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
48896 DbPage *pDbPage; /* The pointer map page */
48897 int iPtrmap; /* Pointer map page index */
48898 u8 *pPtrmap; /* Pointer map page data */
48899 int offset; /* Offset of entry in pointer map */
48900 int rc;
48902 assert( sqlite3_mutex_held(pBt->mutex) );
48904 iPtrmap = PTRMAP_PAGENO(pBt, key);
48905 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
48906 if( rc!=0 ){
48907 return rc;
48909 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
48911 offset = PTRMAP_PTROFFSET(iPtrmap, key);
48912 if( offset<0 ){
48913 sqlite3PagerUnref(pDbPage);
48914 return SQLITE_CORRUPT_BKPT;
48916 assert( offset <= (int)pBt->usableSize-5 );
48917 assert( pEType!=0 );
48918 *pEType = pPtrmap[offset];
48919 if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
48921 sqlite3PagerUnref(pDbPage);
48922 if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
48923 return SQLITE_OK;
48926 #else /* if defined SQLITE_OMIT_AUTOVACUUM */
48927 #define ptrmapPut(w,x,y,z,rc)
48928 #define ptrmapGet(w,x,y,z) SQLITE_OK
48929 #define ptrmapPutOvflPtr(x, y, rc)
48930 #endif
48933 ** Given a btree page and a cell index (0 means the first cell on
48934 ** the page, 1 means the second cell, and so forth) return a pointer
48935 ** to the cell content.
48937 ** This routine works only for pages that do not contain overflow cells.
48939 #define findCell(P,I) \
48940 ((P)->aData + ((P)->maskPage & get2byte(&(P)->aData[(P)->cellOffset+2*(I)])))
48941 #define findCellv2(D,M,O,I) (D+(M&get2byte(D+(O+2*(I)))))
48945 ** This a more complex version of findCell() that works for
48946 ** pages that do contain overflow cells.
48948 static u8 *findOverflowCell(MemPage *pPage, int iCell){
48949 int i;
48950 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48951 for(i=pPage->nOverflow-1; i>=0; i--){
48952 int k;
48953 struct _OvflCell *pOvfl;
48954 pOvfl = &pPage->aOvfl[i];
48955 k = pOvfl->idx;
48956 if( k<=iCell ){
48957 if( k==iCell ){
48958 return pOvfl->pCell;
48960 iCell--;
48963 return findCell(pPage, iCell);
48967 ** Parse a cell content block and fill in the CellInfo structure. There
48968 ** are two versions of this function. btreeParseCell() takes a
48969 ** cell index as the second argument and btreeParseCellPtr()
48970 ** takes a pointer to the body of the cell as its second argument.
48972 ** Within this file, the parseCell() macro can be called instead of
48973 ** btreeParseCellPtr(). Using some compilers, this will be faster.
48975 static void btreeParseCellPtr(
48976 MemPage *pPage, /* Page containing the cell */
48977 u8 *pCell, /* Pointer to the cell text. */
48978 CellInfo *pInfo /* Fill in this structure */
48980 u16 n; /* Number bytes in cell content header */
48981 u32 nPayload; /* Number of bytes of cell payload */
48983 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48985 pInfo->pCell = pCell;
48986 assert( pPage->leaf==0 || pPage->leaf==1 );
48987 n = pPage->childPtrSize;
48988 assert( n==4-4*pPage->leaf );
48989 if( pPage->intKey ){
48990 if( pPage->hasData ){
48991 n += getVarint32(&pCell[n], nPayload);
48992 }else{
48993 nPayload = 0;
48995 n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
48996 pInfo->nData = nPayload;
48997 }else{
48998 pInfo->nData = 0;
48999 n += getVarint32(&pCell[n], nPayload);
49000 pInfo->nKey = nPayload;
49002 pInfo->nPayload = nPayload;
49003 pInfo->nHeader = n;
49004 testcase( nPayload==pPage->maxLocal );
49005 testcase( nPayload==pPage->maxLocal+1 );
49006 if( likely(nPayload<=pPage->maxLocal) ){
49007 /* This is the (easy) common case where the entire payload fits
49008 ** on the local page. No overflow is required.
49010 if( (pInfo->nSize = (u16)(n+nPayload))<4 ) pInfo->nSize = 4;
49011 pInfo->nLocal = (u16)nPayload;
49012 pInfo->iOverflow = 0;
49013 }else{
49014 /* If the payload will not fit completely on the local page, we have
49015 ** to decide how much to store locally and how much to spill onto
49016 ** overflow pages. The strategy is to minimize the amount of unused
49017 ** space on overflow pages while keeping the amount of local storage
49018 ** in between minLocal and maxLocal.
49020 ** Warning: changing the way overflow payload is distributed in any
49021 ** way will result in an incompatible file format.
49023 int minLocal; /* Minimum amount of payload held locally */
49024 int maxLocal; /* Maximum amount of payload held locally */
49025 int surplus; /* Overflow payload available for local storage */
49027 minLocal = pPage->minLocal;
49028 maxLocal = pPage->maxLocal;
49029 surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
49030 testcase( surplus==maxLocal );
49031 testcase( surplus==maxLocal+1 );
49032 if( surplus <= maxLocal ){
49033 pInfo->nLocal = (u16)surplus;
49034 }else{
49035 pInfo->nLocal = (u16)minLocal;
49037 pInfo->iOverflow = (u16)(pInfo->nLocal + n);
49038 pInfo->nSize = pInfo->iOverflow + 4;
49041 #define parseCell(pPage, iCell, pInfo) \
49042 btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
49043 static void btreeParseCell(
49044 MemPage *pPage, /* Page containing the cell */
49045 int iCell, /* The cell index. First cell is 0 */
49046 CellInfo *pInfo /* Fill in this structure */
49048 parseCell(pPage, iCell, pInfo);
49052 ** Compute the total number of bytes that a Cell needs in the cell
49053 ** data area of the btree-page. The return number includes the cell
49054 ** data header and the local payload, but not any overflow page or
49055 ** the space used by the cell pointer.
49057 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
49058 u8 *pIter = &pCell[pPage->childPtrSize];
49059 u32 nSize;
49061 #ifdef SQLITE_DEBUG
49062 /* The value returned by this function should always be the same as
49063 ** the (CellInfo.nSize) value found by doing a full parse of the
49064 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
49065 ** this function verifies that this invariant is not violated. */
49066 CellInfo debuginfo;
49067 btreeParseCellPtr(pPage, pCell, &debuginfo);
49068 #endif
49070 if( pPage->intKey ){
49071 u8 *pEnd;
49072 if( pPage->hasData ){
49073 pIter += getVarint32(pIter, nSize);
49074 }else{
49075 nSize = 0;
49078 /* pIter now points at the 64-bit integer key value, a variable length
49079 ** integer. The following block moves pIter to point at the first byte
49080 ** past the end of the key value. */
49081 pEnd = &pIter[9];
49082 while( (*pIter++)&0x80 && pIter<pEnd );
49083 }else{
49084 pIter += getVarint32(pIter, nSize);
49087 testcase( nSize==pPage->maxLocal );
49088 testcase( nSize==pPage->maxLocal+1 );
49089 if( nSize>pPage->maxLocal ){
49090 int minLocal = pPage->minLocal;
49091 nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
49092 testcase( nSize==pPage->maxLocal );
49093 testcase( nSize==pPage->maxLocal+1 );
49094 if( nSize>pPage->maxLocal ){
49095 nSize = minLocal;
49097 nSize += 4;
49099 nSize += (u32)(pIter - pCell);
49101 /* The minimum size of any cell is 4 bytes. */
49102 if( nSize<4 ){
49103 nSize = 4;
49106 assert( nSize==debuginfo.nSize );
49107 return (u16)nSize;
49110 #ifdef SQLITE_DEBUG
49111 /* This variation on cellSizePtr() is used inside of assert() statements
49112 ** only. */
49113 static u16 cellSize(MemPage *pPage, int iCell){
49114 return cellSizePtr(pPage, findCell(pPage, iCell));
49116 #endif
49118 #ifndef SQLITE_OMIT_AUTOVACUUM
49120 ** If the cell pCell, part of page pPage contains a pointer
49121 ** to an overflow page, insert an entry into the pointer-map
49122 ** for the overflow page.
49124 static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
49125 CellInfo info;
49126 if( *pRC ) return;
49127 assert( pCell!=0 );
49128 btreeParseCellPtr(pPage, pCell, &info);
49129 assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
49130 if( info.iOverflow ){
49131 Pgno ovfl = get4byte(&pCell[info.iOverflow]);
49132 ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
49135 #endif
49139 ** Defragment the page given. All Cells are moved to the
49140 ** end of the page and all free space is collected into one
49141 ** big FreeBlk that occurs in between the header and cell
49142 ** pointer array and the cell content area.
49144 static int defragmentPage(MemPage *pPage){
49145 int i; /* Loop counter */
49146 int pc; /* Address of a i-th cell */
49147 int hdr; /* Offset to the page header */
49148 int size; /* Size of a cell */
49149 int usableSize; /* Number of usable bytes on a page */
49150 int cellOffset; /* Offset to the cell pointer array */
49151 int cbrk; /* Offset to the cell content area */
49152 int nCell; /* Number of cells on the page */
49153 unsigned char *data; /* The page data */
49154 unsigned char *temp; /* Temp area for cell content */
49155 int iCellFirst; /* First allowable cell index */
49156 int iCellLast; /* Last possible cell index */
49159 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
49160 assert( pPage->pBt!=0 );
49161 assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
49162 assert( pPage->nOverflow==0 );
49163 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49164 temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
49165 data = pPage->aData;
49166 hdr = pPage->hdrOffset;
49167 cellOffset = pPage->cellOffset;
49168 nCell = pPage->nCell;
49169 assert( nCell==get2byte(&data[hdr+3]) );
49170 usableSize = pPage->pBt->usableSize;
49171 cbrk = get2byte(&data[hdr+5]);
49172 memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
49173 cbrk = usableSize;
49174 iCellFirst = cellOffset + 2*nCell;
49175 iCellLast = usableSize - 4;
49176 for(i=0; i<nCell; i++){
49177 u8 *pAddr; /* The i-th cell pointer */
49178 pAddr = &data[cellOffset + i*2];
49179 pc = get2byte(pAddr);
49180 testcase( pc==iCellFirst );
49181 testcase( pc==iCellLast );
49182 #if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
49183 /* These conditions have already been verified in btreeInitPage()
49184 ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined
49186 if( pc<iCellFirst || pc>iCellLast ){
49187 return SQLITE_CORRUPT_BKPT;
49189 #endif
49190 assert( pc>=iCellFirst && pc<=iCellLast );
49191 size = cellSizePtr(pPage, &temp[pc]);
49192 cbrk -= size;
49193 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
49194 if( cbrk<iCellFirst ){
49195 return SQLITE_CORRUPT_BKPT;
49197 #else
49198 if( cbrk<iCellFirst || pc+size>usableSize ){
49199 return SQLITE_CORRUPT_BKPT;
49201 #endif
49202 assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
49203 testcase( cbrk+size==usableSize );
49204 testcase( pc+size==usableSize );
49205 memcpy(&data[cbrk], &temp[pc], size);
49206 put2byte(pAddr, cbrk);
49208 assert( cbrk>=iCellFirst );
49209 put2byte(&data[hdr+5], cbrk);
49210 data[hdr+1] = 0;
49211 data[hdr+2] = 0;
49212 data[hdr+7] = 0;
49213 memset(&data[iCellFirst], 0, cbrk-iCellFirst);
49214 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
49215 if( cbrk-iCellFirst!=pPage->nFree ){
49216 return SQLITE_CORRUPT_BKPT;
49218 return SQLITE_OK;
49222 ** Allocate nByte bytes of space from within the B-Tree page passed
49223 ** as the first argument. Write into *pIdx the index into pPage->aData[]
49224 ** of the first byte of allocated space. Return either SQLITE_OK or
49225 ** an error code (usually SQLITE_CORRUPT).
49227 ** The caller guarantees that there is sufficient space to make the
49228 ** allocation. This routine might need to defragment in order to bring
49229 ** all the space together, however. This routine will avoid using
49230 ** the first two bytes past the cell pointer area since presumably this
49231 ** allocation is being made in order to insert a new cell, so we will
49232 ** also end up needing a new cell pointer.
49234 static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
49235 const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
49236 u8 * const data = pPage->aData; /* Local cache of pPage->aData */
49237 int nFrag; /* Number of fragmented bytes on pPage */
49238 int top; /* First byte of cell content area */
49239 int gap; /* First byte of gap between cell pointers and cell content */
49240 int rc; /* Integer return code */
49241 int usableSize; /* Usable size of the page */
49243 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
49244 assert( pPage->pBt );
49245 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49246 assert( nByte>=0 ); /* Minimum cell size is 4 */
49247 assert( pPage->nFree>=nByte );
49248 assert( pPage->nOverflow==0 );
49249 usableSize = pPage->pBt->usableSize;
49250 assert( nByte < usableSize-8 );
49252 nFrag = data[hdr+7];
49253 assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
49254 gap = pPage->cellOffset + 2*pPage->nCell;
49255 top = get2byteNotZero(&data[hdr+5]);
49256 if( gap>top ) return SQLITE_CORRUPT_BKPT;
49257 testcase( gap+2==top );
49258 testcase( gap+1==top );
49259 testcase( gap==top );
49261 if( nFrag>=60 ){
49262 /* Always defragment highly fragmented pages */
49263 rc = defragmentPage(pPage);
49264 if( rc ) return rc;
49265 top = get2byteNotZero(&data[hdr+5]);
49266 }else if( gap+2<=top ){
49267 /* Search the freelist looking for a free slot big enough to satisfy
49268 ** the request. The allocation is made from the first free slot in
49269 ** the list that is large enough to accomadate it.
49271 int pc, addr;
49272 for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
49273 int size; /* Size of the free slot */
49274 if( pc>usableSize-4 || pc<addr+4 ){
49275 return SQLITE_CORRUPT_BKPT;
49277 size = get2byte(&data[pc+2]);
49278 if( size>=nByte ){
49279 int x = size - nByte;
49280 testcase( x==4 );
49281 testcase( x==3 );
49282 if( x<4 ){
49283 /* Remove the slot from the free-list. Update the number of
49284 ** fragmented bytes within the page. */
49285 memcpy(&data[addr], &data[pc], 2);
49286 data[hdr+7] = (u8)(nFrag + x);
49287 }else if( size+pc > usableSize ){
49288 return SQLITE_CORRUPT_BKPT;
49289 }else{
49290 /* The slot remains on the free-list. Reduce its size to account
49291 ** for the portion used by the new allocation. */
49292 put2byte(&data[pc+2], x);
49294 *pIdx = pc + x;
49295 return SQLITE_OK;
49300 /* Check to make sure there is enough space in the gap to satisfy
49301 ** the allocation. If not, defragment.
49303 testcase( gap+2+nByte==top );
49304 if( gap+2+nByte>top ){
49305 rc = defragmentPage(pPage);
49306 if( rc ) return rc;
49307 top = get2byteNotZero(&data[hdr+5]);
49308 assert( gap+nByte<=top );
49312 /* Allocate memory from the gap in between the cell pointer array
49313 ** and the cell content area. The btreeInitPage() call has already
49314 ** validated the freelist. Given that the freelist is valid, there
49315 ** is no way that the allocation can extend off the end of the page.
49316 ** The assert() below verifies the previous sentence.
49318 top -= nByte;
49319 put2byte(&data[hdr+5], top);
49320 assert( top+nByte <= (int)pPage->pBt->usableSize );
49321 *pIdx = top;
49322 return SQLITE_OK;
49326 ** Return a section of the pPage->aData to the freelist.
49327 ** The first byte of the new free block is pPage->aDisk[start]
49328 ** and the size of the block is "size" bytes.
49330 ** Most of the effort here is involved in coalesing adjacent
49331 ** free blocks into a single big free block.
49333 static int freeSpace(MemPage *pPage, int start, int size){
49334 int addr, pbegin, hdr;
49335 int iLast; /* Largest possible freeblock offset */
49336 unsigned char *data = pPage->aData;
49338 assert( pPage->pBt!=0 );
49339 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
49340 assert( start>=pPage->hdrOffset+6+pPage->childPtrSize );
49341 assert( (start + size) <= (int)pPage->pBt->usableSize );
49342 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49343 assert( size>=0 ); /* Minimum cell size is 4 */
49345 if( pPage->pBt->secureDelete ){
49346 /* Overwrite deleted information with zeros when the secure_delete
49347 ** option is enabled */
49348 memset(&data[start], 0, size);
49351 /* Add the space back into the linked list of freeblocks. Note that
49352 ** even though the freeblock list was checked by btreeInitPage(),
49353 ** btreeInitPage() did not detect overlapping cells or
49354 ** freeblocks that overlapped cells. Nor does it detect when the
49355 ** cell content area exceeds the value in the page header. If these
49356 ** situations arise, then subsequent insert operations might corrupt
49357 ** the freelist. So we do need to check for corruption while scanning
49358 ** the freelist.
49360 hdr = pPage->hdrOffset;
49361 addr = hdr + 1;
49362 iLast = pPage->pBt->usableSize - 4;
49363 assert( start<=iLast );
49364 while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
49365 if( pbegin<addr+4 ){
49366 return SQLITE_CORRUPT_BKPT;
49368 addr = pbegin;
49370 if( pbegin>iLast ){
49371 return SQLITE_CORRUPT_BKPT;
49373 assert( pbegin>addr || pbegin==0 );
49374 put2byte(&data[addr], start);
49375 put2byte(&data[start], pbegin);
49376 put2byte(&data[start+2], size);
49377 pPage->nFree = pPage->nFree + (u16)size;
49379 /* Coalesce adjacent free blocks */
49380 addr = hdr + 1;
49381 while( (pbegin = get2byte(&data[addr]))>0 ){
49382 int pnext, psize, x;
49383 assert( pbegin>addr );
49384 assert( pbegin <= (int)pPage->pBt->usableSize-4 );
49385 pnext = get2byte(&data[pbegin]);
49386 psize = get2byte(&data[pbegin+2]);
49387 if( pbegin + psize + 3 >= pnext && pnext>0 ){
49388 int frag = pnext - (pbegin+psize);
49389 if( (frag<0) || (frag>(int)data[hdr+7]) ){
49390 return SQLITE_CORRUPT_BKPT;
49392 data[hdr+7] -= (u8)frag;
49393 x = get2byte(&data[pnext]);
49394 put2byte(&data[pbegin], x);
49395 x = pnext + get2byte(&data[pnext+2]) - pbegin;
49396 put2byte(&data[pbegin+2], x);
49397 }else{
49398 addr = pbegin;
49402 /* If the cell content area begins with a freeblock, remove it. */
49403 if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
49404 int top;
49405 pbegin = get2byte(&data[hdr+1]);
49406 memcpy(&data[hdr+1], &data[pbegin], 2);
49407 top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
49408 put2byte(&data[hdr+5], top);
49410 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
49411 return SQLITE_OK;
49415 ** Decode the flags byte (the first byte of the header) for a page
49416 ** and initialize fields of the MemPage structure accordingly.
49418 ** Only the following combinations are supported. Anything different
49419 ** indicates a corrupt database files:
49421 ** PTF_ZERODATA
49422 ** PTF_ZERODATA | PTF_LEAF
49423 ** PTF_LEAFDATA | PTF_INTKEY
49424 ** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
49426 static int decodeFlags(MemPage *pPage, int flagByte){
49427 BtShared *pBt; /* A copy of pPage->pBt */
49429 assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
49430 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49431 pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
49432 flagByte &= ~PTF_LEAF;
49433 pPage->childPtrSize = 4-4*pPage->leaf;
49434 pBt = pPage->pBt;
49435 if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
49436 pPage->intKey = 1;
49437 pPage->hasData = pPage->leaf;
49438 pPage->maxLocal = pBt->maxLeaf;
49439 pPage->minLocal = pBt->minLeaf;
49440 }else if( flagByte==PTF_ZERODATA ){
49441 pPage->intKey = 0;
49442 pPage->hasData = 0;
49443 pPage->maxLocal = pBt->maxLocal;
49444 pPage->minLocal = pBt->minLocal;
49445 }else{
49446 return SQLITE_CORRUPT_BKPT;
49448 return SQLITE_OK;
49452 ** Initialize the auxiliary information for a disk block.
49454 ** Return SQLITE_OK on success. If we see that the page does
49455 ** not contain a well-formed database page, then return
49456 ** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
49457 ** guarantee that the page is well-formed. It only shows that
49458 ** we failed to detect any corruption.
49460 static int btreeInitPage(MemPage *pPage){
49462 assert( pPage->pBt!=0 );
49463 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49464 assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
49465 assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
49466 assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
49468 if( !pPage->isInit ){
49469 u16 pc; /* Address of a freeblock within pPage->aData[] */
49470 u8 hdr; /* Offset to beginning of page header */
49471 u8 *data; /* Equal to pPage->aData */
49472 BtShared *pBt; /* The main btree structure */
49473 int usableSize; /* Amount of usable space on each page */
49474 u16 cellOffset; /* Offset from start of page to first cell pointer */
49475 int nFree; /* Number of unused bytes on the page */
49476 int top; /* First byte of the cell content area */
49477 int iCellFirst; /* First allowable cell or freeblock offset */
49478 int iCellLast; /* Last possible cell or freeblock offset */
49480 pBt = pPage->pBt;
49482 hdr = pPage->hdrOffset;
49483 data = pPage->aData;
49484 if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
49485 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
49486 pPage->maskPage = (u16)(pBt->pageSize - 1);
49487 pPage->nOverflow = 0;
49488 usableSize = pBt->usableSize;
49489 pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
49490 top = get2byteNotZero(&data[hdr+5]);
49491 pPage->nCell = get2byte(&data[hdr+3]);
49492 if( pPage->nCell>MX_CELL(pBt) ){
49493 /* To many cells for a single page. The page must be corrupt */
49494 return SQLITE_CORRUPT_BKPT;
49496 testcase( pPage->nCell==MX_CELL(pBt) );
49498 /* A malformed database page might cause us to read past the end
49499 ** of page when parsing a cell.
49501 ** The following block of code checks early to see if a cell extends
49502 ** past the end of a page boundary and causes SQLITE_CORRUPT to be
49503 ** returned if it does.
49505 iCellFirst = cellOffset + 2*pPage->nCell;
49506 iCellLast = usableSize - 4;
49507 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
49509 int i; /* Index into the cell pointer array */
49510 int sz; /* Size of a cell */
49512 if( !pPage->leaf ) iCellLast--;
49513 for(i=0; i<pPage->nCell; i++){
49514 pc = get2byte(&data[cellOffset+i*2]);
49515 testcase( pc==iCellFirst );
49516 testcase( pc==iCellLast );
49517 if( pc<iCellFirst || pc>iCellLast ){
49518 return SQLITE_CORRUPT_BKPT;
49520 sz = cellSizePtr(pPage, &data[pc]);
49521 testcase( pc+sz==usableSize );
49522 if( pc+sz>usableSize ){
49523 return SQLITE_CORRUPT_BKPT;
49526 if( !pPage->leaf ) iCellLast++;
49528 #endif
49530 /* Compute the total free space on the page */
49531 pc = get2byte(&data[hdr+1]);
49532 nFree = data[hdr+7] + top;
49533 while( pc>0 ){
49534 u16 next, size;
49535 if( pc<iCellFirst || pc>iCellLast ){
49536 /* Start of free block is off the page */
49537 return SQLITE_CORRUPT_BKPT;
49539 next = get2byte(&data[pc]);
49540 size = get2byte(&data[pc+2]);
49541 if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
49542 /* Free blocks must be in ascending order. And the last byte of
49543 ** the free-block must lie on the database page. */
49544 return SQLITE_CORRUPT_BKPT;
49546 nFree = nFree + size;
49547 pc = next;
49550 /* At this point, nFree contains the sum of the offset to the start
49551 ** of the cell-content area plus the number of free bytes within
49552 ** the cell-content area. If this is greater than the usable-size
49553 ** of the page, then the page must be corrupted. This check also
49554 ** serves to verify that the offset to the start of the cell-content
49555 ** area, according to the page header, lies within the page.
49557 if( nFree>usableSize ){
49558 return SQLITE_CORRUPT_BKPT;
49560 pPage->nFree = (u16)(nFree - iCellFirst);
49561 pPage->isInit = 1;
49563 return SQLITE_OK;
49567 ** Set up a raw page so that it looks like a database page holding
49568 ** no entries.
49570 static void zeroPage(MemPage *pPage, int flags){
49571 unsigned char *data = pPage->aData;
49572 BtShared *pBt = pPage->pBt;
49573 u8 hdr = pPage->hdrOffset;
49574 u16 first;
49576 assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
49577 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
49578 assert( sqlite3PagerGetData(pPage->pDbPage) == data );
49579 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
49580 assert( sqlite3_mutex_held(pBt->mutex) );
49581 if( pBt->secureDelete ){
49582 memset(&data[hdr], 0, pBt->usableSize - hdr);
49584 data[hdr] = (char)flags;
49585 first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
49586 memset(&data[hdr+1], 0, 4);
49587 data[hdr+7] = 0;
49588 put2byte(&data[hdr+5], pBt->usableSize);
49589 pPage->nFree = (u16)(pBt->usableSize - first);
49590 decodeFlags(pPage, flags);
49591 pPage->hdrOffset = hdr;
49592 pPage->cellOffset = first;
49593 pPage->nOverflow = 0;
49594 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
49595 pPage->maskPage = (u16)(pBt->pageSize - 1);
49596 pPage->nCell = 0;
49597 pPage->isInit = 1;
49602 ** Convert a DbPage obtained from the pager into a MemPage used by
49603 ** the btree layer.
49605 static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
49606 MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
49607 pPage->aData = sqlite3PagerGetData(pDbPage);
49608 pPage->pDbPage = pDbPage;
49609 pPage->pBt = pBt;
49610 pPage->pgno = pgno;
49611 pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
49612 return pPage;
49616 ** Get a page from the pager. Initialize the MemPage.pBt and
49617 ** MemPage.aData elements if needed.
49619 ** If the noContent flag is set, it means that we do not care about
49620 ** the content of the page at this time. So do not go to the disk
49621 ** to fetch the content. Just fill in the content with zeros for now.
49622 ** If in the future we call sqlite3PagerWrite() on this page, that
49623 ** means we have started to be concerned about content and the disk
49624 ** read should occur at that point.
49626 static int btreeGetPage(
49627 BtShared *pBt, /* The btree */
49628 Pgno pgno, /* Number of the page to fetch */
49629 MemPage **ppPage, /* Return the page in this parameter */
49630 int noContent /* Do not load page content if true */
49632 int rc;
49633 DbPage *pDbPage;
49635 assert( sqlite3_mutex_held(pBt->mutex) );
49636 rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
49637 if( rc ) return rc;
49638 *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
49639 return SQLITE_OK;
49643 ** Retrieve a page from the pager cache. If the requested page is not
49644 ** already in the pager cache return NULL. Initialize the MemPage.pBt and
49645 ** MemPage.aData elements if needed.
49647 static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
49648 DbPage *pDbPage;
49649 assert( sqlite3_mutex_held(pBt->mutex) );
49650 pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
49651 if( pDbPage ){
49652 return btreePageFromDbPage(pDbPage, pgno, pBt);
49654 return 0;
49658 ** Return the size of the database file in pages. If there is any kind of
49659 ** error, return ((unsigned int)-1).
49661 static Pgno btreePagecount(BtShared *pBt){
49662 return pBt->nPage;
49664 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
49665 assert( sqlite3BtreeHoldsMutex(p) );
49666 assert( ((p->pBt->nPage)&0x8000000)==0 );
49667 return (int)btreePagecount(p->pBt);
49671 ** Get a page from the pager and initialize it. This routine is just a
49672 ** convenience wrapper around separate calls to btreeGetPage() and
49673 ** btreeInitPage().
49675 ** If an error occurs, then the value *ppPage is set to is undefined. It
49676 ** may remain unchanged, or it may be set to an invalid value.
49678 static int getAndInitPage(
49679 BtShared *pBt, /* The database file */
49680 Pgno pgno, /* Number of the page to get */
49681 MemPage **ppPage /* Write the page pointer here */
49683 int rc;
49684 assert( sqlite3_mutex_held(pBt->mutex) );
49686 if( pgno>btreePagecount(pBt) ){
49687 rc = SQLITE_CORRUPT_BKPT;
49688 }else{
49689 rc = btreeGetPage(pBt, pgno, ppPage, 0);
49690 if( rc==SQLITE_OK ){
49691 rc = btreeInitPage(*ppPage);
49692 if( rc!=SQLITE_OK ){
49693 releasePage(*ppPage);
49698 testcase( pgno==0 );
49699 assert( pgno!=0 || rc==SQLITE_CORRUPT );
49700 return rc;
49704 ** Release a MemPage. This should be called once for each prior
49705 ** call to btreeGetPage.
49707 static void releasePage(MemPage *pPage){
49708 if( pPage ){
49709 assert( pPage->aData );
49710 assert( pPage->pBt );
49711 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
49712 assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
49713 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49714 sqlite3PagerUnref(pPage->pDbPage);
49719 ** During a rollback, when the pager reloads information into the cache
49720 ** so that the cache is restored to its original state at the start of
49721 ** the transaction, for each page restored this routine is called.
49723 ** This routine needs to reset the extra data section at the end of the
49724 ** page to agree with the restored data.
49726 static void pageReinit(DbPage *pData){
49727 MemPage *pPage;
49728 pPage = (MemPage *)sqlite3PagerGetExtra(pData);
49729 assert( sqlite3PagerPageRefcount(pData)>0 );
49730 if( pPage->isInit ){
49731 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49732 pPage->isInit = 0;
49733 if( sqlite3PagerPageRefcount(pData)>1 ){
49734 /* pPage might not be a btree page; it might be an overflow page
49735 ** or ptrmap page or a free page. In those cases, the following
49736 ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
49737 ** But no harm is done by this. And it is very important that
49738 ** btreeInitPage() be called on every btree page so we make
49739 ** the call for every page that comes in for re-initing. */
49740 btreeInitPage(pPage);
49746 ** Invoke the busy handler for a btree.
49748 static int btreeInvokeBusyHandler(void *pArg){
49749 BtShared *pBt = (BtShared*)pArg;
49750 assert( pBt->db );
49751 assert( sqlite3_mutex_held(pBt->db->mutex) );
49752 return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
49756 ** Open a database file.
49758 ** zFilename is the name of the database file. If zFilename is NULL
49759 ** then an ephemeral database is created. The ephemeral database might
49760 ** be exclusively in memory, or it might use a disk-based memory cache.
49761 ** Either way, the ephemeral database will be automatically deleted
49762 ** when sqlite3BtreeClose() is called.
49764 ** If zFilename is ":memory:" then an in-memory database is created
49765 ** that is automatically destroyed when it is closed.
49767 ** The "flags" parameter is a bitmask that might contain bits
49768 ** BTREE_OMIT_JOURNAL and/or BTREE_NO_READLOCK. The BTREE_NO_READLOCK
49769 ** bit is also set if the SQLITE_NoReadlock flags is set in db->flags.
49770 ** These flags are passed through into sqlite3PagerOpen() and must
49771 ** be the same values as PAGER_OMIT_JOURNAL and PAGER_NO_READLOCK.
49773 ** If the database is already opened in the same database connection
49774 ** and we are in shared cache mode, then the open will fail with an
49775 ** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
49776 ** objects in the same database connection since doing so will lead
49777 ** to problems with locking.
49779 SQLITE_PRIVATE int sqlite3BtreeOpen(
49780 sqlite3_vfs *pVfs, /* VFS to use for this b-tree */
49781 const char *zFilename, /* Name of the file containing the BTree database */
49782 sqlite3 *db, /* Associated database handle */
49783 Btree **ppBtree, /* Pointer to new Btree object written here */
49784 int flags, /* Options */
49785 int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
49787 BtShared *pBt = 0; /* Shared part of btree structure */
49788 Btree *p; /* Handle to return */
49789 sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
49790 int rc = SQLITE_OK; /* Result code from this function */
49791 u8 nReserve; /* Byte of unused space on each page */
49792 unsigned char zDbHeader[100]; /* Database header content */
49794 /* True if opening an ephemeral, temporary database */
49795 const int isTempDb = zFilename==0 || zFilename[0]==0;
49797 /* Set the variable isMemdb to true for an in-memory database, or
49798 ** false for a file-based database.
49800 #ifdef SQLITE_OMIT_MEMORYDB
49801 const int isMemdb = 0;
49802 #else
49803 const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
49804 || (isTempDb && sqlite3TempInMemory(db));
49805 #endif
49807 assert( db!=0 );
49808 assert( pVfs!=0 );
49809 assert( sqlite3_mutex_held(db->mutex) );
49810 assert( (flags&0xff)==flags ); /* flags fit in 8 bits */
49812 /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
49813 assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
49815 /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
49816 assert( (flags & BTREE_SINGLE)==0 || isTempDb );
49818 if( db->flags & SQLITE_NoReadlock ){
49819 flags |= BTREE_NO_READLOCK;
49821 if( isMemdb ){
49822 flags |= BTREE_MEMORY;
49824 if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
49825 vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
49827 p = sqlite3MallocZero(sizeof(Btree));
49828 if( !p ){
49829 return SQLITE_NOMEM;
49831 p->inTrans = TRANS_NONE;
49832 p->db = db;
49833 #ifndef SQLITE_OMIT_SHARED_CACHE
49834 p->lock.pBtree = p;
49835 p->lock.iTable = 1;
49836 #endif
49838 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
49840 ** If this Btree is a candidate for shared cache, try to find an
49841 ** existing BtShared object that we can share with
49843 if( isMemdb==0 && isTempDb==0 ){
49844 if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
49845 int nFullPathname = pVfs->mxPathname+1;
49846 char *zFullPathname = sqlite3Malloc(nFullPathname);
49847 MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
49848 p->sharable = 1;
49849 if( !zFullPathname ){
49850 sqlite3_free(p);
49851 return SQLITE_NOMEM;
49853 sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname);
49854 #if SQLITE_THREADSAFE
49855 mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
49856 sqlite3_mutex_enter(mutexOpen);
49857 mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
49858 sqlite3_mutex_enter(mutexShared);
49859 #endif
49860 for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
49861 assert( pBt->nRef>0 );
49862 if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager))
49863 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
49864 int iDb;
49865 for(iDb=db->nDb-1; iDb>=0; iDb--){
49866 Btree *pExisting = db->aDb[iDb].pBt;
49867 if( pExisting && pExisting->pBt==pBt ){
49868 sqlite3_mutex_leave(mutexShared);
49869 sqlite3_mutex_leave(mutexOpen);
49870 sqlite3_free(zFullPathname);
49871 sqlite3_free(p);
49872 return SQLITE_CONSTRAINT;
49875 p->pBt = pBt;
49876 pBt->nRef++;
49877 break;
49880 sqlite3_mutex_leave(mutexShared);
49881 sqlite3_free(zFullPathname);
49883 #ifdef SQLITE_DEBUG
49884 else{
49885 /* In debug mode, we mark all persistent databases as sharable
49886 ** even when they are not. This exercises the locking code and
49887 ** gives more opportunity for asserts(sqlite3_mutex_held())
49888 ** statements to find locking problems.
49890 p->sharable = 1;
49892 #endif
49894 #endif
49895 if( pBt==0 ){
49897 ** The following asserts make sure that structures used by the btree are
49898 ** the right size. This is to guard against size changes that result
49899 ** when compiling on a different architecture.
49901 assert( sizeof(i64)==8 || sizeof(i64)==4 );
49902 assert( sizeof(u64)==8 || sizeof(u64)==4 );
49903 assert( sizeof(u32)==4 );
49904 assert( sizeof(u16)==2 );
49905 assert( sizeof(Pgno)==4 );
49907 pBt = sqlite3MallocZero( sizeof(*pBt) );
49908 if( pBt==0 ){
49909 rc = SQLITE_NOMEM;
49910 goto btree_open_out;
49912 rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
49913 EXTRA_SIZE, flags, vfsFlags, pageReinit);
49914 if( rc==SQLITE_OK ){
49915 rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
49917 if( rc!=SQLITE_OK ){
49918 goto btree_open_out;
49920 pBt->openFlags = (u8)flags;
49921 pBt->db = db;
49922 sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
49923 p->pBt = pBt;
49925 pBt->pCursor = 0;
49926 pBt->pPage1 = 0;
49927 pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager);
49928 #ifdef SQLITE_SECURE_DELETE
49929 pBt->secureDelete = 1;
49930 #endif
49931 pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
49932 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
49933 || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
49934 pBt->pageSize = 0;
49935 #ifndef SQLITE_OMIT_AUTOVACUUM
49936 /* If the magic name ":memory:" will create an in-memory database, then
49937 ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
49938 ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
49939 ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
49940 ** regular file-name. In this case the auto-vacuum applies as per normal.
49942 if( zFilename && !isMemdb ){
49943 pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
49944 pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
49946 #endif
49947 nReserve = 0;
49948 }else{
49949 nReserve = zDbHeader[20];
49950 pBt->pageSizeFixed = 1;
49951 #ifndef SQLITE_OMIT_AUTOVACUUM
49952 pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
49953 pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
49954 #endif
49956 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
49957 if( rc ) goto btree_open_out;
49958 pBt->usableSize = pBt->pageSize - nReserve;
49959 assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
49961 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
49962 /* Add the new BtShared object to the linked list sharable BtShareds.
49964 if( p->sharable ){
49965 MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
49966 pBt->nRef = 1;
49967 MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
49968 if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
49969 pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
49970 if( pBt->mutex==0 ){
49971 rc = SQLITE_NOMEM;
49972 db->mallocFailed = 0;
49973 goto btree_open_out;
49976 sqlite3_mutex_enter(mutexShared);
49977 pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
49978 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
49979 sqlite3_mutex_leave(mutexShared);
49981 #endif
49984 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
49985 /* If the new Btree uses a sharable pBtShared, then link the new
49986 ** Btree into the list of all sharable Btrees for the same connection.
49987 ** The list is kept in ascending order by pBt address.
49989 if( p->sharable ){
49990 int i;
49991 Btree *pSib;
49992 for(i=0; i<db->nDb; i++){
49993 if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
49994 while( pSib->pPrev ){ pSib = pSib->pPrev; }
49995 if( p->pBt<pSib->pBt ){
49996 p->pNext = pSib;
49997 p->pPrev = 0;
49998 pSib->pPrev = p;
49999 }else{
50000 while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
50001 pSib = pSib->pNext;
50003 p->pNext = pSib->pNext;
50004 p->pPrev = pSib;
50005 if( p->pNext ){
50006 p->pNext->pPrev = p;
50008 pSib->pNext = p;
50010 break;
50014 #endif
50015 *ppBtree = p;
50017 btree_open_out:
50018 if( rc!=SQLITE_OK ){
50019 if( pBt && pBt->pPager ){
50020 sqlite3PagerClose(pBt->pPager);
50022 sqlite3_free(pBt);
50023 sqlite3_free(p);
50024 *ppBtree = 0;
50025 }else{
50026 /* If the B-Tree was successfully opened, set the pager-cache size to the
50027 ** default value. Except, when opening on an existing shared pager-cache,
50028 ** do not change the pager-cache size.
50030 if( sqlite3BtreeSchema(p, 0, 0)==0 ){
50031 sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
50034 if( mutexOpen ){
50035 assert( sqlite3_mutex_held(mutexOpen) );
50036 sqlite3_mutex_leave(mutexOpen);
50038 return rc;
50042 ** Decrement the BtShared.nRef counter. When it reaches zero,
50043 ** remove the BtShared structure from the sharing list. Return
50044 ** true if the BtShared.nRef counter reaches zero and return
50045 ** false if it is still positive.
50047 static int removeFromSharingList(BtShared *pBt){
50048 #ifndef SQLITE_OMIT_SHARED_CACHE
50049 MUTEX_LOGIC( sqlite3_mutex *pMaster; )
50050 BtShared *pList;
50051 int removed = 0;
50053 assert( sqlite3_mutex_notheld(pBt->mutex) );
50054 MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
50055 sqlite3_mutex_enter(pMaster);
50056 pBt->nRef--;
50057 if( pBt->nRef<=0 ){
50058 if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
50059 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
50060 }else{
50061 pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
50062 while( ALWAYS(pList) && pList->pNext!=pBt ){
50063 pList=pList->pNext;
50065 if( ALWAYS(pList) ){
50066 pList->pNext = pBt->pNext;
50069 if( SQLITE_THREADSAFE ){
50070 sqlite3_mutex_free(pBt->mutex);
50072 removed = 1;
50074 sqlite3_mutex_leave(pMaster);
50075 return removed;
50076 #else
50077 return 1;
50078 #endif
50082 ** Make sure pBt->pTmpSpace points to an allocation of
50083 ** MX_CELL_SIZE(pBt) bytes.
50085 static void allocateTempSpace(BtShared *pBt){
50086 if( !pBt->pTmpSpace ){
50087 pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
50092 ** Free the pBt->pTmpSpace allocation
50094 static void freeTempSpace(BtShared *pBt){
50095 sqlite3PageFree( pBt->pTmpSpace);
50096 pBt->pTmpSpace = 0;
50100 ** Close an open database and invalidate all cursors.
50102 SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
50103 BtShared *pBt = p->pBt;
50104 BtCursor *pCur;
50106 /* Close all cursors opened via this handle. */
50107 assert( sqlite3_mutex_held(p->db->mutex) );
50108 sqlite3BtreeEnter(p);
50109 pCur = pBt->pCursor;
50110 while( pCur ){
50111 BtCursor *pTmp = pCur;
50112 pCur = pCur->pNext;
50113 if( pTmp->pBtree==p ){
50114 sqlite3BtreeCloseCursor(pTmp);
50118 /* Rollback any active transaction and free the handle structure.
50119 ** The call to sqlite3BtreeRollback() drops any table-locks held by
50120 ** this handle.
50122 sqlite3BtreeRollback(p);
50123 sqlite3BtreeLeave(p);
50125 /* If there are still other outstanding references to the shared-btree
50126 ** structure, return now. The remainder of this procedure cleans
50127 ** up the shared-btree.
50129 assert( p->wantToLock==0 && p->locked==0 );
50130 if( !p->sharable || removeFromSharingList(pBt) ){
50131 /* The pBt is no longer on the sharing list, so we can access
50132 ** it without having to hold the mutex.
50134 ** Clean out and delete the BtShared object.
50136 assert( !pBt->pCursor );
50137 sqlite3PagerClose(pBt->pPager);
50138 if( pBt->xFreeSchema && pBt->pSchema ){
50139 pBt->xFreeSchema(pBt->pSchema);
50141 sqlite3DbFree(0, pBt->pSchema);
50142 freeTempSpace(pBt);
50143 sqlite3_free(pBt);
50146 #ifndef SQLITE_OMIT_SHARED_CACHE
50147 assert( p->wantToLock==0 );
50148 assert( p->locked==0 );
50149 if( p->pPrev ) p->pPrev->pNext = p->pNext;
50150 if( p->pNext ) p->pNext->pPrev = p->pPrev;
50151 #endif
50153 sqlite3_free(p);
50154 return SQLITE_OK;
50158 ** Change the limit on the number of pages allowed in the cache.
50160 ** The maximum number of cache pages is set to the absolute
50161 ** value of mxPage. If mxPage is negative, the pager will
50162 ** operate asynchronously - it will not stop to do fsync()s
50163 ** to insure data is written to the disk surface before
50164 ** continuing. Transactions still work if synchronous is off,
50165 ** and the database cannot be corrupted if this program
50166 ** crashes. But if the operating system crashes or there is
50167 ** an abrupt power failure when synchronous is off, the database
50168 ** could be left in an inconsistent and unrecoverable state.
50169 ** Synchronous is on by default so database corruption is not
50170 ** normally a worry.
50172 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
50173 BtShared *pBt = p->pBt;
50174 assert( sqlite3_mutex_held(p->db->mutex) );
50175 sqlite3BtreeEnter(p);
50176 sqlite3PagerSetCachesize(pBt->pPager, mxPage);
50177 sqlite3BtreeLeave(p);
50178 return SQLITE_OK;
50182 ** Change the way data is synced to disk in order to increase or decrease
50183 ** how well the database resists damage due to OS crashes and power
50184 ** failures. Level 1 is the same as asynchronous (no syncs() occur and
50185 ** there is a high probability of damage) Level 2 is the default. There
50186 ** is a very low but non-zero probability of damage. Level 3 reduces the
50187 ** probability of damage to near zero but with a write performance reduction.
50189 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
50190 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(
50191 Btree *p, /* The btree to set the safety level on */
50192 int level, /* PRAGMA synchronous. 1=OFF, 2=NORMAL, 3=FULL */
50193 int fullSync, /* PRAGMA fullfsync. */
50194 int ckptFullSync /* PRAGMA checkpoint_fullfync */
50196 BtShared *pBt = p->pBt;
50197 assert( sqlite3_mutex_held(p->db->mutex) );
50198 assert( level>=1 && level<=3 );
50199 sqlite3BtreeEnter(p);
50200 sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync, ckptFullSync);
50201 sqlite3BtreeLeave(p);
50202 return SQLITE_OK;
50204 #endif
50207 ** Return TRUE if the given btree is set to safety level 1. In other
50208 ** words, return TRUE if no sync() occurs on the disk files.
50210 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
50211 BtShared *pBt = p->pBt;
50212 int rc;
50213 assert( sqlite3_mutex_held(p->db->mutex) );
50214 sqlite3BtreeEnter(p);
50215 assert( pBt && pBt->pPager );
50216 rc = sqlite3PagerNosync(pBt->pPager);
50217 sqlite3BtreeLeave(p);
50218 return rc;
50222 ** Change the default pages size and the number of reserved bytes per page.
50223 ** Or, if the page size has already been fixed, return SQLITE_READONLY
50224 ** without changing anything.
50226 ** The page size must be a power of 2 between 512 and 65536. If the page
50227 ** size supplied does not meet this constraint then the page size is not
50228 ** changed.
50230 ** Page sizes are constrained to be a power of two so that the region
50231 ** of the database file used for locking (beginning at PENDING_BYTE,
50232 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
50233 ** at the beginning of a page.
50235 ** If parameter nReserve is less than zero, then the number of reserved
50236 ** bytes per page is left unchanged.
50238 ** If the iFix!=0 then the pageSizeFixed flag is set so that the page size
50239 ** and autovacuum mode can no longer be changed.
50241 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
50242 int rc = SQLITE_OK;
50243 BtShared *pBt = p->pBt;
50244 assert( nReserve>=-1 && nReserve<=255 );
50245 sqlite3BtreeEnter(p);
50246 if( pBt->pageSizeFixed ){
50247 sqlite3BtreeLeave(p);
50248 return SQLITE_READONLY;
50250 if( nReserve<0 ){
50251 nReserve = pBt->pageSize - pBt->usableSize;
50253 assert( nReserve>=0 && nReserve<=255 );
50254 if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
50255 ((pageSize-1)&pageSize)==0 ){
50256 assert( (pageSize & 7)==0 );
50257 assert( !pBt->pPage1 && !pBt->pCursor );
50258 pBt->pageSize = (u32)pageSize;
50259 freeTempSpace(pBt);
50261 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
50262 pBt->usableSize = pBt->pageSize - (u16)nReserve;
50263 if( iFix ) pBt->pageSizeFixed = 1;
50264 sqlite3BtreeLeave(p);
50265 return rc;
50269 ** Return the currently defined page size
50271 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
50272 return p->pBt->pageSize;
50275 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
50277 ** Return the number of bytes of space at the end of every page that
50278 ** are intentually left unused. This is the "reserved" space that is
50279 ** sometimes used by extensions.
50281 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
50282 int n;
50283 sqlite3BtreeEnter(p);
50284 n = p->pBt->pageSize - p->pBt->usableSize;
50285 sqlite3BtreeLeave(p);
50286 return n;
50290 ** Set the maximum page count for a database if mxPage is positive.
50291 ** No changes are made if mxPage is 0 or negative.
50292 ** Regardless of the value of mxPage, return the maximum page count.
50294 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
50295 int n;
50296 sqlite3BtreeEnter(p);
50297 n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
50298 sqlite3BtreeLeave(p);
50299 return n;
50303 ** Set the secureDelete flag if newFlag is 0 or 1. If newFlag is -1,
50304 ** then make no changes. Always return the value of the secureDelete
50305 ** setting after the change.
50307 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
50308 int b;
50309 if( p==0 ) return 0;
50310 sqlite3BtreeEnter(p);
50311 if( newFlag>=0 ){
50312 p->pBt->secureDelete = (newFlag!=0) ? 1 : 0;
50314 b = p->pBt->secureDelete;
50315 sqlite3BtreeLeave(p);
50316 return b;
50318 #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
50321 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
50322 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
50323 ** is disabled. The default value for the auto-vacuum property is
50324 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
50326 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
50327 #ifdef SQLITE_OMIT_AUTOVACUUM
50328 return SQLITE_READONLY;
50329 #else
50330 BtShared *pBt = p->pBt;
50331 int rc = SQLITE_OK;
50332 u8 av = (u8)autoVacuum;
50334 sqlite3BtreeEnter(p);
50335 if( pBt->pageSizeFixed && (av ?1:0)!=pBt->autoVacuum ){
50336 rc = SQLITE_READONLY;
50337 }else{
50338 pBt->autoVacuum = av ?1:0;
50339 pBt->incrVacuum = av==2 ?1:0;
50341 sqlite3BtreeLeave(p);
50342 return rc;
50343 #endif
50347 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
50348 ** enabled 1 is returned. Otherwise 0.
50350 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
50351 #ifdef SQLITE_OMIT_AUTOVACUUM
50352 return BTREE_AUTOVACUUM_NONE;
50353 #else
50354 int rc;
50355 sqlite3BtreeEnter(p);
50356 rc = (
50357 (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
50358 (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
50359 BTREE_AUTOVACUUM_INCR
50361 sqlite3BtreeLeave(p);
50362 return rc;
50363 #endif
50368 ** Get a reference to pPage1 of the database file. This will
50369 ** also acquire a readlock on that file.
50371 ** SQLITE_OK is returned on success. If the file is not a
50372 ** well-formed database file, then SQLITE_CORRUPT is returned.
50373 ** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
50374 ** is returned if we run out of memory.
50376 static int lockBtree(BtShared *pBt){
50377 int rc; /* Result code from subfunctions */
50378 MemPage *pPage1; /* Page 1 of the database file */
50379 int nPage; /* Number of pages in the database */
50380 int nPageFile = 0; /* Number of pages in the database file */
50381 int nPageHeader; /* Number of pages in the database according to hdr */
50383 assert( sqlite3_mutex_held(pBt->mutex) );
50384 assert( pBt->pPage1==0 );
50385 rc = sqlite3PagerSharedLock(pBt->pPager);
50386 if( rc!=SQLITE_OK ) return rc;
50387 rc = btreeGetPage(pBt, 1, &pPage1, 0);
50388 if( rc!=SQLITE_OK ) return rc;
50390 /* Do some checking to help insure the file we opened really is
50391 ** a valid database file.
50393 nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
50394 sqlite3PagerPagecount(pBt->pPager, &nPageFile);
50395 if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
50396 nPage = nPageFile;
50398 if( nPage>0 ){
50399 u32 pageSize;
50400 u32 usableSize;
50401 u8 *page1 = pPage1->aData;
50402 rc = SQLITE_NOTADB;
50403 if( memcmp(page1, zMagicHeader, 16)!=0 ){
50404 goto page1_init_failed;
50407 #ifdef SQLITE_OMIT_WAL
50408 if( page1[18]>1 ){
50409 pBt->readOnly = 1;
50411 if( page1[19]>1 ){
50412 goto page1_init_failed;
50414 #else
50415 if( page1[18]>2 ){
50416 pBt->readOnly = 1;
50418 if( page1[19]>2 ){
50419 goto page1_init_failed;
50422 /* If the write version is set to 2, this database should be accessed
50423 ** in WAL mode. If the log is not already open, open it now. Then
50424 ** return SQLITE_OK and return without populating BtShared.pPage1.
50425 ** The caller detects this and calls this function again. This is
50426 ** required as the version of page 1 currently in the page1 buffer
50427 ** may not be the latest version - there may be a newer one in the log
50428 ** file.
50430 if( page1[19]==2 && pBt->doNotUseWAL==0 ){
50431 int isOpen = 0;
50432 rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
50433 if( rc!=SQLITE_OK ){
50434 goto page1_init_failed;
50435 }else if( isOpen==0 ){
50436 releasePage(pPage1);
50437 return SQLITE_OK;
50439 rc = SQLITE_NOTADB;
50441 #endif
50443 /* The maximum embedded fraction must be exactly 25%. And the minimum
50444 ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
50445 ** The original design allowed these amounts to vary, but as of
50446 ** version 3.6.0, we require them to be fixed.
50448 if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
50449 goto page1_init_failed;
50451 pageSize = (page1[16]<<8) | (page1[17]<<16);
50452 if( ((pageSize-1)&pageSize)!=0
50453 || pageSize>SQLITE_MAX_PAGE_SIZE
50454 || pageSize<=256
50456 goto page1_init_failed;
50458 assert( (pageSize & 7)==0 );
50459 usableSize = pageSize - page1[20];
50460 if( (u32)pageSize!=pBt->pageSize ){
50461 /* After reading the first page of the database assuming a page size
50462 ** of BtShared.pageSize, we have discovered that the page-size is
50463 ** actually pageSize. Unlock the database, leave pBt->pPage1 at
50464 ** zero and return SQLITE_OK. The caller will call this function
50465 ** again with the correct page-size.
50467 releasePage(pPage1);
50468 pBt->usableSize = usableSize;
50469 pBt->pageSize = pageSize;
50470 freeTempSpace(pBt);
50471 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
50472 pageSize-usableSize);
50473 return rc;
50475 if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
50476 rc = SQLITE_CORRUPT_BKPT;
50477 goto page1_init_failed;
50479 if( usableSize<480 ){
50480 goto page1_init_failed;
50482 pBt->pageSize = pageSize;
50483 pBt->usableSize = usableSize;
50484 #ifndef SQLITE_OMIT_AUTOVACUUM
50485 pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
50486 pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
50487 #endif
50490 /* maxLocal is the maximum amount of payload to store locally for
50491 ** a cell. Make sure it is small enough so that at least minFanout
50492 ** cells can will fit on one page. We assume a 10-byte page header.
50493 ** Besides the payload, the cell must store:
50494 ** 2-byte pointer to the cell
50495 ** 4-byte child pointer
50496 ** 9-byte nKey value
50497 ** 4-byte nData value
50498 ** 4-byte overflow page pointer
50499 ** So a cell consists of a 2-byte pointer, a header which is as much as
50500 ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
50501 ** page pointer.
50503 pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
50504 pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
50505 pBt->maxLeaf = (u16)(pBt->usableSize - 35);
50506 pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
50507 assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
50508 pBt->pPage1 = pPage1;
50509 pBt->nPage = nPage;
50510 return SQLITE_OK;
50512 page1_init_failed:
50513 releasePage(pPage1);
50514 pBt->pPage1 = 0;
50515 return rc;
50519 ** If there are no outstanding cursors and we are not in the middle
50520 ** of a transaction but there is a read lock on the database, then
50521 ** this routine unrefs the first page of the database file which
50522 ** has the effect of releasing the read lock.
50524 ** If there is a transaction in progress, this routine is a no-op.
50526 static void unlockBtreeIfUnused(BtShared *pBt){
50527 assert( sqlite3_mutex_held(pBt->mutex) );
50528 assert( pBt->pCursor==0 || pBt->inTransaction>TRANS_NONE );
50529 if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
50530 assert( pBt->pPage1->aData );
50531 assert( sqlite3PagerRefcount(pBt->pPager)==1 );
50532 assert( pBt->pPage1->aData );
50533 releasePage(pBt->pPage1);
50534 pBt->pPage1 = 0;
50539 ** If pBt points to an empty file then convert that empty file
50540 ** into a new empty database by initializing the first page of
50541 ** the database.
50543 static int newDatabase(BtShared *pBt){
50544 MemPage *pP1;
50545 unsigned char *data;
50546 int rc;
50548 assert( sqlite3_mutex_held(pBt->mutex) );
50549 if( pBt->nPage>0 ){
50550 return SQLITE_OK;
50552 pP1 = pBt->pPage1;
50553 assert( pP1!=0 );
50554 data = pP1->aData;
50555 rc = sqlite3PagerWrite(pP1->pDbPage);
50556 if( rc ) return rc;
50557 memcpy(data, zMagicHeader, sizeof(zMagicHeader));
50558 assert( sizeof(zMagicHeader)==16 );
50559 data[16] = (u8)((pBt->pageSize>>8)&0xff);
50560 data[17] = (u8)((pBt->pageSize>>16)&0xff);
50561 data[18] = 1;
50562 data[19] = 1;
50563 assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
50564 data[20] = (u8)(pBt->pageSize - pBt->usableSize);
50565 data[21] = 64;
50566 data[22] = 32;
50567 data[23] = 32;
50568 memset(&data[24], 0, 100-24);
50569 zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
50570 pBt->pageSizeFixed = 1;
50571 #ifndef SQLITE_OMIT_AUTOVACUUM
50572 assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
50573 assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
50574 put4byte(&data[36 + 4*4], pBt->autoVacuum);
50575 put4byte(&data[36 + 7*4], pBt->incrVacuum);
50576 #endif
50577 pBt->nPage = 1;
50578 data[31] = 1;
50579 return SQLITE_OK;
50583 ** Attempt to start a new transaction. A write-transaction
50584 ** is started if the second argument is nonzero, otherwise a read-
50585 ** transaction. If the second argument is 2 or more and exclusive
50586 ** transaction is started, meaning that no other process is allowed
50587 ** to access the database. A preexisting transaction may not be
50588 ** upgraded to exclusive by calling this routine a second time - the
50589 ** exclusivity flag only works for a new transaction.
50591 ** A write-transaction must be started before attempting any
50592 ** changes to the database. None of the following routines
50593 ** will work unless a transaction is started first:
50595 ** sqlite3BtreeCreateTable()
50596 ** sqlite3BtreeCreateIndex()
50597 ** sqlite3BtreeClearTable()
50598 ** sqlite3BtreeDropTable()
50599 ** sqlite3BtreeInsert()
50600 ** sqlite3BtreeDelete()
50601 ** sqlite3BtreeUpdateMeta()
50603 ** If an initial attempt to acquire the lock fails because of lock contention
50604 ** and the database was previously unlocked, then invoke the busy handler
50605 ** if there is one. But if there was previously a read-lock, do not
50606 ** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
50607 ** returned when there is already a read-lock in order to avoid a deadlock.
50609 ** Suppose there are two processes A and B. A has a read lock and B has
50610 ** a reserved lock. B tries to promote to exclusive but is blocked because
50611 ** of A's read lock. A tries to promote to reserved but is blocked by B.
50612 ** One or the other of the two processes must give way or there can be
50613 ** no progress. By returning SQLITE_BUSY and not invoking the busy callback
50614 ** when A already has a read lock, we encourage A to give up and let B
50615 ** proceed.
50617 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
50618 sqlite3 *pBlock = 0;
50619 BtShared *pBt = p->pBt;
50620 int rc = SQLITE_OK;
50622 sqlite3BtreeEnter(p);
50623 btreeIntegrity(p);
50625 /* If the btree is already in a write-transaction, or it
50626 ** is already in a read-transaction and a read-transaction
50627 ** is requested, this is a no-op.
50629 if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
50630 goto trans_begun;
50633 /* Write transactions are not possible on a read-only database */
50634 if( pBt->readOnly && wrflag ){
50635 rc = SQLITE_READONLY;
50636 goto trans_begun;
50639 #ifndef SQLITE_OMIT_SHARED_CACHE
50640 /* If another database handle has already opened a write transaction
50641 ** on this shared-btree structure and a second write transaction is
50642 ** requested, return SQLITE_LOCKED.
50644 if( (wrflag && pBt->inTransaction==TRANS_WRITE) || pBt->isPending ){
50645 pBlock = pBt->pWriter->db;
50646 }else if( wrflag>1 ){
50647 BtLock *pIter;
50648 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
50649 if( pIter->pBtree!=p ){
50650 pBlock = pIter->pBtree->db;
50651 break;
50655 if( pBlock ){
50656 sqlite3ConnectionBlocked(p->db, pBlock);
50657 rc = SQLITE_LOCKED_SHAREDCACHE;
50658 goto trans_begun;
50660 #endif
50662 /* Any read-only or read-write transaction implies a read-lock on
50663 ** page 1. So if some other shared-cache client already has a write-lock
50664 ** on page 1, the transaction cannot be opened. */
50665 rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
50666 if( SQLITE_OK!=rc ) goto trans_begun;
50668 pBt->initiallyEmpty = (u8)(pBt->nPage==0);
50669 do {
50670 /* Call lockBtree() until either pBt->pPage1 is populated or
50671 ** lockBtree() returns something other than SQLITE_OK. lockBtree()
50672 ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
50673 ** reading page 1 it discovers that the page-size of the database
50674 ** file is not pBt->pageSize. In this case lockBtree() will update
50675 ** pBt->pageSize to the page-size of the file on disk.
50677 while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
50679 if( rc==SQLITE_OK && wrflag ){
50680 if( pBt->readOnly ){
50681 rc = SQLITE_READONLY;
50682 }else{
50683 rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
50684 if( rc==SQLITE_OK ){
50685 rc = newDatabase(pBt);
50690 if( rc!=SQLITE_OK ){
50691 unlockBtreeIfUnused(pBt);
50693 }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
50694 btreeInvokeBusyHandler(pBt) );
50696 if( rc==SQLITE_OK ){
50697 if( p->inTrans==TRANS_NONE ){
50698 pBt->nTransaction++;
50699 #ifndef SQLITE_OMIT_SHARED_CACHE
50700 if( p->sharable ){
50701 assert( p->lock.pBtree==p && p->lock.iTable==1 );
50702 p->lock.eLock = READ_LOCK;
50703 p->lock.pNext = pBt->pLock;
50704 pBt->pLock = &p->lock;
50706 #endif
50708 p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
50709 if( p->inTrans>pBt->inTransaction ){
50710 pBt->inTransaction = p->inTrans;
50712 if( wrflag ){
50713 MemPage *pPage1 = pBt->pPage1;
50714 #ifndef SQLITE_OMIT_SHARED_CACHE
50715 assert( !pBt->pWriter );
50716 pBt->pWriter = p;
50717 pBt->isExclusive = (u8)(wrflag>1);
50718 #endif
50720 /* If the db-size header field is incorrect (as it may be if an old
50721 ** client has been writing the database file), update it now. Doing
50722 ** this sooner rather than later means the database size can safely
50723 ** re-read the database size from page 1 if a savepoint or transaction
50724 ** rollback occurs within the transaction.
50726 if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
50727 rc = sqlite3PagerWrite(pPage1->pDbPage);
50728 if( rc==SQLITE_OK ){
50729 put4byte(&pPage1->aData[28], pBt->nPage);
50736 trans_begun:
50737 if( rc==SQLITE_OK && wrflag ){
50738 /* This call makes sure that the pager has the correct number of
50739 ** open savepoints. If the second parameter is greater than 0 and
50740 ** the sub-journal is not already open, then it will be opened here.
50742 rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
50745 btreeIntegrity(p);
50746 sqlite3BtreeLeave(p);
50747 return rc;
50750 #ifndef SQLITE_OMIT_AUTOVACUUM
50753 ** Set the pointer-map entries for all children of page pPage. Also, if
50754 ** pPage contains cells that point to overflow pages, set the pointer
50755 ** map entries for the overflow pages as well.
50757 static int setChildPtrmaps(MemPage *pPage){
50758 int i; /* Counter variable */
50759 int nCell; /* Number of cells in page pPage */
50760 int rc; /* Return code */
50761 BtShared *pBt = pPage->pBt;
50762 u8 isInitOrig = pPage->isInit;
50763 Pgno pgno = pPage->pgno;
50765 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50766 rc = btreeInitPage(pPage);
50767 if( rc!=SQLITE_OK ){
50768 goto set_child_ptrmaps_out;
50770 nCell = pPage->nCell;
50772 for(i=0; i<nCell; i++){
50773 u8 *pCell = findCell(pPage, i);
50775 ptrmapPutOvflPtr(pPage, pCell, &rc);
50777 if( !pPage->leaf ){
50778 Pgno childPgno = get4byte(pCell);
50779 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
50783 if( !pPage->leaf ){
50784 Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
50785 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
50788 set_child_ptrmaps_out:
50789 pPage->isInit = isInitOrig;
50790 return rc;
50794 ** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so
50795 ** that it points to iTo. Parameter eType describes the type of pointer to
50796 ** be modified, as follows:
50798 ** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
50799 ** page of pPage.
50801 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
50802 ** page pointed to by one of the cells on pPage.
50804 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
50805 ** overflow page in the list.
50807 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
50808 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50809 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
50810 if( eType==PTRMAP_OVERFLOW2 ){
50811 /* The pointer is always the first 4 bytes of the page in this case. */
50812 if( get4byte(pPage->aData)!=iFrom ){
50813 return SQLITE_CORRUPT_BKPT;
50815 put4byte(pPage->aData, iTo);
50816 }else{
50817 u8 isInitOrig = pPage->isInit;
50818 int i;
50819 int nCell;
50821 btreeInitPage(pPage);
50822 nCell = pPage->nCell;
50824 for(i=0; i<nCell; i++){
50825 u8 *pCell = findCell(pPage, i);
50826 if( eType==PTRMAP_OVERFLOW1 ){
50827 CellInfo info;
50828 btreeParseCellPtr(pPage, pCell, &info);
50829 if( info.iOverflow
50830 && pCell+info.iOverflow+3<=pPage->aData+pPage->maskPage
50831 && iFrom==get4byte(&pCell[info.iOverflow])
50833 put4byte(&pCell[info.iOverflow], iTo);
50834 break;
50836 }else{
50837 if( get4byte(pCell)==iFrom ){
50838 put4byte(pCell, iTo);
50839 break;
50844 if( i==nCell ){
50845 if( eType!=PTRMAP_BTREE ||
50846 get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
50847 return SQLITE_CORRUPT_BKPT;
50849 put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
50852 pPage->isInit = isInitOrig;
50854 return SQLITE_OK;
50859 ** Move the open database page pDbPage to location iFreePage in the
50860 ** database. The pDbPage reference remains valid.
50862 ** The isCommit flag indicates that there is no need to remember that
50863 ** the journal needs to be sync()ed before database page pDbPage->pgno
50864 ** can be written to. The caller has already promised not to write to that
50865 ** page.
50867 static int relocatePage(
50868 BtShared *pBt, /* Btree */
50869 MemPage *pDbPage, /* Open page to move */
50870 u8 eType, /* Pointer map 'type' entry for pDbPage */
50871 Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
50872 Pgno iFreePage, /* The location to move pDbPage to */
50873 int isCommit /* isCommit flag passed to sqlite3PagerMovepage */
50875 MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
50876 Pgno iDbPage = pDbPage->pgno;
50877 Pager *pPager = pBt->pPager;
50878 int rc;
50880 assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
50881 eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
50882 assert( sqlite3_mutex_held(pBt->mutex) );
50883 assert( pDbPage->pBt==pBt );
50885 /* Move page iDbPage from its current location to page number iFreePage */
50886 TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
50887 iDbPage, iFreePage, iPtrPage, eType));
50888 rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
50889 if( rc!=SQLITE_OK ){
50890 return rc;
50892 pDbPage->pgno = iFreePage;
50894 /* If pDbPage was a btree-page, then it may have child pages and/or cells
50895 ** that point to overflow pages. The pointer map entries for all these
50896 ** pages need to be changed.
50898 ** If pDbPage is an overflow page, then the first 4 bytes may store a
50899 ** pointer to a subsequent overflow page. If this is the case, then
50900 ** the pointer map needs to be updated for the subsequent overflow page.
50902 if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
50903 rc = setChildPtrmaps(pDbPage);
50904 if( rc!=SQLITE_OK ){
50905 return rc;
50907 }else{
50908 Pgno nextOvfl = get4byte(pDbPage->aData);
50909 if( nextOvfl!=0 ){
50910 ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
50911 if( rc!=SQLITE_OK ){
50912 return rc;
50917 /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
50918 ** that it points at iFreePage. Also fix the pointer map entry for
50919 ** iPtrPage.
50921 if( eType!=PTRMAP_ROOTPAGE ){
50922 rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
50923 if( rc!=SQLITE_OK ){
50924 return rc;
50926 rc = sqlite3PagerWrite(pPtrPage->pDbPage);
50927 if( rc!=SQLITE_OK ){
50928 releasePage(pPtrPage);
50929 return rc;
50931 rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
50932 releasePage(pPtrPage);
50933 if( rc==SQLITE_OK ){
50934 ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
50937 return rc;
50940 /* Forward declaration required by incrVacuumStep(). */
50941 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
50944 ** Perform a single step of an incremental-vacuum. If successful,
50945 ** return SQLITE_OK. If there is no work to do (and therefore no
50946 ** point in calling this function again), return SQLITE_DONE.
50948 ** More specificly, this function attempts to re-organize the
50949 ** database so that the last page of the file currently in use
50950 ** is no longer in use.
50952 ** If the nFin parameter is non-zero, this function assumes
50953 ** that the caller will keep calling incrVacuumStep() until
50954 ** it returns SQLITE_DONE or an error, and that nFin is the
50955 ** number of pages the database file will contain after this
50956 ** process is complete. If nFin is zero, it is assumed that
50957 ** incrVacuumStep() will be called a finite amount of times
50958 ** which may or may not empty the freelist. A full autovacuum
50959 ** has nFin>0. A "PRAGMA incremental_vacuum" has nFin==0.
50961 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg){
50962 Pgno nFreeList; /* Number of pages still on the free-list */
50963 int rc;
50965 assert( sqlite3_mutex_held(pBt->mutex) );
50966 assert( iLastPg>nFin );
50968 if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
50969 u8 eType;
50970 Pgno iPtrPage;
50972 nFreeList = get4byte(&pBt->pPage1->aData[36]);
50973 if( nFreeList==0 ){
50974 return SQLITE_DONE;
50977 rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
50978 if( rc!=SQLITE_OK ){
50979 return rc;
50981 if( eType==PTRMAP_ROOTPAGE ){
50982 return SQLITE_CORRUPT_BKPT;
50985 if( eType==PTRMAP_FREEPAGE ){
50986 if( nFin==0 ){
50987 /* Remove the page from the files free-list. This is not required
50988 ** if nFin is non-zero. In that case, the free-list will be
50989 ** truncated to zero after this function returns, so it doesn't
50990 ** matter if it still contains some garbage entries.
50992 Pgno iFreePg;
50993 MemPage *pFreePg;
50994 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
50995 if( rc!=SQLITE_OK ){
50996 return rc;
50998 assert( iFreePg==iLastPg );
50999 releasePage(pFreePg);
51001 } else {
51002 Pgno iFreePg; /* Index of free page to move pLastPg to */
51003 MemPage *pLastPg;
51005 rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
51006 if( rc!=SQLITE_OK ){
51007 return rc;
51010 /* If nFin is zero, this loop runs exactly once and page pLastPg
51011 ** is swapped with the first free page pulled off the free list.
51013 ** On the other hand, if nFin is greater than zero, then keep
51014 ** looping until a free-page located within the first nFin pages
51015 ** of the file is found.
51017 do {
51018 MemPage *pFreePg;
51019 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
51020 if( rc!=SQLITE_OK ){
51021 releasePage(pLastPg);
51022 return rc;
51024 releasePage(pFreePg);
51025 }while( nFin!=0 && iFreePg>nFin );
51026 assert( iFreePg<iLastPg );
51028 rc = sqlite3PagerWrite(pLastPg->pDbPage);
51029 if( rc==SQLITE_OK ){
51030 rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, nFin!=0);
51032 releasePage(pLastPg);
51033 if( rc!=SQLITE_OK ){
51034 return rc;
51039 if( nFin==0 ){
51040 iLastPg--;
51041 while( iLastPg==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, iLastPg) ){
51042 if( PTRMAP_ISPAGE(pBt, iLastPg) ){
51043 MemPage *pPg;
51044 rc = btreeGetPage(pBt, iLastPg, &pPg, 0);
51045 if( rc!=SQLITE_OK ){
51046 return rc;
51048 rc = sqlite3PagerWrite(pPg->pDbPage);
51049 releasePage(pPg);
51050 if( rc!=SQLITE_OK ){
51051 return rc;
51054 iLastPg--;
51056 sqlite3PagerTruncateImage(pBt->pPager, iLastPg);
51057 pBt->nPage = iLastPg;
51059 return SQLITE_OK;
51063 ** A write-transaction must be opened before calling this function.
51064 ** It performs a single unit of work towards an incremental vacuum.
51066 ** If the incremental vacuum is finished after this function has run,
51067 ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
51068 ** SQLITE_OK is returned. Otherwise an SQLite error code.
51070 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
51071 int rc;
51072 BtShared *pBt = p->pBt;
51074 sqlite3BtreeEnter(p);
51075 assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
51076 if( !pBt->autoVacuum ){
51077 rc = SQLITE_DONE;
51078 }else{
51079 invalidateAllOverflowCache(pBt);
51080 rc = incrVacuumStep(pBt, 0, btreePagecount(pBt));
51081 if( rc==SQLITE_OK ){
51082 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
51083 put4byte(&pBt->pPage1->aData[28], pBt->nPage);
51086 sqlite3BtreeLeave(p);
51087 return rc;
51091 ** This routine is called prior to sqlite3PagerCommit when a transaction
51092 ** is commited for an auto-vacuum database.
51094 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
51095 ** the database file should be truncated to during the commit process.
51096 ** i.e. the database has been reorganized so that only the first *pnTrunc
51097 ** pages are in use.
51099 static int autoVacuumCommit(BtShared *pBt){
51100 int rc = SQLITE_OK;
51101 Pager *pPager = pBt->pPager;
51102 VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
51104 assert( sqlite3_mutex_held(pBt->mutex) );
51105 invalidateAllOverflowCache(pBt);
51106 assert(pBt->autoVacuum);
51107 if( !pBt->incrVacuum ){
51108 Pgno nFin; /* Number of pages in database after autovacuuming */
51109 Pgno nFree; /* Number of pages on the freelist initially */
51110 Pgno nPtrmap; /* Number of PtrMap pages to be freed */
51111 Pgno iFree; /* The next page to be freed */
51112 int nEntry; /* Number of entries on one ptrmap page */
51113 Pgno nOrig; /* Database size before freeing */
51115 nOrig = btreePagecount(pBt);
51116 if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
51117 /* It is not possible to create a database for which the final page
51118 ** is either a pointer-map page or the pending-byte page. If one
51119 ** is encountered, this indicates corruption.
51121 return SQLITE_CORRUPT_BKPT;
51124 nFree = get4byte(&pBt->pPage1->aData[36]);
51125 nEntry = pBt->usableSize/5;
51126 nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
51127 nFin = nOrig - nFree - nPtrmap;
51128 if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
51129 nFin--;
51131 while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
51132 nFin--;
51134 if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
51136 for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
51137 rc = incrVacuumStep(pBt, nFin, iFree);
51139 if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
51140 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
51141 put4byte(&pBt->pPage1->aData[32], 0);
51142 put4byte(&pBt->pPage1->aData[36], 0);
51143 put4byte(&pBt->pPage1->aData[28], nFin);
51144 sqlite3PagerTruncateImage(pBt->pPager, nFin);
51145 pBt->nPage = nFin;
51147 if( rc!=SQLITE_OK ){
51148 sqlite3PagerRollback(pPager);
51152 assert( nRef==sqlite3PagerRefcount(pPager) );
51153 return rc;
51156 #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
51157 # define setChildPtrmaps(x) SQLITE_OK
51158 #endif
51161 ** This routine does the first phase of a two-phase commit. This routine
51162 ** causes a rollback journal to be created (if it does not already exist)
51163 ** and populated with enough information so that if a power loss occurs
51164 ** the database can be restored to its original state by playing back
51165 ** the journal. Then the contents of the journal are flushed out to
51166 ** the disk. After the journal is safely on oxide, the changes to the
51167 ** database are written into the database file and flushed to oxide.
51168 ** At the end of this call, the rollback journal still exists on the
51169 ** disk and we are still holding all locks, so the transaction has not
51170 ** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
51171 ** commit process.
51173 ** This call is a no-op if no write-transaction is currently active on pBt.
51175 ** Otherwise, sync the database file for the btree pBt. zMaster points to
51176 ** the name of a master journal file that should be written into the
51177 ** individual journal file, or is NULL, indicating no master journal file
51178 ** (single database transaction).
51180 ** When this is called, the master journal should already have been
51181 ** created, populated with this journal pointer and synced to disk.
51183 ** Once this is routine has returned, the only thing required to commit
51184 ** the write-transaction for this database file is to delete the journal.
51186 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
51187 int rc = SQLITE_OK;
51188 if( p->inTrans==TRANS_WRITE ){
51189 BtShared *pBt = p->pBt;
51190 sqlite3BtreeEnter(p);
51191 #ifndef SQLITE_OMIT_AUTOVACUUM
51192 if( pBt->autoVacuum ){
51193 rc = autoVacuumCommit(pBt);
51194 if( rc!=SQLITE_OK ){
51195 sqlite3BtreeLeave(p);
51196 return rc;
51199 #endif
51200 rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
51201 sqlite3BtreeLeave(p);
51203 return rc;
51207 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
51208 ** at the conclusion of a transaction.
51210 static void btreeEndTransaction(Btree *p){
51211 BtShared *pBt = p->pBt;
51212 assert( sqlite3BtreeHoldsMutex(p) );
51214 btreeClearHasContent(pBt);
51215 if( p->inTrans>TRANS_NONE && p->db->activeVdbeCnt>1 ){
51216 /* If there are other active statements that belong to this database
51217 ** handle, downgrade to a read-only transaction. The other statements
51218 ** may still be reading from the database. */
51219 downgradeAllSharedCacheTableLocks(p);
51220 p->inTrans = TRANS_READ;
51221 }else{
51222 /* If the handle had any kind of transaction open, decrement the
51223 ** transaction count of the shared btree. If the transaction count
51224 ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
51225 ** call below will unlock the pager. */
51226 if( p->inTrans!=TRANS_NONE ){
51227 clearAllSharedCacheTableLocks(p);
51228 pBt->nTransaction--;
51229 if( 0==pBt->nTransaction ){
51230 pBt->inTransaction = TRANS_NONE;
51234 /* Set the current transaction state to TRANS_NONE and unlock the
51235 ** pager if this call closed the only read or write transaction. */
51236 p->inTrans = TRANS_NONE;
51237 unlockBtreeIfUnused(pBt);
51240 btreeIntegrity(p);
51244 ** Commit the transaction currently in progress.
51246 ** This routine implements the second phase of a 2-phase commit. The
51247 ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
51248 ** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
51249 ** routine did all the work of writing information out to disk and flushing the
51250 ** contents so that they are written onto the disk platter. All this
51251 ** routine has to do is delete or truncate or zero the header in the
51252 ** the rollback journal (which causes the transaction to commit) and
51253 ** drop locks.
51255 ** Normally, if an error occurs while the pager layer is attempting to
51256 ** finalize the underlying journal file, this function returns an error and
51257 ** the upper layer will attempt a rollback. However, if the second argument
51258 ** is non-zero then this b-tree transaction is part of a multi-file
51259 ** transaction. In this case, the transaction has already been committed
51260 ** (by deleting a master journal file) and the caller will ignore this
51261 ** functions return code. So, even if an error occurs in the pager layer,
51262 ** reset the b-tree objects internal state to indicate that the write
51263 ** transaction has been closed. This is quite safe, as the pager will have
51264 ** transitioned to the error state.
51266 ** This will release the write lock on the database file. If there
51267 ** are no active cursors, it also releases the read lock.
51269 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
51271 if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
51272 sqlite3BtreeEnter(p);
51273 btreeIntegrity(p);
51275 /* If the handle has a write-transaction open, commit the shared-btrees
51276 ** transaction and set the shared state to TRANS_READ.
51278 if( p->inTrans==TRANS_WRITE ){
51279 int rc;
51280 BtShared *pBt = p->pBt;
51281 assert( pBt->inTransaction==TRANS_WRITE );
51282 assert( pBt->nTransaction>0 );
51283 rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
51284 if( rc!=SQLITE_OK && bCleanup==0 ){
51285 sqlite3BtreeLeave(p);
51286 return rc;
51288 pBt->inTransaction = TRANS_READ;
51291 btreeEndTransaction(p);
51292 sqlite3BtreeLeave(p);
51293 return SQLITE_OK;
51297 ** Do both phases of a commit.
51299 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
51300 int rc;
51301 sqlite3BtreeEnter(p);
51302 rc = sqlite3BtreeCommitPhaseOne(p, 0);
51303 if( rc==SQLITE_OK ){
51304 rc = sqlite3BtreeCommitPhaseTwo(p, 0);
51306 sqlite3BtreeLeave(p);
51307 return rc;
51310 #ifndef NDEBUG
51312 ** Return the number of write-cursors open on this handle. This is for use
51313 ** in assert() expressions, so it is only compiled if NDEBUG is not
51314 ** defined.
51316 ** For the purposes of this routine, a write-cursor is any cursor that
51317 ** is capable of writing to the databse. That means the cursor was
51318 ** originally opened for writing and the cursor has not be disabled
51319 ** by having its state changed to CURSOR_FAULT.
51321 static int countWriteCursors(BtShared *pBt){
51322 BtCursor *pCur;
51323 int r = 0;
51324 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
51325 if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++;
51327 return r;
51329 #endif
51332 ** This routine sets the state to CURSOR_FAULT and the error
51333 ** code to errCode for every cursor on BtShared that pBtree
51334 ** references.
51336 ** Every cursor is tripped, including cursors that belong
51337 ** to other database connections that happen to be sharing
51338 ** the cache with pBtree.
51340 ** This routine gets called when a rollback occurs.
51341 ** All cursors using the same cache must be tripped
51342 ** to prevent them from trying to use the btree after
51343 ** the rollback. The rollback may have deleted tables
51344 ** or moved root pages, so it is not sufficient to
51345 ** save the state of the cursor. The cursor must be
51346 ** invalidated.
51348 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
51349 BtCursor *p;
51350 sqlite3BtreeEnter(pBtree);
51351 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
51352 int i;
51353 sqlite3BtreeClearCursor(p);
51354 p->eState = CURSOR_FAULT;
51355 p->skipNext = errCode;
51356 for(i=0; i<=p->iPage; i++){
51357 releasePage(p->apPage[i]);
51358 p->apPage[i] = 0;
51361 sqlite3BtreeLeave(pBtree);
51365 ** Rollback the transaction in progress. All cursors will be
51366 ** invalided by this operation. Any attempt to use a cursor
51367 ** that was open at the beginning of this operation will result
51368 ** in an error.
51370 ** This will release the write lock on the database file. If there
51371 ** are no active cursors, it also releases the read lock.
51373 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p){
51374 int rc;
51375 BtShared *pBt = p->pBt;
51376 MemPage *pPage1;
51378 sqlite3BtreeEnter(p);
51379 rc = saveAllCursors(pBt, 0, 0);
51380 #ifndef SQLITE_OMIT_SHARED_CACHE
51381 if( rc!=SQLITE_OK ){
51382 /* This is a horrible situation. An IO or malloc() error occurred whilst
51383 ** trying to save cursor positions. If this is an automatic rollback (as
51384 ** the result of a constraint, malloc() failure or IO error) then
51385 ** the cache may be internally inconsistent (not contain valid trees) so
51386 ** we cannot simply return the error to the caller. Instead, abort
51387 ** all queries that may be using any of the cursors that failed to save.
51389 sqlite3BtreeTripAllCursors(p, rc);
51391 #endif
51392 btreeIntegrity(p);
51394 if( p->inTrans==TRANS_WRITE ){
51395 int rc2;
51397 assert( TRANS_WRITE==pBt->inTransaction );
51398 rc2 = sqlite3PagerRollback(pBt->pPager);
51399 if( rc2!=SQLITE_OK ){
51400 rc = rc2;
51403 /* The rollback may have destroyed the pPage1->aData value. So
51404 ** call btreeGetPage() on page 1 again to make
51405 ** sure pPage1->aData is set correctly. */
51406 if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
51407 int nPage = get4byte(28+(u8*)pPage1->aData);
51408 testcase( nPage==0 );
51409 if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
51410 testcase( pBt->nPage!=nPage );
51411 pBt->nPage = nPage;
51412 releasePage(pPage1);
51414 assert( countWriteCursors(pBt)==0 );
51415 pBt->inTransaction = TRANS_READ;
51418 btreeEndTransaction(p);
51419 sqlite3BtreeLeave(p);
51420 return rc;
51424 ** Start a statement subtransaction. The subtransaction can can be rolled
51425 ** back independently of the main transaction. You must start a transaction
51426 ** before starting a subtransaction. The subtransaction is ended automatically
51427 ** if the main transaction commits or rolls back.
51429 ** Statement subtransactions are used around individual SQL statements
51430 ** that are contained within a BEGIN...COMMIT block. If a constraint
51431 ** error occurs within the statement, the effect of that one statement
51432 ** can be rolled back without having to rollback the entire transaction.
51434 ** A statement sub-transaction is implemented as an anonymous savepoint. The
51435 ** value passed as the second parameter is the total number of savepoints,
51436 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
51437 ** are no active savepoints and no other statement-transactions open,
51438 ** iStatement is 1. This anonymous savepoint can be released or rolled back
51439 ** using the sqlite3BtreeSavepoint() function.
51441 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
51442 int rc;
51443 BtShared *pBt = p->pBt;
51444 sqlite3BtreeEnter(p);
51445 assert( p->inTrans==TRANS_WRITE );
51446 assert( pBt->readOnly==0 );
51447 assert( iStatement>0 );
51448 assert( iStatement>p->db->nSavepoint );
51449 assert( pBt->inTransaction==TRANS_WRITE );
51450 /* At the pager level, a statement transaction is a savepoint with
51451 ** an index greater than all savepoints created explicitly using
51452 ** SQL statements. It is illegal to open, release or rollback any
51453 ** such savepoints while the statement transaction savepoint is active.
51455 rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
51456 sqlite3BtreeLeave(p);
51457 return rc;
51461 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
51462 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
51463 ** savepoint identified by parameter iSavepoint, depending on the value
51464 ** of op.
51466 ** Normally, iSavepoint is greater than or equal to zero. However, if op is
51467 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
51468 ** contents of the entire transaction are rolled back. This is different
51469 ** from a normal transaction rollback, as no locks are released and the
51470 ** transaction remains open.
51472 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
51473 int rc = SQLITE_OK;
51474 if( p && p->inTrans==TRANS_WRITE ){
51475 BtShared *pBt = p->pBt;
51476 assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
51477 assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
51478 sqlite3BtreeEnter(p);
51479 rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
51480 if( rc==SQLITE_OK ){
51481 if( iSavepoint<0 && pBt->initiallyEmpty ) pBt->nPage = 0;
51482 rc = newDatabase(pBt);
51483 pBt->nPage = get4byte(28 + pBt->pPage1->aData);
51485 /* The database size was written into the offset 28 of the header
51486 ** when the transaction started, so we know that the value at offset
51487 ** 28 is nonzero. */
51488 assert( pBt->nPage>0 );
51490 sqlite3BtreeLeave(p);
51492 return rc;
51496 ** Create a new cursor for the BTree whose root is on the page
51497 ** iTable. If a read-only cursor is requested, it is assumed that
51498 ** the caller already has at least a read-only transaction open
51499 ** on the database already. If a write-cursor is requested, then
51500 ** the caller is assumed to have an open write transaction.
51502 ** If wrFlag==0, then the cursor can only be used for reading.
51503 ** If wrFlag==1, then the cursor can be used for reading or for
51504 ** writing if other conditions for writing are also met. These
51505 ** are the conditions that must be met in order for writing to
51506 ** be allowed:
51508 ** 1: The cursor must have been opened with wrFlag==1
51510 ** 2: Other database connections that share the same pager cache
51511 ** but which are not in the READ_UNCOMMITTED state may not have
51512 ** cursors open with wrFlag==0 on the same table. Otherwise
51513 ** the changes made by this write cursor would be visible to
51514 ** the read cursors in the other database connection.
51516 ** 3: The database must be writable (not on read-only media)
51518 ** 4: There must be an active transaction.
51520 ** No checking is done to make sure that page iTable really is the
51521 ** root page of a b-tree. If it is not, then the cursor acquired
51522 ** will not work correctly.
51524 ** It is assumed that the sqlite3BtreeCursorZero() has been called
51525 ** on pCur to initialize the memory space prior to invoking this routine.
51527 static int btreeCursor(
51528 Btree *p, /* The btree */
51529 int iTable, /* Root page of table to open */
51530 int wrFlag, /* 1 to write. 0 read-only */
51531 struct KeyInfo *pKeyInfo, /* First arg to comparison function */
51532 BtCursor *pCur /* Space for new cursor */
51534 BtShared *pBt = p->pBt; /* Shared b-tree handle */
51536 assert( sqlite3BtreeHoldsMutex(p) );
51537 assert( wrFlag==0 || wrFlag==1 );
51539 /* The following assert statements verify that if this is a sharable
51540 ** b-tree database, the connection is holding the required table locks,
51541 ** and that no other connection has any open cursor that conflicts with
51542 ** this lock. */
51543 assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
51544 assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
51546 /* Assert that the caller has opened the required transaction. */
51547 assert( p->inTrans>TRANS_NONE );
51548 assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
51549 assert( pBt->pPage1 && pBt->pPage1->aData );
51551 if( NEVER(wrFlag && pBt->readOnly) ){
51552 return SQLITE_READONLY;
51554 if( iTable==1 && btreePagecount(pBt)==0 ){
51555 assert( wrFlag==0 );
51556 iTable = 0;
51559 /* Now that no other errors can occur, finish filling in the BtCursor
51560 ** variables and link the cursor into the BtShared list. */
51561 pCur->pgnoRoot = (Pgno)iTable;
51562 pCur->iPage = -1;
51563 pCur->pKeyInfo = pKeyInfo;
51564 pCur->pBtree = p;
51565 pCur->pBt = pBt;
51566 pCur->wrFlag = (u8)wrFlag;
51567 pCur->pNext = pBt->pCursor;
51568 if( pCur->pNext ){
51569 pCur->pNext->pPrev = pCur;
51571 pBt->pCursor = pCur;
51572 pCur->eState = CURSOR_INVALID;
51573 pCur->cachedRowid = 0;
51574 return SQLITE_OK;
51576 SQLITE_PRIVATE int sqlite3BtreeCursor(
51577 Btree *p, /* The btree */
51578 int iTable, /* Root page of table to open */
51579 int wrFlag, /* 1 to write. 0 read-only */
51580 struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
51581 BtCursor *pCur /* Write new cursor here */
51583 int rc;
51584 sqlite3BtreeEnter(p);
51585 rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
51586 sqlite3BtreeLeave(p);
51587 return rc;
51591 ** Return the size of a BtCursor object in bytes.
51593 ** This interfaces is needed so that users of cursors can preallocate
51594 ** sufficient storage to hold a cursor. The BtCursor object is opaque
51595 ** to users so they cannot do the sizeof() themselves - they must call
51596 ** this routine.
51598 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
51599 return ROUND8(sizeof(BtCursor));
51603 ** Initialize memory that will be converted into a BtCursor object.
51605 ** The simple approach here would be to memset() the entire object
51606 ** to zero. But it turns out that the apPage[] and aiIdx[] arrays
51607 ** do not need to be zeroed and they are large, so we can save a lot
51608 ** of run-time by skipping the initialization of those elements.
51610 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
51611 memset(p, 0, offsetof(BtCursor, iPage));
51615 ** Set the cached rowid value of every cursor in the same database file
51616 ** as pCur and having the same root page number as pCur. The value is
51617 ** set to iRowid.
51619 ** Only positive rowid values are considered valid for this cache.
51620 ** The cache is initialized to zero, indicating an invalid cache.
51621 ** A btree will work fine with zero or negative rowids. We just cannot
51622 ** cache zero or negative rowids, which means tables that use zero or
51623 ** negative rowids might run a little slower. But in practice, zero
51624 ** or negative rowids are very uncommon so this should not be a problem.
51626 SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){
51627 BtCursor *p;
51628 for(p=pCur->pBt->pCursor; p; p=p->pNext){
51629 if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid;
51631 assert( pCur->cachedRowid==iRowid );
51635 ** Return the cached rowid for the given cursor. A negative or zero
51636 ** return value indicates that the rowid cache is invalid and should be
51637 ** ignored. If the rowid cache has never before been set, then a
51638 ** zero is returned.
51640 SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){
51641 return pCur->cachedRowid;
51645 ** Close a cursor. The read lock on the database file is released
51646 ** when the last cursor is closed.
51648 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
51649 Btree *pBtree = pCur->pBtree;
51650 if( pBtree ){
51651 int i;
51652 BtShared *pBt = pCur->pBt;
51653 sqlite3BtreeEnter(pBtree);
51654 sqlite3BtreeClearCursor(pCur);
51655 if( pCur->pPrev ){
51656 pCur->pPrev->pNext = pCur->pNext;
51657 }else{
51658 pBt->pCursor = pCur->pNext;
51660 if( pCur->pNext ){
51661 pCur->pNext->pPrev = pCur->pPrev;
51663 for(i=0; i<=pCur->iPage; i++){
51664 releasePage(pCur->apPage[i]);
51666 unlockBtreeIfUnused(pBt);
51667 invalidateOverflowCache(pCur);
51668 /* sqlite3_free(pCur); */
51669 sqlite3BtreeLeave(pBtree);
51671 return SQLITE_OK;
51675 ** Make sure the BtCursor* given in the argument has a valid
51676 ** BtCursor.info structure. If it is not already valid, call
51677 ** btreeParseCell() to fill it in.
51679 ** BtCursor.info is a cache of the information in the current cell.
51680 ** Using this cache reduces the number of calls to btreeParseCell().
51682 ** 2007-06-25: There is a bug in some versions of MSVC that cause the
51683 ** compiler to crash when getCellInfo() is implemented as a macro.
51684 ** But there is a measureable speed advantage to using the macro on gcc
51685 ** (when less compiler optimizations like -Os or -O0 are used and the
51686 ** compiler is not doing agressive inlining.) So we use a real function
51687 ** for MSVC and a macro for everything else. Ticket #2457.
51689 #ifndef NDEBUG
51690 static void assertCellInfo(BtCursor *pCur){
51691 CellInfo info;
51692 int iPage = pCur->iPage;
51693 memset(&info, 0, sizeof(info));
51694 btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
51695 assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
51697 #else
51698 #define assertCellInfo(x)
51699 #endif
51700 #ifdef _MSC_VER
51701 /* Use a real function in MSVC to work around bugs in that compiler. */
51702 static void getCellInfo(BtCursor *pCur){
51703 if( pCur->info.nSize==0 ){
51704 int iPage = pCur->iPage;
51705 btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
51706 pCur->validNKey = 1;
51707 }else{
51708 assertCellInfo(pCur);
51711 #else /* if not _MSC_VER */
51712 /* Use a macro in all other compilers so that the function is inlined */
51713 #define getCellInfo(pCur) \
51714 if( pCur->info.nSize==0 ){ \
51715 int iPage = pCur->iPage; \
51716 btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
51717 pCur->validNKey = 1; \
51718 }else{ \
51719 assertCellInfo(pCur); \
51721 #endif /* _MSC_VER */
51723 #ifndef NDEBUG /* The next routine used only within assert() statements */
51725 ** Return true if the given BtCursor is valid. A valid cursor is one
51726 ** that is currently pointing to a row in a (non-empty) table.
51727 ** This is a verification routine is used only within assert() statements.
51729 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
51730 return pCur && pCur->eState==CURSOR_VALID;
51732 #endif /* NDEBUG */
51735 ** Set *pSize to the size of the buffer needed to hold the value of
51736 ** the key for the current entry. If the cursor is not pointing
51737 ** to a valid entry, *pSize is set to 0.
51739 ** For a table with the INTKEY flag set, this routine returns the key
51740 ** itself, not the number of bytes in the key.
51742 ** The caller must position the cursor prior to invoking this routine.
51744 ** This routine cannot fail. It always returns SQLITE_OK.
51746 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
51747 assert( cursorHoldsMutex(pCur) );
51748 assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
51749 if( pCur->eState!=CURSOR_VALID ){
51750 *pSize = 0;
51751 }else{
51752 getCellInfo(pCur);
51753 *pSize = pCur->info.nKey;
51755 return SQLITE_OK;
51759 ** Set *pSize to the number of bytes of data in the entry the
51760 ** cursor currently points to.
51762 ** The caller must guarantee that the cursor is pointing to a non-NULL
51763 ** valid entry. In other words, the calling procedure must guarantee
51764 ** that the cursor has Cursor.eState==CURSOR_VALID.
51766 ** Failure is not possible. This function always returns SQLITE_OK.
51767 ** It might just as well be a procedure (returning void) but we continue
51768 ** to return an integer result code for historical reasons.
51770 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
51771 assert( cursorHoldsMutex(pCur) );
51772 assert( pCur->eState==CURSOR_VALID );
51773 getCellInfo(pCur);
51774 *pSize = pCur->info.nData;
51775 return SQLITE_OK;
51779 ** Given the page number of an overflow page in the database (parameter
51780 ** ovfl), this function finds the page number of the next page in the
51781 ** linked list of overflow pages. If possible, it uses the auto-vacuum
51782 ** pointer-map data instead of reading the content of page ovfl to do so.
51784 ** If an error occurs an SQLite error code is returned. Otherwise:
51786 ** The page number of the next overflow page in the linked list is
51787 ** written to *pPgnoNext. If page ovfl is the last page in its linked
51788 ** list, *pPgnoNext is set to zero.
51790 ** If ppPage is not NULL, and a reference to the MemPage object corresponding
51791 ** to page number pOvfl was obtained, then *ppPage is set to point to that
51792 ** reference. It is the responsibility of the caller to call releasePage()
51793 ** on *ppPage to free the reference. In no reference was obtained (because
51794 ** the pointer-map was used to obtain the value for *pPgnoNext), then
51795 ** *ppPage is set to zero.
51797 static int getOverflowPage(
51798 BtShared *pBt, /* The database file */
51799 Pgno ovfl, /* Current overflow page number */
51800 MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
51801 Pgno *pPgnoNext /* OUT: Next overflow page number */
51803 Pgno next = 0;
51804 MemPage *pPage = 0;
51805 int rc = SQLITE_OK;
51807 assert( sqlite3_mutex_held(pBt->mutex) );
51808 assert(pPgnoNext);
51810 #ifndef SQLITE_OMIT_AUTOVACUUM
51811 /* Try to find the next page in the overflow list using the
51812 ** autovacuum pointer-map pages. Guess that the next page in
51813 ** the overflow list is page number (ovfl+1). If that guess turns
51814 ** out to be wrong, fall back to loading the data of page
51815 ** number ovfl to determine the next page number.
51817 if( pBt->autoVacuum ){
51818 Pgno pgno;
51819 Pgno iGuess = ovfl+1;
51820 u8 eType;
51822 while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
51823 iGuess++;
51826 if( iGuess<=btreePagecount(pBt) ){
51827 rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
51828 if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
51829 next = iGuess;
51830 rc = SQLITE_DONE;
51834 #endif
51836 assert( next==0 || rc==SQLITE_DONE );
51837 if( rc==SQLITE_OK ){
51838 rc = btreeGetPage(pBt, ovfl, &pPage, 0);
51839 assert( rc==SQLITE_OK || pPage==0 );
51840 if( rc==SQLITE_OK ){
51841 next = get4byte(pPage->aData);
51845 *pPgnoNext = next;
51846 if( ppPage ){
51847 *ppPage = pPage;
51848 }else{
51849 releasePage(pPage);
51851 return (rc==SQLITE_DONE ? SQLITE_OK : rc);
51855 ** Copy data from a buffer to a page, or from a page to a buffer.
51857 ** pPayload is a pointer to data stored on database page pDbPage.
51858 ** If argument eOp is false, then nByte bytes of data are copied
51859 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
51860 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
51861 ** of data are copied from the buffer pBuf to pPayload.
51863 ** SQLITE_OK is returned on success, otherwise an error code.
51865 static int copyPayload(
51866 void *pPayload, /* Pointer to page data */
51867 void *pBuf, /* Pointer to buffer */
51868 int nByte, /* Number of bytes to copy */
51869 int eOp, /* 0 -> copy from page, 1 -> copy to page */
51870 DbPage *pDbPage /* Page containing pPayload */
51872 if( eOp ){
51873 /* Copy data from buffer to page (a write operation) */
51874 int rc = sqlite3PagerWrite(pDbPage);
51875 if( rc!=SQLITE_OK ){
51876 return rc;
51878 memcpy(pPayload, pBuf, nByte);
51879 }else{
51880 /* Copy data from page to buffer (a read operation) */
51881 memcpy(pBuf, pPayload, nByte);
51883 return SQLITE_OK;
51887 ** This function is used to read or overwrite payload information
51888 ** for the entry that the pCur cursor is pointing to. If the eOp
51889 ** parameter is 0, this is a read operation (data copied into
51890 ** buffer pBuf). If it is non-zero, a write (data copied from
51891 ** buffer pBuf).
51893 ** A total of "amt" bytes are read or written beginning at "offset".
51894 ** Data is read to or from the buffer pBuf.
51896 ** The content being read or written might appear on the main page
51897 ** or be scattered out on multiple overflow pages.
51899 ** If the BtCursor.isIncrblobHandle flag is set, and the current
51900 ** cursor entry uses one or more overflow pages, this function
51901 ** allocates space for and lazily popluates the overflow page-list
51902 ** cache array (BtCursor.aOverflow). Subsequent calls use this
51903 ** cache to make seeking to the supplied offset more efficient.
51905 ** Once an overflow page-list cache has been allocated, it may be
51906 ** invalidated if some other cursor writes to the same table, or if
51907 ** the cursor is moved to a different row. Additionally, in auto-vacuum
51908 ** mode, the following events may invalidate an overflow page-list cache.
51910 ** * An incremental vacuum,
51911 ** * A commit in auto_vacuum="full" mode,
51912 ** * Creating a table (may require moving an overflow page).
51914 static int accessPayload(
51915 BtCursor *pCur, /* Cursor pointing to entry to read from */
51916 u32 offset, /* Begin reading this far into payload */
51917 u32 amt, /* Read this many bytes */
51918 unsigned char *pBuf, /* Write the bytes into this buffer */
51919 int eOp /* zero to read. non-zero to write. */
51921 unsigned char *aPayload;
51922 int rc = SQLITE_OK;
51923 u32 nKey;
51924 int iIdx = 0;
51925 MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
51926 BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
51928 assert( pPage );
51929 assert( pCur->eState==CURSOR_VALID );
51930 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
51931 assert( cursorHoldsMutex(pCur) );
51933 getCellInfo(pCur);
51934 aPayload = pCur->info.pCell + pCur->info.nHeader;
51935 nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
51937 if( NEVER(offset+amt > nKey+pCur->info.nData)
51938 || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
51940 /* Trying to read or write past the end of the data is an error */
51941 return SQLITE_CORRUPT_BKPT;
51944 /* Check if data must be read/written to/from the btree page itself. */
51945 if( offset<pCur->info.nLocal ){
51946 int a = amt;
51947 if( a+offset>pCur->info.nLocal ){
51948 a = pCur->info.nLocal - offset;
51950 rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
51951 offset = 0;
51952 pBuf += a;
51953 amt -= a;
51954 }else{
51955 offset -= pCur->info.nLocal;
51958 if( rc==SQLITE_OK && amt>0 ){
51959 const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
51960 Pgno nextPage;
51962 nextPage = get4byte(&aPayload[pCur->info.nLocal]);
51964 #ifndef SQLITE_OMIT_INCRBLOB
51965 /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
51966 ** has not been allocated, allocate it now. The array is sized at
51967 ** one entry for each overflow page in the overflow chain. The
51968 ** page number of the first overflow page is stored in aOverflow[0],
51969 ** etc. A value of 0 in the aOverflow[] array means "not yet known"
51970 ** (the cache is lazily populated).
51972 if( pCur->isIncrblobHandle && !pCur->aOverflow ){
51973 int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
51974 pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
51975 /* nOvfl is always positive. If it were zero, fetchPayload would have
51976 ** been used instead of this routine. */
51977 if( ALWAYS(nOvfl) && !pCur->aOverflow ){
51978 rc = SQLITE_NOMEM;
51982 /* If the overflow page-list cache has been allocated and the
51983 ** entry for the first required overflow page is valid, skip
51984 ** directly to it.
51986 if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
51987 iIdx = (offset/ovflSize);
51988 nextPage = pCur->aOverflow[iIdx];
51989 offset = (offset%ovflSize);
51991 #endif
51993 for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
51995 #ifndef SQLITE_OMIT_INCRBLOB
51996 /* If required, populate the overflow page-list cache. */
51997 if( pCur->aOverflow ){
51998 assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
51999 pCur->aOverflow[iIdx] = nextPage;
52001 #endif
52003 if( offset>=ovflSize ){
52004 /* The only reason to read this page is to obtain the page
52005 ** number for the next page in the overflow chain. The page
52006 ** data is not required. So first try to lookup the overflow
52007 ** page-list cache, if any, then fall back to the getOverflowPage()
52008 ** function.
52010 #ifndef SQLITE_OMIT_INCRBLOB
52011 if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
52012 nextPage = pCur->aOverflow[iIdx+1];
52013 } else
52014 #endif
52015 rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
52016 offset -= ovflSize;
52017 }else{
52018 /* Need to read this page properly. It contains some of the
52019 ** range of data that is being read (eOp==0) or written (eOp!=0).
52021 #ifdef SQLITE_DIRECT_OVERFLOW_READ
52022 sqlite3_file *fd;
52023 #endif
52024 int a = amt;
52025 if( a + offset > ovflSize ){
52026 a = ovflSize - offset;
52029 #ifdef SQLITE_DIRECT_OVERFLOW_READ
52030 /* If all the following are true:
52032 ** 1) this is a read operation, and
52033 ** 2) data is required from the start of this overflow page, and
52034 ** 3) the database is file-backed, and
52035 ** 4) there is no open write-transaction, and
52036 ** 5) the database is not a WAL database,
52038 ** then data can be read directly from the database file into the
52039 ** output buffer, bypassing the page-cache altogether. This speeds
52040 ** up loading large records that span many overflow pages.
52042 if( eOp==0 /* (1) */
52043 && offset==0 /* (2) */
52044 && pBt->inTransaction==TRANS_READ /* (4) */
52045 && (fd = sqlite3PagerFile(pBt->pPager))->pMethods /* (3) */
52046 && pBt->pPage1->aData[19]==0x01 /* (5) */
52048 u8 aSave[4];
52049 u8 *aWrite = &pBuf[-4];
52050 memcpy(aSave, aWrite, 4);
52051 rc = sqlite3OsRead(fd, aWrite, a+4, pBt->pageSize * (nextPage-1));
52052 nextPage = get4byte(aWrite);
52053 memcpy(aWrite, aSave, 4);
52054 }else
52055 #endif
52058 DbPage *pDbPage;
52059 rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
52060 if( rc==SQLITE_OK ){
52061 aPayload = sqlite3PagerGetData(pDbPage);
52062 nextPage = get4byte(aPayload);
52063 rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
52064 sqlite3PagerUnref(pDbPage);
52065 offset = 0;
52068 amt -= a;
52069 pBuf += a;
52074 if( rc==SQLITE_OK && amt>0 ){
52075 return SQLITE_CORRUPT_BKPT;
52077 return rc;
52081 ** Read part of the key associated with cursor pCur. Exactly
52082 ** "amt" bytes will be transfered into pBuf[]. The transfer
52083 ** begins at "offset".
52085 ** The caller must ensure that pCur is pointing to a valid row
52086 ** in the table.
52088 ** Return SQLITE_OK on success or an error code if anything goes
52089 ** wrong. An error is returned if "offset+amt" is larger than
52090 ** the available payload.
52092 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
52093 assert( cursorHoldsMutex(pCur) );
52094 assert( pCur->eState==CURSOR_VALID );
52095 assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
52096 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
52097 return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
52101 ** Read part of the data associated with cursor pCur. Exactly
52102 ** "amt" bytes will be transfered into pBuf[]. The transfer
52103 ** begins at "offset".
52105 ** Return SQLITE_OK on success or an error code if anything goes
52106 ** wrong. An error is returned if "offset+amt" is larger than
52107 ** the available payload.
52109 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
52110 int rc;
52112 #ifndef SQLITE_OMIT_INCRBLOB
52113 if ( pCur->eState==CURSOR_INVALID ){
52114 return SQLITE_ABORT;
52116 #endif
52118 assert( cursorHoldsMutex(pCur) );
52119 rc = restoreCursorPosition(pCur);
52120 if( rc==SQLITE_OK ){
52121 assert( pCur->eState==CURSOR_VALID );
52122 assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
52123 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
52124 rc = accessPayload(pCur, offset, amt, pBuf, 0);
52126 return rc;
52130 ** Return a pointer to payload information from the entry that the
52131 ** pCur cursor is pointing to. The pointer is to the beginning of
52132 ** the key if skipKey==0 and it points to the beginning of data if
52133 ** skipKey==1. The number of bytes of available key/data is written
52134 ** into *pAmt. If *pAmt==0, then the value returned will not be
52135 ** a valid pointer.
52137 ** This routine is an optimization. It is common for the entire key
52138 ** and data to fit on the local page and for there to be no overflow
52139 ** pages. When that is so, this routine can be used to access the
52140 ** key and data without making a copy. If the key and/or data spills
52141 ** onto overflow pages, then accessPayload() must be used to reassemble
52142 ** the key/data and copy it into a preallocated buffer.
52144 ** The pointer returned by this routine looks directly into the cached
52145 ** page of the database. The data might change or move the next time
52146 ** any btree routine is called.
52148 static const unsigned char *fetchPayload(
52149 BtCursor *pCur, /* Cursor pointing to entry to read from */
52150 int *pAmt, /* Write the number of available bytes here */
52151 int skipKey /* read beginning at data if this is true */
52153 unsigned char *aPayload;
52154 MemPage *pPage;
52155 u32 nKey;
52156 u32 nLocal;
52158 assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
52159 assert( pCur->eState==CURSOR_VALID );
52160 assert( cursorHoldsMutex(pCur) );
52161 pPage = pCur->apPage[pCur->iPage];
52162 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
52163 if( NEVER(pCur->info.nSize==0) ){
52164 btreeParseCell(pCur->apPage[pCur->iPage], pCur->aiIdx[pCur->iPage],
52165 &pCur->info);
52167 aPayload = pCur->info.pCell;
52168 aPayload += pCur->info.nHeader;
52169 if( pPage->intKey ){
52170 nKey = 0;
52171 }else{
52172 nKey = (int)pCur->info.nKey;
52174 if( skipKey ){
52175 aPayload += nKey;
52176 nLocal = pCur->info.nLocal - nKey;
52177 }else{
52178 nLocal = pCur->info.nLocal;
52179 assert( nLocal<=nKey );
52181 *pAmt = nLocal;
52182 return aPayload;
52187 ** For the entry that cursor pCur is point to, return as
52188 ** many bytes of the key or data as are available on the local
52189 ** b-tree page. Write the number of available bytes into *pAmt.
52191 ** The pointer returned is ephemeral. The key/data may move
52192 ** or be destroyed on the next call to any Btree routine,
52193 ** including calls from other threads against the same cache.
52194 ** Hence, a mutex on the BtShared should be held prior to calling
52195 ** this routine.
52197 ** These routines is used to get quick access to key and data
52198 ** in the common case where no overflow pages are used.
52200 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
52201 const void *p = 0;
52202 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
52203 assert( cursorHoldsMutex(pCur) );
52204 if( ALWAYS(pCur->eState==CURSOR_VALID) ){
52205 p = (const void*)fetchPayload(pCur, pAmt, 0);
52207 return p;
52209 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
52210 const void *p = 0;
52211 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
52212 assert( cursorHoldsMutex(pCur) );
52213 if( ALWAYS(pCur->eState==CURSOR_VALID) ){
52214 p = (const void*)fetchPayload(pCur, pAmt, 1);
52216 return p;
52221 ** Move the cursor down to a new child page. The newPgno argument is the
52222 ** page number of the child page to move to.
52224 ** This function returns SQLITE_CORRUPT if the page-header flags field of
52225 ** the new child page does not match the flags field of the parent (i.e.
52226 ** if an intkey page appears to be the parent of a non-intkey page, or
52227 ** vice-versa).
52229 static int moveToChild(BtCursor *pCur, u32 newPgno){
52230 int rc;
52231 int i = pCur->iPage;
52232 MemPage *pNewPage;
52233 BtShared *pBt = pCur->pBt;
52235 assert( cursorHoldsMutex(pCur) );
52236 assert( pCur->eState==CURSOR_VALID );
52237 assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
52238 if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
52239 return SQLITE_CORRUPT_BKPT;
52241 rc = getAndInitPage(pBt, newPgno, &pNewPage);
52242 if( rc ) return rc;
52243 pCur->apPage[i+1] = pNewPage;
52244 pCur->aiIdx[i+1] = 0;
52245 pCur->iPage++;
52247 pCur->info.nSize = 0;
52248 pCur->validNKey = 0;
52249 if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
52250 return SQLITE_CORRUPT_BKPT;
52252 return SQLITE_OK;
52255 #ifndef NDEBUG
52257 ** Page pParent is an internal (non-leaf) tree page. This function
52258 ** asserts that page number iChild is the left-child if the iIdx'th
52259 ** cell in page pParent. Or, if iIdx is equal to the total number of
52260 ** cells in pParent, that page number iChild is the right-child of
52261 ** the page.
52263 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
52264 assert( iIdx<=pParent->nCell );
52265 if( iIdx==pParent->nCell ){
52266 assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
52267 }else{
52268 assert( get4byte(findCell(pParent, iIdx))==iChild );
52271 #else
52272 # define assertParentIndex(x,y,z)
52273 #endif
52276 ** Move the cursor up to the parent page.
52278 ** pCur->idx is set to the cell index that contains the pointer
52279 ** to the page we are coming from. If we are coming from the
52280 ** right-most child page then pCur->idx is set to one more than
52281 ** the largest cell index.
52283 static void moveToParent(BtCursor *pCur){
52284 assert( cursorHoldsMutex(pCur) );
52285 assert( pCur->eState==CURSOR_VALID );
52286 assert( pCur->iPage>0 );
52287 assert( pCur->apPage[pCur->iPage] );
52288 assertParentIndex(
52289 pCur->apPage[pCur->iPage-1],
52290 pCur->aiIdx[pCur->iPage-1],
52291 pCur->apPage[pCur->iPage]->pgno
52293 releasePage(pCur->apPage[pCur->iPage]);
52294 pCur->iPage--;
52295 pCur->info.nSize = 0;
52296 pCur->validNKey = 0;
52300 ** Move the cursor to point to the root page of its b-tree structure.
52302 ** If the table has a virtual root page, then the cursor is moved to point
52303 ** to the virtual root page instead of the actual root page. A table has a
52304 ** virtual root page when the actual root page contains no cells and a
52305 ** single child page. This can only happen with the table rooted at page 1.
52307 ** If the b-tree structure is empty, the cursor state is set to
52308 ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
52309 ** cell located on the root (or virtual root) page and the cursor state
52310 ** is set to CURSOR_VALID.
52312 ** If this function returns successfully, it may be assumed that the
52313 ** page-header flags indicate that the [virtual] root-page is the expected
52314 ** kind of b-tree page (i.e. if when opening the cursor the caller did not
52315 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
52316 ** indicating a table b-tree, or if the caller did specify a KeyInfo
52317 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
52318 ** b-tree).
52320 static int moveToRoot(BtCursor *pCur){
52321 MemPage *pRoot;
52322 int rc = SQLITE_OK;
52323 Btree *p = pCur->pBtree;
52324 BtShared *pBt = p->pBt;
52326 assert( cursorHoldsMutex(pCur) );
52327 assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
52328 assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
52329 assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
52330 if( pCur->eState>=CURSOR_REQUIRESEEK ){
52331 if( pCur->eState==CURSOR_FAULT ){
52332 assert( pCur->skipNext!=SQLITE_OK );
52333 return pCur->skipNext;
52335 sqlite3BtreeClearCursor(pCur);
52338 if( pCur->iPage>=0 ){
52339 int i;
52340 for(i=1; i<=pCur->iPage; i++){
52341 releasePage(pCur->apPage[i]);
52343 pCur->iPage = 0;
52344 }else if( pCur->pgnoRoot==0 ){
52345 pCur->eState = CURSOR_INVALID;
52346 return SQLITE_OK;
52347 }else{
52348 rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]);
52349 if( rc!=SQLITE_OK ){
52350 pCur->eState = CURSOR_INVALID;
52351 return rc;
52353 pCur->iPage = 0;
52355 /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
52356 ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
52357 ** NULL, the caller expects a table b-tree. If this is not the case,
52358 ** return an SQLITE_CORRUPT error. */
52359 assert( pCur->apPage[0]->intKey==1 || pCur->apPage[0]->intKey==0 );
52360 if( (pCur->pKeyInfo==0)!=pCur->apPage[0]->intKey ){
52361 return SQLITE_CORRUPT_BKPT;
52365 /* Assert that the root page is of the correct type. This must be the
52366 ** case as the call to this function that loaded the root-page (either
52367 ** this call or a previous invocation) would have detected corruption
52368 ** if the assumption were not true, and it is not possible for the flags
52369 ** byte to have been modified while this cursor is holding a reference
52370 ** to the page. */
52371 pRoot = pCur->apPage[0];
52372 assert( pRoot->pgno==pCur->pgnoRoot );
52373 assert( pRoot->isInit && (pCur->pKeyInfo==0)==pRoot->intKey );
52375 pCur->aiIdx[0] = 0;
52376 pCur->info.nSize = 0;
52377 pCur->atLast = 0;
52378 pCur->validNKey = 0;
52380 if( pRoot->nCell==0 && !pRoot->leaf ){
52381 Pgno subpage;
52382 if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
52383 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
52384 pCur->eState = CURSOR_VALID;
52385 rc = moveToChild(pCur, subpage);
52386 }else{
52387 pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
52389 return rc;
52393 ** Move the cursor down to the left-most leaf entry beneath the
52394 ** entry to which it is currently pointing.
52396 ** The left-most leaf is the one with the smallest key - the first
52397 ** in ascending order.
52399 static int moveToLeftmost(BtCursor *pCur){
52400 Pgno pgno;
52401 int rc = SQLITE_OK;
52402 MemPage *pPage;
52404 assert( cursorHoldsMutex(pCur) );
52405 assert( pCur->eState==CURSOR_VALID );
52406 while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
52407 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
52408 pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
52409 rc = moveToChild(pCur, pgno);
52411 return rc;
52415 ** Move the cursor down to the right-most leaf entry beneath the
52416 ** page to which it is currently pointing. Notice the difference
52417 ** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
52418 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
52419 ** finds the right-most entry beneath the *page*.
52421 ** The right-most entry is the one with the largest key - the last
52422 ** key in ascending order.
52424 static int moveToRightmost(BtCursor *pCur){
52425 Pgno pgno;
52426 int rc = SQLITE_OK;
52427 MemPage *pPage = 0;
52429 assert( cursorHoldsMutex(pCur) );
52430 assert( pCur->eState==CURSOR_VALID );
52431 while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
52432 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
52433 pCur->aiIdx[pCur->iPage] = pPage->nCell;
52434 rc = moveToChild(pCur, pgno);
52436 if( rc==SQLITE_OK ){
52437 pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
52438 pCur->info.nSize = 0;
52439 pCur->validNKey = 0;
52441 return rc;
52444 /* Move the cursor to the first entry in the table. Return SQLITE_OK
52445 ** on success. Set *pRes to 0 if the cursor actually points to something
52446 ** or set *pRes to 1 if the table is empty.
52448 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
52449 int rc;
52451 assert( cursorHoldsMutex(pCur) );
52452 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
52453 rc = moveToRoot(pCur);
52454 if( rc==SQLITE_OK ){
52455 if( pCur->eState==CURSOR_INVALID ){
52456 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
52457 *pRes = 1;
52458 }else{
52459 assert( pCur->apPage[pCur->iPage]->nCell>0 );
52460 *pRes = 0;
52461 rc = moveToLeftmost(pCur);
52464 return rc;
52467 /* Move the cursor to the last entry in the table. Return SQLITE_OK
52468 ** on success. Set *pRes to 0 if the cursor actually points to something
52469 ** or set *pRes to 1 if the table is empty.
52471 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
52472 int rc;
52474 assert( cursorHoldsMutex(pCur) );
52475 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
52477 /* If the cursor already points to the last entry, this is a no-op. */
52478 if( CURSOR_VALID==pCur->eState && pCur->atLast ){
52479 #ifdef SQLITE_DEBUG
52480 /* This block serves to assert() that the cursor really does point
52481 ** to the last entry in the b-tree. */
52482 int ii;
52483 for(ii=0; ii<pCur->iPage; ii++){
52484 assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
52486 assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
52487 assert( pCur->apPage[pCur->iPage]->leaf );
52488 #endif
52489 return SQLITE_OK;
52492 rc = moveToRoot(pCur);
52493 if( rc==SQLITE_OK ){
52494 if( CURSOR_INVALID==pCur->eState ){
52495 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
52496 *pRes = 1;
52497 }else{
52498 assert( pCur->eState==CURSOR_VALID );
52499 *pRes = 0;
52500 rc = moveToRightmost(pCur);
52501 pCur->atLast = rc==SQLITE_OK ?1:0;
52504 return rc;
52507 /* Move the cursor so that it points to an entry near the key
52508 ** specified by pIdxKey or intKey. Return a success code.
52510 ** For INTKEY tables, the intKey parameter is used. pIdxKey
52511 ** must be NULL. For index tables, pIdxKey is used and intKey
52512 ** is ignored.
52514 ** If an exact match is not found, then the cursor is always
52515 ** left pointing at a leaf page which would hold the entry if it
52516 ** were present. The cursor might point to an entry that comes
52517 ** before or after the key.
52519 ** An integer is written into *pRes which is the result of
52520 ** comparing the key with the entry to which the cursor is
52521 ** pointing. The meaning of the integer written into
52522 ** *pRes is as follows:
52524 ** *pRes<0 The cursor is left pointing at an entry that
52525 ** is smaller than intKey/pIdxKey or if the table is empty
52526 ** and the cursor is therefore left point to nothing.
52528 ** *pRes==0 The cursor is left pointing at an entry that
52529 ** exactly matches intKey/pIdxKey.
52531 ** *pRes>0 The cursor is left pointing at an entry that
52532 ** is larger than intKey/pIdxKey.
52535 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
52536 BtCursor *pCur, /* The cursor to be moved */
52537 UnpackedRecord *pIdxKey, /* Unpacked index key */
52538 i64 intKey, /* The table key */
52539 int biasRight, /* If true, bias the search to the high end */
52540 int *pRes /* Write search results here */
52542 int rc;
52544 assert( cursorHoldsMutex(pCur) );
52545 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
52546 assert( pRes );
52547 assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
52549 /* If the cursor is already positioned at the point we are trying
52550 ** to move to, then just return without doing any work */
52551 if( pCur->eState==CURSOR_VALID && pCur->validNKey
52552 && pCur->apPage[0]->intKey
52554 if( pCur->info.nKey==intKey ){
52555 *pRes = 0;
52556 return SQLITE_OK;
52558 if( pCur->atLast && pCur->info.nKey<intKey ){
52559 *pRes = -1;
52560 return SQLITE_OK;
52564 rc = moveToRoot(pCur);
52565 if( rc ){
52566 return rc;
52568 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
52569 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
52570 assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
52571 if( pCur->eState==CURSOR_INVALID ){
52572 *pRes = -1;
52573 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
52574 return SQLITE_OK;
52576 assert( pCur->apPage[0]->intKey || pIdxKey );
52577 for(;;){
52578 int lwr, upr, idx;
52579 Pgno chldPg;
52580 MemPage *pPage = pCur->apPage[pCur->iPage];
52581 int c;
52583 /* pPage->nCell must be greater than zero. If this is the root-page
52584 ** the cursor would have been INVALID above and this for(;;) loop
52585 ** not run. If this is not the root-page, then the moveToChild() routine
52586 ** would have already detected db corruption. Similarly, pPage must
52587 ** be the right kind (index or table) of b-tree page. Otherwise
52588 ** a moveToChild() or moveToRoot() call would have detected corruption. */
52589 assert( pPage->nCell>0 );
52590 assert( pPage->intKey==(pIdxKey==0) );
52591 lwr = 0;
52592 upr = pPage->nCell-1;
52593 if( biasRight ){
52594 pCur->aiIdx[pCur->iPage] = (u16)(idx = upr);
52595 }else{
52596 pCur->aiIdx[pCur->iPage] = (u16)(idx = (upr+lwr)/2);
52598 for(;;){
52599 u8 *pCell; /* Pointer to current cell in pPage */
52601 assert( idx==pCur->aiIdx[pCur->iPage] );
52602 pCur->info.nSize = 0;
52603 pCell = findCell(pPage, idx) + pPage->childPtrSize;
52604 if( pPage->intKey ){
52605 i64 nCellKey;
52606 if( pPage->hasData ){
52607 u32 dummy;
52608 pCell += getVarint32(pCell, dummy);
52610 getVarint(pCell, (u64*)&nCellKey);
52611 if( nCellKey==intKey ){
52612 c = 0;
52613 }else if( nCellKey<intKey ){
52614 c = -1;
52615 }else{
52616 assert( nCellKey>intKey );
52617 c = +1;
52619 pCur->validNKey = 1;
52620 pCur->info.nKey = nCellKey;
52621 }else{
52622 /* The maximum supported page-size is 65536 bytes. This means that
52623 ** the maximum number of record bytes stored on an index B-Tree
52624 ** page is less than 16384 bytes and may be stored as a 2-byte
52625 ** varint. This information is used to attempt to avoid parsing
52626 ** the entire cell by checking for the cases where the record is
52627 ** stored entirely within the b-tree page by inspecting the first
52628 ** 2 bytes of the cell.
52630 int nCell = pCell[0];
52631 if( !(nCell & 0x80) && nCell<=pPage->maxLocal ){
52632 /* This branch runs if the record-size field of the cell is a
52633 ** single byte varint and the record fits entirely on the main
52634 ** b-tree page. */
52635 c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
52636 }else if( !(pCell[1] & 0x80)
52637 && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
52639 /* The record-size field is a 2 byte varint and the record
52640 ** fits entirely on the main b-tree page. */
52641 c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
52642 }else{
52643 /* The record flows over onto one or more overflow pages. In
52644 ** this case the whole cell needs to be parsed, a buffer allocated
52645 ** and accessPayload() used to retrieve the record into the
52646 ** buffer before VdbeRecordCompare() can be called. */
52647 void *pCellKey;
52648 u8 * const pCellBody = pCell - pPage->childPtrSize;
52649 btreeParseCellPtr(pPage, pCellBody, &pCur->info);
52650 nCell = (int)pCur->info.nKey;
52651 pCellKey = sqlite3Malloc( nCell );
52652 if( pCellKey==0 ){
52653 rc = SQLITE_NOMEM;
52654 goto moveto_finish;
52656 rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
52657 if( rc ){
52658 sqlite3_free(pCellKey);
52659 goto moveto_finish;
52661 c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
52662 sqlite3_free(pCellKey);
52665 if( c==0 ){
52666 if( pPage->intKey && !pPage->leaf ){
52667 lwr = idx;
52668 break;
52669 }else{
52670 *pRes = 0;
52671 rc = SQLITE_OK;
52672 goto moveto_finish;
52675 if( c<0 ){
52676 lwr = idx+1;
52677 }else{
52678 upr = idx-1;
52680 if( lwr>upr ){
52681 break;
52683 pCur->aiIdx[pCur->iPage] = (u16)(idx = (lwr+upr)/2);
52685 assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
52686 assert( pPage->isInit );
52687 if( pPage->leaf ){
52688 chldPg = 0;
52689 }else if( lwr>=pPage->nCell ){
52690 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
52691 }else{
52692 chldPg = get4byte(findCell(pPage, lwr));
52694 if( chldPg==0 ){
52695 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
52696 *pRes = c;
52697 rc = SQLITE_OK;
52698 goto moveto_finish;
52700 pCur->aiIdx[pCur->iPage] = (u16)lwr;
52701 pCur->info.nSize = 0;
52702 pCur->validNKey = 0;
52703 rc = moveToChild(pCur, chldPg);
52704 if( rc ) goto moveto_finish;
52706 moveto_finish:
52707 return rc;
52712 ** Return TRUE if the cursor is not pointing at an entry of the table.
52714 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
52715 ** past the last entry in the table or sqlite3BtreePrev() moves past
52716 ** the first entry. TRUE is also returned if the table is empty.
52718 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
52719 /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
52720 ** have been deleted? This API will need to change to return an error code
52721 ** as well as the boolean result value.
52723 return (CURSOR_VALID!=pCur->eState);
52727 ** Advance the cursor to the next entry in the database. If
52728 ** successful then set *pRes=0. If the cursor
52729 ** was already pointing to the last entry in the database before
52730 ** this routine was called, then set *pRes=1.
52732 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
52733 int rc;
52734 int idx;
52735 MemPage *pPage;
52737 assert( cursorHoldsMutex(pCur) );
52738 rc = restoreCursorPosition(pCur);
52739 if( rc!=SQLITE_OK ){
52740 return rc;
52742 assert( pRes!=0 );
52743 if( CURSOR_INVALID==pCur->eState ){
52744 *pRes = 1;
52745 return SQLITE_OK;
52747 if( pCur->skipNext>0 ){
52748 pCur->skipNext = 0;
52749 *pRes = 0;
52750 return SQLITE_OK;
52752 pCur->skipNext = 0;
52754 pPage = pCur->apPage[pCur->iPage];
52755 idx = ++pCur->aiIdx[pCur->iPage];
52756 assert( pPage->isInit );
52757 assert( idx<=pPage->nCell );
52759 pCur->info.nSize = 0;
52760 pCur->validNKey = 0;
52761 if( idx>=pPage->nCell ){
52762 if( !pPage->leaf ){
52763 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
52764 if( rc ) return rc;
52765 rc = moveToLeftmost(pCur);
52766 *pRes = 0;
52767 return rc;
52770 if( pCur->iPage==0 ){
52771 *pRes = 1;
52772 pCur->eState = CURSOR_INVALID;
52773 return SQLITE_OK;
52775 moveToParent(pCur);
52776 pPage = pCur->apPage[pCur->iPage];
52777 }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
52778 *pRes = 0;
52779 if( pPage->intKey ){
52780 rc = sqlite3BtreeNext(pCur, pRes);
52781 }else{
52782 rc = SQLITE_OK;
52784 return rc;
52786 *pRes = 0;
52787 if( pPage->leaf ){
52788 return SQLITE_OK;
52790 rc = moveToLeftmost(pCur);
52791 return rc;
52796 ** Step the cursor to the back to the previous entry in the database. If
52797 ** successful then set *pRes=0. If the cursor
52798 ** was already pointing to the first entry in the database before
52799 ** this routine was called, then set *pRes=1.
52801 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
52802 int rc;
52803 MemPage *pPage;
52805 assert( cursorHoldsMutex(pCur) );
52806 rc = restoreCursorPosition(pCur);
52807 if( rc!=SQLITE_OK ){
52808 return rc;
52810 pCur->atLast = 0;
52811 if( CURSOR_INVALID==pCur->eState ){
52812 *pRes = 1;
52813 return SQLITE_OK;
52815 if( pCur->skipNext<0 ){
52816 pCur->skipNext = 0;
52817 *pRes = 0;
52818 return SQLITE_OK;
52820 pCur->skipNext = 0;
52822 pPage = pCur->apPage[pCur->iPage];
52823 assert( pPage->isInit );
52824 if( !pPage->leaf ){
52825 int idx = pCur->aiIdx[pCur->iPage];
52826 rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
52827 if( rc ){
52828 return rc;
52830 rc = moveToRightmost(pCur);
52831 }else{
52832 while( pCur->aiIdx[pCur->iPage]==0 ){
52833 if( pCur->iPage==0 ){
52834 pCur->eState = CURSOR_INVALID;
52835 *pRes = 1;
52836 return SQLITE_OK;
52838 moveToParent(pCur);
52840 pCur->info.nSize = 0;
52841 pCur->validNKey = 0;
52843 pCur->aiIdx[pCur->iPage]--;
52844 pPage = pCur->apPage[pCur->iPage];
52845 if( pPage->intKey && !pPage->leaf ){
52846 rc = sqlite3BtreePrevious(pCur, pRes);
52847 }else{
52848 rc = SQLITE_OK;
52851 *pRes = 0;
52852 return rc;
52856 ** Allocate a new page from the database file.
52858 ** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
52859 ** has already been called on the new page.) The new page has also
52860 ** been referenced and the calling routine is responsible for calling
52861 ** sqlite3PagerUnref() on the new page when it is done.
52863 ** SQLITE_OK is returned on success. Any other return value indicates
52864 ** an error. *ppPage and *pPgno are undefined in the event of an error.
52865 ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
52867 ** If the "nearby" parameter is not 0, then a (feeble) effort is made to
52868 ** locate a page close to the page number "nearby". This can be used in an
52869 ** attempt to keep related pages close to each other in the database file,
52870 ** which in turn can make database access faster.
52872 ** If the "exact" parameter is not 0, and the page-number nearby exists
52873 ** anywhere on the free-list, then it is guarenteed to be returned. This
52874 ** is only used by auto-vacuum databases when allocating a new table.
52876 static int allocateBtreePage(
52877 BtShared *pBt,
52878 MemPage **ppPage,
52879 Pgno *pPgno,
52880 Pgno nearby,
52881 u8 exact
52883 MemPage *pPage1;
52884 int rc;
52885 u32 n; /* Number of pages on the freelist */
52886 u32 k; /* Number of leaves on the trunk of the freelist */
52887 MemPage *pTrunk = 0;
52888 MemPage *pPrevTrunk = 0;
52889 Pgno mxPage; /* Total size of the database file */
52891 assert( sqlite3_mutex_held(pBt->mutex) );
52892 pPage1 = pBt->pPage1;
52893 mxPage = btreePagecount(pBt);
52894 n = get4byte(&pPage1->aData[36]);
52895 testcase( n==mxPage-1 );
52896 if( n>=mxPage ){
52897 return SQLITE_CORRUPT_BKPT;
52899 if( n>0 ){
52900 /* There are pages on the freelist. Reuse one of those pages. */
52901 Pgno iTrunk;
52902 u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
52904 /* If the 'exact' parameter was true and a query of the pointer-map
52905 ** shows that the page 'nearby' is somewhere on the free-list, then
52906 ** the entire-list will be searched for that page.
52908 #ifndef SQLITE_OMIT_AUTOVACUUM
52909 if( exact && nearby<=mxPage ){
52910 u8 eType;
52911 assert( nearby>0 );
52912 assert( pBt->autoVacuum );
52913 rc = ptrmapGet(pBt, nearby, &eType, 0);
52914 if( rc ) return rc;
52915 if( eType==PTRMAP_FREEPAGE ){
52916 searchList = 1;
52918 *pPgno = nearby;
52920 #endif
52922 /* Decrement the free-list count by 1. Set iTrunk to the index of the
52923 ** first free-list trunk page. iPrevTrunk is initially 1.
52925 rc = sqlite3PagerWrite(pPage1->pDbPage);
52926 if( rc ) return rc;
52927 put4byte(&pPage1->aData[36], n-1);
52929 /* The code within this loop is run only once if the 'searchList' variable
52930 ** is not true. Otherwise, it runs once for each trunk-page on the
52931 ** free-list until the page 'nearby' is located.
52933 do {
52934 pPrevTrunk = pTrunk;
52935 if( pPrevTrunk ){
52936 iTrunk = get4byte(&pPrevTrunk->aData[0]);
52937 }else{
52938 iTrunk = get4byte(&pPage1->aData[32]);
52940 testcase( iTrunk==mxPage );
52941 if( iTrunk>mxPage ){
52942 rc = SQLITE_CORRUPT_BKPT;
52943 }else{
52944 rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
52946 if( rc ){
52947 pTrunk = 0;
52948 goto end_allocate_page;
52950 assert( pTrunk!=0 );
52951 assert( pTrunk->aData!=0 );
52953 k = get4byte(&pTrunk->aData[4]); /* # of leaves on this trunk page */
52954 if( k==0 && !searchList ){
52955 /* The trunk has no leaves and the list is not being searched.
52956 ** So extract the trunk page itself and use it as the newly
52957 ** allocated page */
52958 assert( pPrevTrunk==0 );
52959 rc = sqlite3PagerWrite(pTrunk->pDbPage);
52960 if( rc ){
52961 goto end_allocate_page;
52963 *pPgno = iTrunk;
52964 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
52965 *ppPage = pTrunk;
52966 pTrunk = 0;
52967 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
52968 }else if( k>(u32)(pBt->usableSize/4 - 2) ){
52969 /* Value of k is out of range. Database corruption */
52970 rc = SQLITE_CORRUPT_BKPT;
52971 goto end_allocate_page;
52972 #ifndef SQLITE_OMIT_AUTOVACUUM
52973 }else if( searchList && nearby==iTrunk ){
52974 /* The list is being searched and this trunk page is the page
52975 ** to allocate, regardless of whether it has leaves.
52977 assert( *pPgno==iTrunk );
52978 *ppPage = pTrunk;
52979 searchList = 0;
52980 rc = sqlite3PagerWrite(pTrunk->pDbPage);
52981 if( rc ){
52982 goto end_allocate_page;
52984 if( k==0 ){
52985 if( !pPrevTrunk ){
52986 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
52987 }else{
52988 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
52989 if( rc!=SQLITE_OK ){
52990 goto end_allocate_page;
52992 memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
52994 }else{
52995 /* The trunk page is required by the caller but it contains
52996 ** pointers to free-list leaves. The first leaf becomes a trunk
52997 ** page in this case.
52999 MemPage *pNewTrunk;
53000 Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
53001 if( iNewTrunk>mxPage ){
53002 rc = SQLITE_CORRUPT_BKPT;
53003 goto end_allocate_page;
53005 testcase( iNewTrunk==mxPage );
53006 rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
53007 if( rc!=SQLITE_OK ){
53008 goto end_allocate_page;
53010 rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
53011 if( rc!=SQLITE_OK ){
53012 releasePage(pNewTrunk);
53013 goto end_allocate_page;
53015 memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
53016 put4byte(&pNewTrunk->aData[4], k-1);
53017 memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
53018 releasePage(pNewTrunk);
53019 if( !pPrevTrunk ){
53020 assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
53021 put4byte(&pPage1->aData[32], iNewTrunk);
53022 }else{
53023 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
53024 if( rc ){
53025 goto end_allocate_page;
53027 put4byte(&pPrevTrunk->aData[0], iNewTrunk);
53030 pTrunk = 0;
53031 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
53032 #endif
53033 }else if( k>0 ){
53034 /* Extract a leaf from the trunk */
53035 u32 closest;
53036 Pgno iPage;
53037 unsigned char *aData = pTrunk->aData;
53038 if( nearby>0 ){
53039 u32 i;
53040 int dist;
53041 closest = 0;
53042 dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
53043 for(i=1; i<k; i++){
53044 int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
53045 if( d2<dist ){
53046 closest = i;
53047 dist = d2;
53050 }else{
53051 closest = 0;
53054 iPage = get4byte(&aData[8+closest*4]);
53055 testcase( iPage==mxPage );
53056 if( iPage>mxPage ){
53057 rc = SQLITE_CORRUPT_BKPT;
53058 goto end_allocate_page;
53060 testcase( iPage==mxPage );
53061 if( !searchList || iPage==nearby ){
53062 int noContent;
53063 *pPgno = iPage;
53064 TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
53065 ": %d more free pages\n",
53066 *pPgno, closest+1, k, pTrunk->pgno, n-1));
53067 rc = sqlite3PagerWrite(pTrunk->pDbPage);
53068 if( rc ) goto end_allocate_page;
53069 if( closest<k-1 ){
53070 memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
53072 put4byte(&aData[4], k-1);
53073 noContent = !btreeGetHasContent(pBt, *pPgno);
53074 rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
53075 if( rc==SQLITE_OK ){
53076 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
53077 if( rc!=SQLITE_OK ){
53078 releasePage(*ppPage);
53081 searchList = 0;
53084 releasePage(pPrevTrunk);
53085 pPrevTrunk = 0;
53086 }while( searchList );
53087 }else{
53088 /* There are no pages on the freelist, so create a new page at the
53089 ** end of the file */
53090 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
53091 if( rc ) return rc;
53092 pBt->nPage++;
53093 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
53095 #ifndef SQLITE_OMIT_AUTOVACUUM
53096 if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
53097 /* If *pPgno refers to a pointer-map page, allocate two new pages
53098 ** at the end of the file instead of one. The first allocated page
53099 ** becomes a new pointer-map page, the second is used by the caller.
53101 MemPage *pPg = 0;
53102 TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
53103 assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
53104 rc = btreeGetPage(pBt, pBt->nPage, &pPg, 1);
53105 if( rc==SQLITE_OK ){
53106 rc = sqlite3PagerWrite(pPg->pDbPage);
53107 releasePage(pPg);
53109 if( rc ) return rc;
53110 pBt->nPage++;
53111 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
53113 #endif
53114 put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
53115 *pPgno = pBt->nPage;
53117 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
53118 rc = btreeGetPage(pBt, *pPgno, ppPage, 1);
53119 if( rc ) return rc;
53120 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
53121 if( rc!=SQLITE_OK ){
53122 releasePage(*ppPage);
53124 TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
53127 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
53129 end_allocate_page:
53130 releasePage(pTrunk);
53131 releasePage(pPrevTrunk);
53132 if( rc==SQLITE_OK ){
53133 if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
53134 releasePage(*ppPage);
53135 return SQLITE_CORRUPT_BKPT;
53137 (*ppPage)->isInit = 0;
53138 }else{
53139 *ppPage = 0;
53141 assert( rc!=SQLITE_OK || sqlite3PagerIswriteable((*ppPage)->pDbPage) );
53142 return rc;
53146 ** This function is used to add page iPage to the database file free-list.
53147 ** It is assumed that the page is not already a part of the free-list.
53149 ** The value passed as the second argument to this function is optional.
53150 ** If the caller happens to have a pointer to the MemPage object
53151 ** corresponding to page iPage handy, it may pass it as the second value.
53152 ** Otherwise, it may pass NULL.
53154 ** If a pointer to a MemPage object is passed as the second argument,
53155 ** its reference count is not altered by this function.
53157 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
53158 MemPage *pTrunk = 0; /* Free-list trunk page */
53159 Pgno iTrunk = 0; /* Page number of free-list trunk page */
53160 MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
53161 MemPage *pPage; /* Page being freed. May be NULL. */
53162 int rc; /* Return Code */
53163 int nFree; /* Initial number of pages on free-list */
53165 assert( sqlite3_mutex_held(pBt->mutex) );
53166 assert( iPage>1 );
53167 assert( !pMemPage || pMemPage->pgno==iPage );
53169 if( pMemPage ){
53170 pPage = pMemPage;
53171 sqlite3PagerRef(pPage->pDbPage);
53172 }else{
53173 pPage = btreePageLookup(pBt, iPage);
53176 /* Increment the free page count on pPage1 */
53177 rc = sqlite3PagerWrite(pPage1->pDbPage);
53178 if( rc ) goto freepage_out;
53179 nFree = get4byte(&pPage1->aData[36]);
53180 put4byte(&pPage1->aData[36], nFree+1);
53182 if( pBt->secureDelete ){
53183 /* If the secure_delete option is enabled, then
53184 ** always fully overwrite deleted information with zeros.
53186 if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
53187 || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
53189 goto freepage_out;
53191 memset(pPage->aData, 0, pPage->pBt->pageSize);
53194 /* If the database supports auto-vacuum, write an entry in the pointer-map
53195 ** to indicate that the page is free.
53197 if( ISAUTOVACUUM ){
53198 ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
53199 if( rc ) goto freepage_out;
53202 /* Now manipulate the actual database free-list structure. There are two
53203 ** possibilities. If the free-list is currently empty, or if the first
53204 ** trunk page in the free-list is full, then this page will become a
53205 ** new free-list trunk page. Otherwise, it will become a leaf of the
53206 ** first trunk page in the current free-list. This block tests if it
53207 ** is possible to add the page as a new free-list leaf.
53209 if( nFree!=0 ){
53210 u32 nLeaf; /* Initial number of leaf cells on trunk page */
53212 iTrunk = get4byte(&pPage1->aData[32]);
53213 rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
53214 if( rc!=SQLITE_OK ){
53215 goto freepage_out;
53218 nLeaf = get4byte(&pTrunk->aData[4]);
53219 assert( pBt->usableSize>32 );
53220 if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
53221 rc = SQLITE_CORRUPT_BKPT;
53222 goto freepage_out;
53224 if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
53225 /* In this case there is room on the trunk page to insert the page
53226 ** being freed as a new leaf.
53228 ** Note that the trunk page is not really full until it contains
53229 ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
53230 ** coded. But due to a coding error in versions of SQLite prior to
53231 ** 3.6.0, databases with freelist trunk pages holding more than
53232 ** usableSize/4 - 8 entries will be reported as corrupt. In order
53233 ** to maintain backwards compatibility with older versions of SQLite,
53234 ** we will continue to restrict the number of entries to usableSize/4 - 8
53235 ** for now. At some point in the future (once everyone has upgraded
53236 ** to 3.6.0 or later) we should consider fixing the conditional above
53237 ** to read "usableSize/4-2" instead of "usableSize/4-8".
53239 rc = sqlite3PagerWrite(pTrunk->pDbPage);
53240 if( rc==SQLITE_OK ){
53241 put4byte(&pTrunk->aData[4], nLeaf+1);
53242 put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
53243 if( pPage && !pBt->secureDelete ){
53244 sqlite3PagerDontWrite(pPage->pDbPage);
53246 rc = btreeSetHasContent(pBt, iPage);
53248 TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
53249 goto freepage_out;
53253 /* If control flows to this point, then it was not possible to add the
53254 ** the page being freed as a leaf page of the first trunk in the free-list.
53255 ** Possibly because the free-list is empty, or possibly because the
53256 ** first trunk in the free-list is full. Either way, the page being freed
53257 ** will become the new first trunk page in the free-list.
53259 if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
53260 goto freepage_out;
53262 rc = sqlite3PagerWrite(pPage->pDbPage);
53263 if( rc!=SQLITE_OK ){
53264 goto freepage_out;
53266 put4byte(pPage->aData, iTrunk);
53267 put4byte(&pPage->aData[4], 0);
53268 put4byte(&pPage1->aData[32], iPage);
53269 TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
53271 freepage_out:
53272 if( pPage ){
53273 pPage->isInit = 0;
53275 releasePage(pPage);
53276 releasePage(pTrunk);
53277 return rc;
53279 static void freePage(MemPage *pPage, int *pRC){
53280 if( (*pRC)==SQLITE_OK ){
53281 *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
53286 ** Free any overflow pages associated with the given Cell.
53288 static int clearCell(MemPage *pPage, unsigned char *pCell){
53289 BtShared *pBt = pPage->pBt;
53290 CellInfo info;
53291 Pgno ovflPgno;
53292 int rc;
53293 int nOvfl;
53294 u32 ovflPageSize;
53296 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
53297 btreeParseCellPtr(pPage, pCell, &info);
53298 if( info.iOverflow==0 ){
53299 return SQLITE_OK; /* No overflow pages. Return without doing anything */
53301 if( pCell+info.iOverflow+3 > pPage->aData+pPage->maskPage ){
53302 return SQLITE_CORRUPT; /* Cell extends past end of page */
53304 ovflPgno = get4byte(&pCell[info.iOverflow]);
53305 assert( pBt->usableSize > 4 );
53306 ovflPageSize = pBt->usableSize - 4;
53307 nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
53308 assert( ovflPgno==0 || nOvfl>0 );
53309 while( nOvfl-- ){
53310 Pgno iNext = 0;
53311 MemPage *pOvfl = 0;
53312 if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
53313 /* 0 is not a legal page number and page 1 cannot be an
53314 ** overflow page. Therefore if ovflPgno<2 or past the end of the
53315 ** file the database must be corrupt. */
53316 return SQLITE_CORRUPT_BKPT;
53318 if( nOvfl ){
53319 rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
53320 if( rc ) return rc;
53323 if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
53324 && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
53326 /* There is no reason any cursor should have an outstanding reference
53327 ** to an overflow page belonging to a cell that is being deleted/updated.
53328 ** So if there exists more than one reference to this page, then it
53329 ** must not really be an overflow page and the database must be corrupt.
53330 ** It is helpful to detect this before calling freePage2(), as
53331 ** freePage2() may zero the page contents if secure-delete mode is
53332 ** enabled. If this 'overflow' page happens to be a page that the
53333 ** caller is iterating through or using in some other way, this
53334 ** can be problematic.
53336 rc = SQLITE_CORRUPT_BKPT;
53337 }else{
53338 rc = freePage2(pBt, pOvfl, ovflPgno);
53341 if( pOvfl ){
53342 sqlite3PagerUnref(pOvfl->pDbPage);
53344 if( rc ) return rc;
53345 ovflPgno = iNext;
53347 return SQLITE_OK;
53351 ** Create the byte sequence used to represent a cell on page pPage
53352 ** and write that byte sequence into pCell[]. Overflow pages are
53353 ** allocated and filled in as necessary. The calling procedure
53354 ** is responsible for making sure sufficient space has been allocated
53355 ** for pCell[].
53357 ** Note that pCell does not necessary need to point to the pPage->aData
53358 ** area. pCell might point to some temporary storage. The cell will
53359 ** be constructed in this temporary area then copied into pPage->aData
53360 ** later.
53362 static int fillInCell(
53363 MemPage *pPage, /* The page that contains the cell */
53364 unsigned char *pCell, /* Complete text of the cell */
53365 const void *pKey, i64 nKey, /* The key */
53366 const void *pData,int nData, /* The data */
53367 int nZero, /* Extra zero bytes to append to pData */
53368 int *pnSize /* Write cell size here */
53370 int nPayload;
53371 const u8 *pSrc;
53372 int nSrc, n, rc;
53373 int spaceLeft;
53374 MemPage *pOvfl = 0;
53375 MemPage *pToRelease = 0;
53376 unsigned char *pPrior;
53377 unsigned char *pPayload;
53378 BtShared *pBt = pPage->pBt;
53379 Pgno pgnoOvfl = 0;
53380 int nHeader;
53381 CellInfo info;
53383 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
53385 /* pPage is not necessarily writeable since pCell might be auxiliary
53386 ** buffer space that is separate from the pPage buffer area */
53387 assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
53388 || sqlite3PagerIswriteable(pPage->pDbPage) );
53390 /* Fill in the header. */
53391 nHeader = 0;
53392 if( !pPage->leaf ){
53393 nHeader += 4;
53395 if( pPage->hasData ){
53396 nHeader += putVarint(&pCell[nHeader], nData+nZero);
53397 }else{
53398 nData = nZero = 0;
53400 nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
53401 btreeParseCellPtr(pPage, pCell, &info);
53402 assert( info.nHeader==nHeader );
53403 assert( info.nKey==nKey );
53404 assert( info.nData==(u32)(nData+nZero) );
53406 /* Fill in the payload */
53407 nPayload = nData + nZero;
53408 if( pPage->intKey ){
53409 pSrc = pData;
53410 nSrc = nData;
53411 nData = 0;
53412 }else{
53413 if( NEVER(nKey>0x7fffffff || pKey==0) ){
53414 return SQLITE_CORRUPT_BKPT;
53416 nPayload += (int)nKey;
53417 pSrc = pKey;
53418 nSrc = (int)nKey;
53420 *pnSize = info.nSize;
53421 spaceLeft = info.nLocal;
53422 pPayload = &pCell[nHeader];
53423 pPrior = &pCell[info.iOverflow];
53425 while( nPayload>0 ){
53426 if( spaceLeft==0 ){
53427 #ifndef SQLITE_OMIT_AUTOVACUUM
53428 Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
53429 if( pBt->autoVacuum ){
53431 pgnoOvfl++;
53432 } while(
53433 PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
53436 #endif
53437 rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
53438 #ifndef SQLITE_OMIT_AUTOVACUUM
53439 /* If the database supports auto-vacuum, and the second or subsequent
53440 ** overflow page is being allocated, add an entry to the pointer-map
53441 ** for that page now.
53443 ** If this is the first overflow page, then write a partial entry
53444 ** to the pointer-map. If we write nothing to this pointer-map slot,
53445 ** then the optimistic overflow chain processing in clearCell()
53446 ** may misinterpret the uninitialised values and delete the
53447 ** wrong pages from the database.
53449 if( pBt->autoVacuum && rc==SQLITE_OK ){
53450 u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
53451 ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
53452 if( rc ){
53453 releasePage(pOvfl);
53456 #endif
53457 if( rc ){
53458 releasePage(pToRelease);
53459 return rc;
53462 /* If pToRelease is not zero than pPrior points into the data area
53463 ** of pToRelease. Make sure pToRelease is still writeable. */
53464 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
53466 /* If pPrior is part of the data area of pPage, then make sure pPage
53467 ** is still writeable */
53468 assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
53469 || sqlite3PagerIswriteable(pPage->pDbPage) );
53471 put4byte(pPrior, pgnoOvfl);
53472 releasePage(pToRelease);
53473 pToRelease = pOvfl;
53474 pPrior = pOvfl->aData;
53475 put4byte(pPrior, 0);
53476 pPayload = &pOvfl->aData[4];
53477 spaceLeft = pBt->usableSize - 4;
53479 n = nPayload;
53480 if( n>spaceLeft ) n = spaceLeft;
53482 /* If pToRelease is not zero than pPayload points into the data area
53483 ** of pToRelease. Make sure pToRelease is still writeable. */
53484 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
53486 /* If pPayload is part of the data area of pPage, then make sure pPage
53487 ** is still writeable */
53488 assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
53489 || sqlite3PagerIswriteable(pPage->pDbPage) );
53491 if( nSrc>0 ){
53492 if( n>nSrc ) n = nSrc;
53493 assert( pSrc );
53494 memcpy(pPayload, pSrc, n);
53495 }else{
53496 memset(pPayload, 0, n);
53498 nPayload -= n;
53499 pPayload += n;
53500 pSrc += n;
53501 nSrc -= n;
53502 spaceLeft -= n;
53503 if( nSrc==0 ){
53504 nSrc = nData;
53505 pSrc = pData;
53508 releasePage(pToRelease);
53509 return SQLITE_OK;
53513 ** Remove the i-th cell from pPage. This routine effects pPage only.
53514 ** The cell content is not freed or deallocated. It is assumed that
53515 ** the cell content has been copied someplace else. This routine just
53516 ** removes the reference to the cell from pPage.
53518 ** "sz" must be the number of bytes in the cell.
53520 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
53521 u32 pc; /* Offset to cell content of cell being deleted */
53522 u8 *data; /* pPage->aData */
53523 u8 *ptr; /* Used to move bytes around within data[] */
53524 u8 *endPtr; /* End of loop */
53525 int rc; /* The return code */
53526 int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */
53528 if( *pRC ) return;
53530 assert( idx>=0 && idx<pPage->nCell );
53531 assert( sz==cellSize(pPage, idx) );
53532 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
53533 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
53534 data = pPage->aData;
53535 ptr = &data[pPage->cellOffset + 2*idx];
53536 pc = get2byte(ptr);
53537 hdr = pPage->hdrOffset;
53538 testcase( pc==get2byte(&data[hdr+5]) );
53539 testcase( pc+sz==pPage->pBt->usableSize );
53540 if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
53541 *pRC = SQLITE_CORRUPT_BKPT;
53542 return;
53544 rc = freeSpace(pPage, pc, sz);
53545 if( rc ){
53546 *pRC = rc;
53547 return;
53549 endPtr = &data[pPage->cellOffset + 2*pPage->nCell - 2];
53550 assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 ); /* ptr is always 2-byte aligned */
53551 while( ptr<endPtr ){
53552 *(u16*)ptr = *(u16*)&ptr[2];
53553 ptr += 2;
53555 pPage->nCell--;
53556 put2byte(&data[hdr+3], pPage->nCell);
53557 pPage->nFree += 2;
53561 ** Insert a new cell on pPage at cell index "i". pCell points to the
53562 ** content of the cell.
53564 ** If the cell content will fit on the page, then put it there. If it
53565 ** will not fit, then make a copy of the cell content into pTemp if
53566 ** pTemp is not null. Regardless of pTemp, allocate a new entry
53567 ** in pPage->aOvfl[] and make it point to the cell content (either
53568 ** in pTemp or the original pCell) and also record its index.
53569 ** Allocating a new entry in pPage->aCell[] implies that
53570 ** pPage->nOverflow is incremented.
53572 ** If nSkip is non-zero, then do not copy the first nSkip bytes of the
53573 ** cell. The caller will overwrite them after this function returns. If
53574 ** nSkip is non-zero, then pCell may not point to an invalid memory location
53575 ** (but pCell+nSkip is always valid).
53577 static void insertCell(
53578 MemPage *pPage, /* Page into which we are copying */
53579 int i, /* New cell becomes the i-th cell of the page */
53580 u8 *pCell, /* Content of the new cell */
53581 int sz, /* Bytes of content in pCell */
53582 u8 *pTemp, /* Temp storage space for pCell, if needed */
53583 Pgno iChild, /* If non-zero, replace first 4 bytes with this value */
53584 int *pRC /* Read and write return code from here */
53586 int idx = 0; /* Where to write new cell content in data[] */
53587 int j; /* Loop counter */
53588 int end; /* First byte past the last cell pointer in data[] */
53589 int ins; /* Index in data[] where new cell pointer is inserted */
53590 int cellOffset; /* Address of first cell pointer in data[] */
53591 u8 *data; /* The content of the whole page */
53592 u8 *ptr; /* Used for moving information around in data[] */
53593 u8 *endPtr; /* End of the loop */
53595 int nSkip = (iChild ? 4 : 0);
53597 if( *pRC ) return;
53599 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
53600 assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=10921 );
53601 assert( pPage->nOverflow<=ArraySize(pPage->aOvfl) );
53602 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
53603 /* The cell should normally be sized correctly. However, when moving a
53604 ** malformed cell from a leaf page to an interior page, if the cell size
53605 ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
53606 ** might be less than 8 (leaf-size + pointer) on the interior node. Hence
53607 ** the term after the || in the following assert(). */
53608 assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
53609 if( pPage->nOverflow || sz+2>pPage->nFree ){
53610 if( pTemp ){
53611 memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
53612 pCell = pTemp;
53614 if( iChild ){
53615 put4byte(pCell, iChild);
53617 j = pPage->nOverflow++;
53618 assert( j<(int)(sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0])) );
53619 pPage->aOvfl[j].pCell = pCell;
53620 pPage->aOvfl[j].idx = (u16)i;
53621 }else{
53622 int rc = sqlite3PagerWrite(pPage->pDbPage);
53623 if( rc!=SQLITE_OK ){
53624 *pRC = rc;
53625 return;
53627 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
53628 data = pPage->aData;
53629 cellOffset = pPage->cellOffset;
53630 end = cellOffset + 2*pPage->nCell;
53631 ins = cellOffset + 2*i;
53632 rc = allocateSpace(pPage, sz, &idx);
53633 if( rc ){ *pRC = rc; return; }
53634 /* The allocateSpace() routine guarantees the following two properties
53635 ** if it returns success */
53636 assert( idx >= end+2 );
53637 assert( idx+sz <= (int)pPage->pBt->usableSize );
53638 pPage->nCell++;
53639 pPage->nFree -= (u16)(2 + sz);
53640 memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
53641 if( iChild ){
53642 put4byte(&data[idx], iChild);
53644 ptr = &data[end];
53645 endPtr = &data[ins];
53646 assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 ); /* ptr is always 2-byte aligned */
53647 while( ptr>endPtr ){
53648 *(u16*)ptr = *(u16*)&ptr[-2];
53649 ptr -= 2;
53651 put2byte(&data[ins], idx);
53652 put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
53653 #ifndef SQLITE_OMIT_AUTOVACUUM
53654 if( pPage->pBt->autoVacuum ){
53655 /* The cell may contain a pointer to an overflow page. If so, write
53656 ** the entry for the overflow page into the pointer map.
53658 ptrmapPutOvflPtr(pPage, pCell, pRC);
53660 #endif
53665 ** Add a list of cells to a page. The page should be initially empty.
53666 ** The cells are guaranteed to fit on the page.
53668 static void assemblePage(
53669 MemPage *pPage, /* The page to be assemblied */
53670 int nCell, /* The number of cells to add to this page */
53671 u8 **apCell, /* Pointers to cell bodies */
53672 u16 *aSize /* Sizes of the cells */
53674 int i; /* Loop counter */
53675 u8 *pCellptr; /* Address of next cell pointer */
53676 int cellbody; /* Address of next cell body */
53677 u8 * const data = pPage->aData; /* Pointer to data for pPage */
53678 const int hdr = pPage->hdrOffset; /* Offset of header on pPage */
53679 const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
53681 assert( pPage->nOverflow==0 );
53682 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
53683 assert( nCell>=0 && nCell<=(int)MX_CELL(pPage->pBt)
53684 && (int)MX_CELL(pPage->pBt)<=10921);
53685 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
53687 /* Check that the page has just been zeroed by zeroPage() */
53688 assert( pPage->nCell==0 );
53689 assert( get2byteNotZero(&data[hdr+5])==nUsable );
53691 pCellptr = &data[pPage->cellOffset + nCell*2];
53692 cellbody = nUsable;
53693 for(i=nCell-1; i>=0; i--){
53694 u16 sz = aSize[i];
53695 pCellptr -= 2;
53696 cellbody -= sz;
53697 put2byte(pCellptr, cellbody);
53698 memcpy(&data[cellbody], apCell[i], sz);
53700 put2byte(&data[hdr+3], nCell);
53701 put2byte(&data[hdr+5], cellbody);
53702 pPage->nFree -= (nCell*2 + nUsable - cellbody);
53703 pPage->nCell = (u16)nCell;
53707 ** The following parameters determine how many adjacent pages get involved
53708 ** in a balancing operation. NN is the number of neighbors on either side
53709 ** of the page that participate in the balancing operation. NB is the
53710 ** total number of pages that participate, including the target page and
53711 ** NN neighbors on either side.
53713 ** The minimum value of NN is 1 (of course). Increasing NN above 1
53714 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
53715 ** in exchange for a larger degradation in INSERT and UPDATE performance.
53716 ** The value of NN appears to give the best results overall.
53718 #define NN 1 /* Number of neighbors on either side of pPage */
53719 #define NB (NN*2+1) /* Total pages involved in the balance */
53722 #ifndef SQLITE_OMIT_QUICKBALANCE
53724 ** This version of balance() handles the common special case where
53725 ** a new entry is being inserted on the extreme right-end of the
53726 ** tree, in other words, when the new entry will become the largest
53727 ** entry in the tree.
53729 ** Instead of trying to balance the 3 right-most leaf pages, just add
53730 ** a new page to the right-hand side and put the one new entry in
53731 ** that page. This leaves the right side of the tree somewhat
53732 ** unbalanced. But odds are that we will be inserting new entries
53733 ** at the end soon afterwards so the nearly empty page will quickly
53734 ** fill up. On average.
53736 ** pPage is the leaf page which is the right-most page in the tree.
53737 ** pParent is its parent. pPage must have a single overflow entry
53738 ** which is also the right-most entry on the page.
53740 ** The pSpace buffer is used to store a temporary copy of the divider
53741 ** cell that will be inserted into pParent. Such a cell consists of a 4
53742 ** byte page number followed by a variable length integer. In other
53743 ** words, at most 13 bytes. Hence the pSpace buffer must be at
53744 ** least 13 bytes in size.
53746 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
53747 BtShared *const pBt = pPage->pBt; /* B-Tree Database */
53748 MemPage *pNew; /* Newly allocated page */
53749 int rc; /* Return Code */
53750 Pgno pgnoNew; /* Page number of pNew */
53752 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
53753 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
53754 assert( pPage->nOverflow==1 );
53756 /* This error condition is now caught prior to reaching this function */
53757 if( pPage->nCell<=0 ) return SQLITE_CORRUPT_BKPT;
53759 /* Allocate a new page. This page will become the right-sibling of
53760 ** pPage. Make the parent page writable, so that the new divider cell
53761 ** may be inserted. If both these operations are successful, proceed.
53763 rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
53765 if( rc==SQLITE_OK ){
53767 u8 *pOut = &pSpace[4];
53768 u8 *pCell = pPage->aOvfl[0].pCell;
53769 u16 szCell = cellSizePtr(pPage, pCell);
53770 u8 *pStop;
53772 assert( sqlite3PagerIswriteable(pNew->pDbPage) );
53773 assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
53774 zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
53775 assemblePage(pNew, 1, &pCell, &szCell);
53777 /* If this is an auto-vacuum database, update the pointer map
53778 ** with entries for the new page, and any pointer from the
53779 ** cell on the page to an overflow page. If either of these
53780 ** operations fails, the return code is set, but the contents
53781 ** of the parent page are still manipulated by thh code below.
53782 ** That is Ok, at this point the parent page is guaranteed to
53783 ** be marked as dirty. Returning an error code will cause a
53784 ** rollback, undoing any changes made to the parent page.
53786 if( ISAUTOVACUUM ){
53787 ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
53788 if( szCell>pNew->minLocal ){
53789 ptrmapPutOvflPtr(pNew, pCell, &rc);
53793 /* Create a divider cell to insert into pParent. The divider cell
53794 ** consists of a 4-byte page number (the page number of pPage) and
53795 ** a variable length key value (which must be the same value as the
53796 ** largest key on pPage).
53798 ** To find the largest key value on pPage, first find the right-most
53799 ** cell on pPage. The first two fields of this cell are the
53800 ** record-length (a variable length integer at most 32-bits in size)
53801 ** and the key value (a variable length integer, may have any value).
53802 ** The first of the while(...) loops below skips over the record-length
53803 ** field. The second while(...) loop copies the key value from the
53804 ** cell on pPage into the pSpace buffer.
53806 pCell = findCell(pPage, pPage->nCell-1);
53807 pStop = &pCell[9];
53808 while( (*(pCell++)&0x80) && pCell<pStop );
53809 pStop = &pCell[9];
53810 while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
53812 /* Insert the new divider cell into pParent. */
53813 insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
53814 0, pPage->pgno, &rc);
53816 /* Set the right-child pointer of pParent to point to the new page. */
53817 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
53819 /* Release the reference to the new page. */
53820 releasePage(pNew);
53823 return rc;
53825 #endif /* SQLITE_OMIT_QUICKBALANCE */
53827 #if 0
53829 ** This function does not contribute anything to the operation of SQLite.
53830 ** it is sometimes activated temporarily while debugging code responsible
53831 ** for setting pointer-map entries.
53833 static int ptrmapCheckPages(MemPage **apPage, int nPage){
53834 int i, j;
53835 for(i=0; i<nPage; i++){
53836 Pgno n;
53837 u8 e;
53838 MemPage *pPage = apPage[i];
53839 BtShared *pBt = pPage->pBt;
53840 assert( pPage->isInit );
53842 for(j=0; j<pPage->nCell; j++){
53843 CellInfo info;
53844 u8 *z;
53846 z = findCell(pPage, j);
53847 btreeParseCellPtr(pPage, z, &info);
53848 if( info.iOverflow ){
53849 Pgno ovfl = get4byte(&z[info.iOverflow]);
53850 ptrmapGet(pBt, ovfl, &e, &n);
53851 assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
53853 if( !pPage->leaf ){
53854 Pgno child = get4byte(z);
53855 ptrmapGet(pBt, child, &e, &n);
53856 assert( n==pPage->pgno && e==PTRMAP_BTREE );
53859 if( !pPage->leaf ){
53860 Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
53861 ptrmapGet(pBt, child, &e, &n);
53862 assert( n==pPage->pgno && e==PTRMAP_BTREE );
53865 return 1;
53867 #endif
53870 ** This function is used to copy the contents of the b-tree node stored
53871 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
53872 ** the pointer-map entries for each child page are updated so that the
53873 ** parent page stored in the pointer map is page pTo. If pFrom contained
53874 ** any cells with overflow page pointers, then the corresponding pointer
53875 ** map entries are also updated so that the parent page is page pTo.
53877 ** If pFrom is currently carrying any overflow cells (entries in the
53878 ** MemPage.aOvfl[] array), they are not copied to pTo.
53880 ** Before returning, page pTo is reinitialized using btreeInitPage().
53882 ** The performance of this function is not critical. It is only used by
53883 ** the balance_shallower() and balance_deeper() procedures, neither of
53884 ** which are called often under normal circumstances.
53886 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
53887 if( (*pRC)==SQLITE_OK ){
53888 BtShared * const pBt = pFrom->pBt;
53889 u8 * const aFrom = pFrom->aData;
53890 u8 * const aTo = pTo->aData;
53891 int const iFromHdr = pFrom->hdrOffset;
53892 int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
53893 int rc;
53894 int iData;
53897 assert( pFrom->isInit );
53898 assert( pFrom->nFree>=iToHdr );
53899 assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
53901 /* Copy the b-tree node content from page pFrom to page pTo. */
53902 iData = get2byte(&aFrom[iFromHdr+5]);
53903 memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
53904 memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
53906 /* Reinitialize page pTo so that the contents of the MemPage structure
53907 ** match the new data. The initialization of pTo can actually fail under
53908 ** fairly obscure circumstances, even though it is a copy of initialized
53909 ** page pFrom.
53911 pTo->isInit = 0;
53912 rc = btreeInitPage(pTo);
53913 if( rc!=SQLITE_OK ){
53914 *pRC = rc;
53915 return;
53918 /* If this is an auto-vacuum database, update the pointer-map entries
53919 ** for any b-tree or overflow pages that pTo now contains the pointers to.
53921 if( ISAUTOVACUUM ){
53922 *pRC = setChildPtrmaps(pTo);
53928 ** This routine redistributes cells on the iParentIdx'th child of pParent
53929 ** (hereafter "the page") and up to 2 siblings so that all pages have about the
53930 ** same amount of free space. Usually a single sibling on either side of the
53931 ** page are used in the balancing, though both siblings might come from one
53932 ** side if the page is the first or last child of its parent. If the page
53933 ** has fewer than 2 siblings (something which can only happen if the page
53934 ** is a root page or a child of a root page) then all available siblings
53935 ** participate in the balancing.
53937 ** The number of siblings of the page might be increased or decreased by
53938 ** one or two in an effort to keep pages nearly full but not over full.
53940 ** Note that when this routine is called, some of the cells on the page
53941 ** might not actually be stored in MemPage.aData[]. This can happen
53942 ** if the page is overfull. This routine ensures that all cells allocated
53943 ** to the page and its siblings fit into MemPage.aData[] before returning.
53945 ** In the course of balancing the page and its siblings, cells may be
53946 ** inserted into or removed from the parent page (pParent). Doing so
53947 ** may cause the parent page to become overfull or underfull. If this
53948 ** happens, it is the responsibility of the caller to invoke the correct
53949 ** balancing routine to fix this problem (see the balance() routine).
53951 ** If this routine fails for any reason, it might leave the database
53952 ** in a corrupted state. So if this routine fails, the database should
53953 ** be rolled back.
53955 ** The third argument to this function, aOvflSpace, is a pointer to a
53956 ** buffer big enough to hold one page. If while inserting cells into the parent
53957 ** page (pParent) the parent page becomes overfull, this buffer is
53958 ** used to store the parent's overflow cells. Because this function inserts
53959 ** a maximum of four divider cells into the parent page, and the maximum
53960 ** size of a cell stored within an internal node is always less than 1/4
53961 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
53962 ** enough for all overflow cells.
53964 ** If aOvflSpace is set to a null pointer, this function returns
53965 ** SQLITE_NOMEM.
53967 static int balance_nonroot(
53968 MemPage *pParent, /* Parent page of siblings being balanced */
53969 int iParentIdx, /* Index of "the page" in pParent */
53970 u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
53971 int isRoot /* True if pParent is a root-page */
53973 BtShared *pBt; /* The whole database */
53974 int nCell = 0; /* Number of cells in apCell[] */
53975 int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
53976 int nNew = 0; /* Number of pages in apNew[] */
53977 int nOld; /* Number of pages in apOld[] */
53978 int i, j, k; /* Loop counters */
53979 int nxDiv; /* Next divider slot in pParent->aCell[] */
53980 int rc = SQLITE_OK; /* The return code */
53981 u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
53982 int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
53983 int usableSpace; /* Bytes in pPage beyond the header */
53984 int pageFlags; /* Value of pPage->aData[0] */
53985 int subtotal; /* Subtotal of bytes in cells on one page */
53986 int iSpace1 = 0; /* First unused byte of aSpace1[] */
53987 int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
53988 int szScratch; /* Size of scratch memory requested */
53989 MemPage *apOld[NB]; /* pPage and up to two siblings */
53990 MemPage *apCopy[NB]; /* Private copies of apOld[] pages */
53991 MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
53992 u8 *pRight; /* Location in parent of right-sibling pointer */
53993 u8 *apDiv[NB-1]; /* Divider cells in pParent */
53994 int cntNew[NB+2]; /* Index in aCell[] of cell after i-th page */
53995 int szNew[NB+2]; /* Combined size of cells place on i-th page */
53996 u8 **apCell = 0; /* All cells begin balanced */
53997 u16 *szCell; /* Local size of all cells in apCell[] */
53998 u8 *aSpace1; /* Space for copies of dividers cells */
53999 Pgno pgno; /* Temp var to store a page number in */
54001 pBt = pParent->pBt;
54002 assert( sqlite3_mutex_held(pBt->mutex) );
54003 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
54005 #if 0
54006 TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
54007 #endif
54009 /* At this point pParent may have at most one overflow cell. And if
54010 ** this overflow cell is present, it must be the cell with
54011 ** index iParentIdx. This scenario comes about when this function
54012 ** is called (indirectly) from sqlite3BtreeDelete().
54014 assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
54015 assert( pParent->nOverflow==0 || pParent->aOvfl[0].idx==iParentIdx );
54017 if( !aOvflSpace ){
54018 return SQLITE_NOMEM;
54021 /* Find the sibling pages to balance. Also locate the cells in pParent
54022 ** that divide the siblings. An attempt is made to find NN siblings on
54023 ** either side of pPage. More siblings are taken from one side, however,
54024 ** if there are fewer than NN siblings on the other side. If pParent
54025 ** has NB or fewer children then all children of pParent are taken.
54027 ** This loop also drops the divider cells from the parent page. This
54028 ** way, the remainder of the function does not have to deal with any
54029 ** overflow cells in the parent page, since if any existed they will
54030 ** have already been removed.
54032 i = pParent->nOverflow + pParent->nCell;
54033 if( i<2 ){
54034 nxDiv = 0;
54035 nOld = i+1;
54036 }else{
54037 nOld = 3;
54038 if( iParentIdx==0 ){
54039 nxDiv = 0;
54040 }else if( iParentIdx==i ){
54041 nxDiv = i-2;
54042 }else{
54043 nxDiv = iParentIdx-1;
54045 i = 2;
54047 if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
54048 pRight = &pParent->aData[pParent->hdrOffset+8];
54049 }else{
54050 pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
54052 pgno = get4byte(pRight);
54053 while( 1 ){
54054 rc = getAndInitPage(pBt, pgno, &apOld[i]);
54055 if( rc ){
54056 memset(apOld, 0, (i+1)*sizeof(MemPage*));
54057 goto balance_cleanup;
54059 nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
54060 if( (i--)==0 ) break;
54062 if( i+nxDiv==pParent->aOvfl[0].idx && pParent->nOverflow ){
54063 apDiv[i] = pParent->aOvfl[0].pCell;
54064 pgno = get4byte(apDiv[i]);
54065 szNew[i] = cellSizePtr(pParent, apDiv[i]);
54066 pParent->nOverflow = 0;
54067 }else{
54068 apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
54069 pgno = get4byte(apDiv[i]);
54070 szNew[i] = cellSizePtr(pParent, apDiv[i]);
54072 /* Drop the cell from the parent page. apDiv[i] still points to
54073 ** the cell within the parent, even though it has been dropped.
54074 ** This is safe because dropping a cell only overwrites the first
54075 ** four bytes of it, and this function does not need the first
54076 ** four bytes of the divider cell. So the pointer is safe to use
54077 ** later on.
54079 ** But not if we are in secure-delete mode. In secure-delete mode,
54080 ** the dropCell() routine will overwrite the entire cell with zeroes.
54081 ** In this case, temporarily copy the cell into the aOvflSpace[]
54082 ** buffer. It will be copied out again as soon as the aSpace[] buffer
54083 ** is allocated. */
54084 if( pBt->secureDelete ){
54085 int iOff;
54087 iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
54088 if( (iOff+szNew[i])>(int)pBt->usableSize ){
54089 rc = SQLITE_CORRUPT_BKPT;
54090 memset(apOld, 0, (i+1)*sizeof(MemPage*));
54091 goto balance_cleanup;
54092 }else{
54093 memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
54094 apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
54097 dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
54101 /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
54102 ** alignment */
54103 nMaxCells = (nMaxCells + 3)&~3;
54106 ** Allocate space for memory structures
54108 k = pBt->pageSize + ROUND8(sizeof(MemPage));
54109 szScratch =
54110 nMaxCells*sizeof(u8*) /* apCell */
54111 + nMaxCells*sizeof(u16) /* szCell */
54112 + pBt->pageSize /* aSpace1 */
54113 + k*nOld; /* Page copies (apCopy) */
54114 apCell = sqlite3ScratchMalloc( szScratch );
54115 if( apCell==0 ){
54116 rc = SQLITE_NOMEM;
54117 goto balance_cleanup;
54119 szCell = (u16*)&apCell[nMaxCells];
54120 aSpace1 = (u8*)&szCell[nMaxCells];
54121 assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
54124 ** Load pointers to all cells on sibling pages and the divider cells
54125 ** into the local apCell[] array. Make copies of the divider cells
54126 ** into space obtained from aSpace1[] and remove the the divider Cells
54127 ** from pParent.
54129 ** If the siblings are on leaf pages, then the child pointers of the
54130 ** divider cells are stripped from the cells before they are copied
54131 ** into aSpace1[]. In this way, all cells in apCell[] are without
54132 ** child pointers. If siblings are not leaves, then all cell in
54133 ** apCell[] include child pointers. Either way, all cells in apCell[]
54134 ** are alike.
54136 ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
54137 ** leafData: 1 if pPage holds key+data and pParent holds only keys.
54139 leafCorrection = apOld[0]->leaf*4;
54140 leafData = apOld[0]->hasData;
54141 for(i=0; i<nOld; i++){
54142 int limit;
54144 /* Before doing anything else, take a copy of the i'th original sibling
54145 ** The rest of this function will use data from the copies rather
54146 ** that the original pages since the original pages will be in the
54147 ** process of being overwritten. */
54148 MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
54149 memcpy(pOld, apOld[i], sizeof(MemPage));
54150 pOld->aData = (void*)&pOld[1];
54151 memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
54153 limit = pOld->nCell+pOld->nOverflow;
54154 if( pOld->nOverflow>0 ){
54155 for(j=0; j<limit; j++){
54156 assert( nCell<nMaxCells );
54157 apCell[nCell] = findOverflowCell(pOld, j);
54158 szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
54159 nCell++;
54161 }else{
54162 u8 *aData = pOld->aData;
54163 u16 maskPage = pOld->maskPage;
54164 u16 cellOffset = pOld->cellOffset;
54165 for(j=0; j<limit; j++){
54166 assert( nCell<nMaxCells );
54167 apCell[nCell] = findCellv2(aData, maskPage, cellOffset, j);
54168 szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
54169 nCell++;
54172 if( i<nOld-1 && !leafData){
54173 u16 sz = (u16)szNew[i];
54174 u8 *pTemp;
54175 assert( nCell<nMaxCells );
54176 szCell[nCell] = sz;
54177 pTemp = &aSpace1[iSpace1];
54178 iSpace1 += sz;
54179 assert( sz<=pBt->maxLocal+23 );
54180 assert( iSpace1 <= (int)pBt->pageSize );
54181 memcpy(pTemp, apDiv[i], sz);
54182 apCell[nCell] = pTemp+leafCorrection;
54183 assert( leafCorrection==0 || leafCorrection==4 );
54184 szCell[nCell] = szCell[nCell] - leafCorrection;
54185 if( !pOld->leaf ){
54186 assert( leafCorrection==0 );
54187 assert( pOld->hdrOffset==0 );
54188 /* The right pointer of the child page pOld becomes the left
54189 ** pointer of the divider cell */
54190 memcpy(apCell[nCell], &pOld->aData[8], 4);
54191 }else{
54192 assert( leafCorrection==4 );
54193 if( szCell[nCell]<4 ){
54194 /* Do not allow any cells smaller than 4 bytes. */
54195 szCell[nCell] = 4;
54198 nCell++;
54203 ** Figure out the number of pages needed to hold all nCell cells.
54204 ** Store this number in "k". Also compute szNew[] which is the total
54205 ** size of all cells on the i-th page and cntNew[] which is the index
54206 ** in apCell[] of the cell that divides page i from page i+1.
54207 ** cntNew[k] should equal nCell.
54209 ** Values computed by this block:
54211 ** k: The total number of sibling pages
54212 ** szNew[i]: Spaced used on the i-th sibling page.
54213 ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to
54214 ** the right of the i-th sibling page.
54215 ** usableSpace: Number of bytes of space available on each sibling.
54218 usableSpace = pBt->usableSize - 12 + leafCorrection;
54219 for(subtotal=k=i=0; i<nCell; i++){
54220 assert( i<nMaxCells );
54221 subtotal += szCell[i] + 2;
54222 if( subtotal > usableSpace ){
54223 szNew[k] = subtotal - szCell[i];
54224 cntNew[k] = i;
54225 if( leafData ){ i--; }
54226 subtotal = 0;
54227 k++;
54228 if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
54231 szNew[k] = subtotal;
54232 cntNew[k] = nCell;
54233 k++;
54236 ** The packing computed by the previous block is biased toward the siblings
54237 ** on the left side. The left siblings are always nearly full, while the
54238 ** right-most sibling might be nearly empty. This block of code attempts
54239 ** to adjust the packing of siblings to get a better balance.
54241 ** This adjustment is more than an optimization. The packing above might
54242 ** be so out of balance as to be illegal. For example, the right-most
54243 ** sibling might be completely empty. This adjustment is not optional.
54245 for(i=k-1; i>0; i--){
54246 int szRight = szNew[i]; /* Size of sibling on the right */
54247 int szLeft = szNew[i-1]; /* Size of sibling on the left */
54248 int r; /* Index of right-most cell in left sibling */
54249 int d; /* Index of first cell to the left of right sibling */
54251 r = cntNew[i-1] - 1;
54252 d = r + 1 - leafData;
54253 assert( d<nMaxCells );
54254 assert( r<nMaxCells );
54255 while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
54256 szRight += szCell[d] + 2;
54257 szLeft -= szCell[r] + 2;
54258 cntNew[i-1]--;
54259 r = cntNew[i-1] - 1;
54260 d = r + 1 - leafData;
54262 szNew[i] = szRight;
54263 szNew[i-1] = szLeft;
54266 /* Either we found one or more cells (cntnew[0])>0) or pPage is
54267 ** a virtual root page. A virtual root page is when the real root
54268 ** page is page 1 and we are the only child of that page.
54270 assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
54272 TRACE(("BALANCE: old: %d %d %d ",
54273 apOld[0]->pgno,
54274 nOld>=2 ? apOld[1]->pgno : 0,
54275 nOld>=3 ? apOld[2]->pgno : 0
54279 ** Allocate k new pages. Reuse old pages where possible.
54281 if( apOld[0]->pgno<=1 ){
54282 rc = SQLITE_CORRUPT_BKPT;
54283 goto balance_cleanup;
54285 pageFlags = apOld[0]->aData[0];
54286 for(i=0; i<k; i++){
54287 MemPage *pNew;
54288 if( i<nOld ){
54289 pNew = apNew[i] = apOld[i];
54290 apOld[i] = 0;
54291 rc = sqlite3PagerWrite(pNew->pDbPage);
54292 nNew++;
54293 if( rc ) goto balance_cleanup;
54294 }else{
54295 assert( i>0 );
54296 rc = allocateBtreePage(pBt, &pNew, &pgno, pgno, 0);
54297 if( rc ) goto balance_cleanup;
54298 apNew[i] = pNew;
54299 nNew++;
54301 /* Set the pointer-map entry for the new sibling page. */
54302 if( ISAUTOVACUUM ){
54303 ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
54304 if( rc!=SQLITE_OK ){
54305 goto balance_cleanup;
54311 /* Free any old pages that were not reused as new pages.
54313 while( i<nOld ){
54314 freePage(apOld[i], &rc);
54315 if( rc ) goto balance_cleanup;
54316 releasePage(apOld[i]);
54317 apOld[i] = 0;
54318 i++;
54322 ** Put the new pages in accending order. This helps to
54323 ** keep entries in the disk file in order so that a scan
54324 ** of the table is a linear scan through the file. That
54325 ** in turn helps the operating system to deliver pages
54326 ** from the disk more rapidly.
54328 ** An O(n^2) insertion sort algorithm is used, but since
54329 ** n is never more than NB (a small constant), that should
54330 ** not be a problem.
54332 ** When NB==3, this one optimization makes the database
54333 ** about 25% faster for large insertions and deletions.
54335 for(i=0; i<k-1; i++){
54336 int minV = apNew[i]->pgno;
54337 int minI = i;
54338 for(j=i+1; j<k; j++){
54339 if( apNew[j]->pgno<(unsigned)minV ){
54340 minI = j;
54341 minV = apNew[j]->pgno;
54344 if( minI>i ){
54345 MemPage *pT;
54346 pT = apNew[i];
54347 apNew[i] = apNew[minI];
54348 apNew[minI] = pT;
54351 TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
54352 apNew[0]->pgno, szNew[0],
54353 nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
54354 nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
54355 nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
54356 nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
54358 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
54359 put4byte(pRight, apNew[nNew-1]->pgno);
54362 ** Evenly distribute the data in apCell[] across the new pages.
54363 ** Insert divider cells into pParent as necessary.
54365 j = 0;
54366 for(i=0; i<nNew; i++){
54367 /* Assemble the new sibling page. */
54368 MemPage *pNew = apNew[i];
54369 assert( j<nMaxCells );
54370 zeroPage(pNew, pageFlags);
54371 assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
54372 assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
54373 assert( pNew->nOverflow==0 );
54375 j = cntNew[i];
54377 /* If the sibling page assembled above was not the right-most sibling,
54378 ** insert a divider cell into the parent page.
54380 assert( i<nNew-1 || j==nCell );
54381 if( j<nCell ){
54382 u8 *pCell;
54383 u8 *pTemp;
54384 int sz;
54386 assert( j<nMaxCells );
54387 pCell = apCell[j];
54388 sz = szCell[j] + leafCorrection;
54389 pTemp = &aOvflSpace[iOvflSpace];
54390 if( !pNew->leaf ){
54391 memcpy(&pNew->aData[8], pCell, 4);
54392 }else if( leafData ){
54393 /* If the tree is a leaf-data tree, and the siblings are leaves,
54394 ** then there is no divider cell in apCell[]. Instead, the divider
54395 ** cell consists of the integer key for the right-most cell of
54396 ** the sibling-page assembled above only.
54398 CellInfo info;
54399 j--;
54400 btreeParseCellPtr(pNew, apCell[j], &info);
54401 pCell = pTemp;
54402 sz = 4 + putVarint(&pCell[4], info.nKey);
54403 pTemp = 0;
54404 }else{
54405 pCell -= 4;
54406 /* Obscure case for non-leaf-data trees: If the cell at pCell was
54407 ** previously stored on a leaf node, and its reported size was 4
54408 ** bytes, then it may actually be smaller than this
54409 ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
54410 ** any cell). But it is important to pass the correct size to
54411 ** insertCell(), so reparse the cell now.
54413 ** Note that this can never happen in an SQLite data file, as all
54414 ** cells are at least 4 bytes. It only happens in b-trees used
54415 ** to evaluate "IN (SELECT ...)" and similar clauses.
54417 if( szCell[j]==4 ){
54418 assert(leafCorrection==4);
54419 sz = cellSizePtr(pParent, pCell);
54422 iOvflSpace += sz;
54423 assert( sz<=pBt->maxLocal+23 );
54424 assert( iOvflSpace <= (int)pBt->pageSize );
54425 insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
54426 if( rc!=SQLITE_OK ) goto balance_cleanup;
54427 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
54429 j++;
54430 nxDiv++;
54433 assert( j==nCell );
54434 assert( nOld>0 );
54435 assert( nNew>0 );
54436 if( (pageFlags & PTF_LEAF)==0 ){
54437 u8 *zChild = &apCopy[nOld-1]->aData[8];
54438 memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
54441 if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
54442 /* The root page of the b-tree now contains no cells. The only sibling
54443 ** page is the right-child of the parent. Copy the contents of the
54444 ** child page into the parent, decreasing the overall height of the
54445 ** b-tree structure by one. This is described as the "balance-shallower"
54446 ** sub-algorithm in some documentation.
54448 ** If this is an auto-vacuum database, the call to copyNodeContent()
54449 ** sets all pointer-map entries corresponding to database image pages
54450 ** for which the pointer is stored within the content being copied.
54452 ** The second assert below verifies that the child page is defragmented
54453 ** (it must be, as it was just reconstructed using assemblePage()). This
54454 ** is important if the parent page happens to be page 1 of the database
54455 ** image. */
54456 assert( nNew==1 );
54457 assert( apNew[0]->nFree ==
54458 (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
54460 copyNodeContent(apNew[0], pParent, &rc);
54461 freePage(apNew[0], &rc);
54462 }else if( ISAUTOVACUUM ){
54463 /* Fix the pointer-map entries for all the cells that were shifted around.
54464 ** There are several different types of pointer-map entries that need to
54465 ** be dealt with by this routine. Some of these have been set already, but
54466 ** many have not. The following is a summary:
54468 ** 1) The entries associated with new sibling pages that were not
54469 ** siblings when this function was called. These have already
54470 ** been set. We don't need to worry about old siblings that were
54471 ** moved to the free-list - the freePage() code has taken care
54472 ** of those.
54474 ** 2) The pointer-map entries associated with the first overflow
54475 ** page in any overflow chains used by new divider cells. These
54476 ** have also already been taken care of by the insertCell() code.
54478 ** 3) If the sibling pages are not leaves, then the child pages of
54479 ** cells stored on the sibling pages may need to be updated.
54481 ** 4) If the sibling pages are not internal intkey nodes, then any
54482 ** overflow pages used by these cells may need to be updated
54483 ** (internal intkey nodes never contain pointers to overflow pages).
54485 ** 5) If the sibling pages are not leaves, then the pointer-map
54486 ** entries for the right-child pages of each sibling may need
54487 ** to be updated.
54489 ** Cases 1 and 2 are dealt with above by other code. The next
54490 ** block deals with cases 3 and 4 and the one after that, case 5. Since
54491 ** setting a pointer map entry is a relatively expensive operation, this
54492 ** code only sets pointer map entries for child or overflow pages that have
54493 ** actually moved between pages. */
54494 MemPage *pNew = apNew[0];
54495 MemPage *pOld = apCopy[0];
54496 int nOverflow = pOld->nOverflow;
54497 int iNextOld = pOld->nCell + nOverflow;
54498 int iOverflow = (nOverflow ? pOld->aOvfl[0].idx : -1);
54499 j = 0; /* Current 'old' sibling page */
54500 k = 0; /* Current 'new' sibling page */
54501 for(i=0; i<nCell; i++){
54502 int isDivider = 0;
54503 while( i==iNextOld ){
54504 /* Cell i is the cell immediately following the last cell on old
54505 ** sibling page j. If the siblings are not leaf pages of an
54506 ** intkey b-tree, then cell i was a divider cell. */
54507 assert( j+1 < ArraySize(apCopy) );
54508 pOld = apCopy[++j];
54509 iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
54510 if( pOld->nOverflow ){
54511 nOverflow = pOld->nOverflow;
54512 iOverflow = i + !leafData + pOld->aOvfl[0].idx;
54514 isDivider = !leafData;
54517 assert(nOverflow>0 || iOverflow<i );
54518 assert(nOverflow<2 || pOld->aOvfl[0].idx==pOld->aOvfl[1].idx-1);
54519 assert(nOverflow<3 || pOld->aOvfl[1].idx==pOld->aOvfl[2].idx-1);
54520 if( i==iOverflow ){
54521 isDivider = 1;
54522 if( (--nOverflow)>0 ){
54523 iOverflow++;
54527 if( i==cntNew[k] ){
54528 /* Cell i is the cell immediately following the last cell on new
54529 ** sibling page k. If the siblings are not leaf pages of an
54530 ** intkey b-tree, then cell i is a divider cell. */
54531 pNew = apNew[++k];
54532 if( !leafData ) continue;
54534 assert( j<nOld );
54535 assert( k<nNew );
54537 /* If the cell was originally divider cell (and is not now) or
54538 ** an overflow cell, or if the cell was located on a different sibling
54539 ** page before the balancing, then the pointer map entries associated
54540 ** with any child or overflow pages need to be updated. */
54541 if( isDivider || pOld->pgno!=pNew->pgno ){
54542 if( !leafCorrection ){
54543 ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
54545 if( szCell[i]>pNew->minLocal ){
54546 ptrmapPutOvflPtr(pNew, apCell[i], &rc);
54551 if( !leafCorrection ){
54552 for(i=0; i<nNew; i++){
54553 u32 key = get4byte(&apNew[i]->aData[8]);
54554 ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
54558 #if 0
54559 /* The ptrmapCheckPages() contains assert() statements that verify that
54560 ** all pointer map pages are set correctly. This is helpful while
54561 ** debugging. This is usually disabled because a corrupt database may
54562 ** cause an assert() statement to fail. */
54563 ptrmapCheckPages(apNew, nNew);
54564 ptrmapCheckPages(&pParent, 1);
54565 #endif
54568 assert( pParent->isInit );
54569 TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
54570 nOld, nNew, nCell));
54573 ** Cleanup before returning.
54575 balance_cleanup:
54576 sqlite3ScratchFree(apCell);
54577 for(i=0; i<nOld; i++){
54578 releasePage(apOld[i]);
54580 for(i=0; i<nNew; i++){
54581 releasePage(apNew[i]);
54584 return rc;
54589 ** This function is called when the root page of a b-tree structure is
54590 ** overfull (has one or more overflow pages).
54592 ** A new child page is allocated and the contents of the current root
54593 ** page, including overflow cells, are copied into the child. The root
54594 ** page is then overwritten to make it an empty page with the right-child
54595 ** pointer pointing to the new page.
54597 ** Before returning, all pointer-map entries corresponding to pages
54598 ** that the new child-page now contains pointers to are updated. The
54599 ** entry corresponding to the new right-child pointer of the root
54600 ** page is also updated.
54602 ** If successful, *ppChild is set to contain a reference to the child
54603 ** page and SQLITE_OK is returned. In this case the caller is required
54604 ** to call releasePage() on *ppChild exactly once. If an error occurs,
54605 ** an error code is returned and *ppChild is set to 0.
54607 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
54608 int rc; /* Return value from subprocedures */
54609 MemPage *pChild = 0; /* Pointer to a new child page */
54610 Pgno pgnoChild = 0; /* Page number of the new child page */
54611 BtShared *pBt = pRoot->pBt; /* The BTree */
54613 assert( pRoot->nOverflow>0 );
54614 assert( sqlite3_mutex_held(pBt->mutex) );
54616 /* Make pRoot, the root page of the b-tree, writable. Allocate a new
54617 ** page that will become the new right-child of pPage. Copy the contents
54618 ** of the node stored on pRoot into the new child page.
54620 rc = sqlite3PagerWrite(pRoot->pDbPage);
54621 if( rc==SQLITE_OK ){
54622 rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
54623 copyNodeContent(pRoot, pChild, &rc);
54624 if( ISAUTOVACUUM ){
54625 ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
54628 if( rc ){
54629 *ppChild = 0;
54630 releasePage(pChild);
54631 return rc;
54633 assert( sqlite3PagerIswriteable(pChild->pDbPage) );
54634 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
54635 assert( pChild->nCell==pRoot->nCell );
54637 TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
54639 /* Copy the overflow cells from pRoot to pChild */
54640 memcpy(pChild->aOvfl, pRoot->aOvfl, pRoot->nOverflow*sizeof(pRoot->aOvfl[0]));
54641 pChild->nOverflow = pRoot->nOverflow;
54643 /* Zero the contents of pRoot. Then install pChild as the right-child. */
54644 zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
54645 put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
54647 *ppChild = pChild;
54648 return SQLITE_OK;
54652 ** The page that pCur currently points to has just been modified in
54653 ** some way. This function figures out if this modification means the
54654 ** tree needs to be balanced, and if so calls the appropriate balancing
54655 ** routine. Balancing routines are:
54657 ** balance_quick()
54658 ** balance_deeper()
54659 ** balance_nonroot()
54661 static int balance(BtCursor *pCur){
54662 int rc = SQLITE_OK;
54663 const int nMin = pCur->pBt->usableSize * 2 / 3;
54664 u8 aBalanceQuickSpace[13];
54665 u8 *pFree = 0;
54667 TESTONLY( int balance_quick_called = 0 );
54668 TESTONLY( int balance_deeper_called = 0 );
54670 do {
54671 int iPage = pCur->iPage;
54672 MemPage *pPage = pCur->apPage[iPage];
54674 if( iPage==0 ){
54675 if( pPage->nOverflow ){
54676 /* The root page of the b-tree is overfull. In this case call the
54677 ** balance_deeper() function to create a new child for the root-page
54678 ** and copy the current contents of the root-page to it. The
54679 ** next iteration of the do-loop will balance the child page.
54681 assert( (balance_deeper_called++)==0 );
54682 rc = balance_deeper(pPage, &pCur->apPage[1]);
54683 if( rc==SQLITE_OK ){
54684 pCur->iPage = 1;
54685 pCur->aiIdx[0] = 0;
54686 pCur->aiIdx[1] = 0;
54687 assert( pCur->apPage[1]->nOverflow );
54689 }else{
54690 break;
54692 }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
54693 break;
54694 }else{
54695 MemPage * const pParent = pCur->apPage[iPage-1];
54696 int const iIdx = pCur->aiIdx[iPage-1];
54698 rc = sqlite3PagerWrite(pParent->pDbPage);
54699 if( rc==SQLITE_OK ){
54700 #ifndef SQLITE_OMIT_QUICKBALANCE
54701 if( pPage->hasData
54702 && pPage->nOverflow==1
54703 && pPage->aOvfl[0].idx==pPage->nCell
54704 && pParent->pgno!=1
54705 && pParent->nCell==iIdx
54707 /* Call balance_quick() to create a new sibling of pPage on which
54708 ** to store the overflow cell. balance_quick() inserts a new cell
54709 ** into pParent, which may cause pParent overflow. If this
54710 ** happens, the next interation of the do-loop will balance pParent
54711 ** use either balance_nonroot() or balance_deeper(). Until this
54712 ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
54713 ** buffer.
54715 ** The purpose of the following assert() is to check that only a
54716 ** single call to balance_quick() is made for each call to this
54717 ** function. If this were not verified, a subtle bug involving reuse
54718 ** of the aBalanceQuickSpace[] might sneak in.
54720 assert( (balance_quick_called++)==0 );
54721 rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
54722 }else
54723 #endif
54725 /* In this case, call balance_nonroot() to redistribute cells
54726 ** between pPage and up to 2 of its sibling pages. This involves
54727 ** modifying the contents of pParent, which may cause pParent to
54728 ** become overfull or underfull. The next iteration of the do-loop
54729 ** will balance the parent page to correct this.
54731 ** If the parent page becomes overfull, the overflow cell or cells
54732 ** are stored in the pSpace buffer allocated immediately below.
54733 ** A subsequent iteration of the do-loop will deal with this by
54734 ** calling balance_nonroot() (balance_deeper() may be called first,
54735 ** but it doesn't deal with overflow cells - just moves them to a
54736 ** different page). Once this subsequent call to balance_nonroot()
54737 ** has completed, it is safe to release the pSpace buffer used by
54738 ** the previous call, as the overflow cell data will have been
54739 ** copied either into the body of a database page or into the new
54740 ** pSpace buffer passed to the latter call to balance_nonroot().
54742 u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
54743 rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1);
54744 if( pFree ){
54745 /* If pFree is not NULL, it points to the pSpace buffer used
54746 ** by a previous call to balance_nonroot(). Its contents are
54747 ** now stored either on real database pages or within the
54748 ** new pSpace buffer, so it may be safely freed here. */
54749 sqlite3PageFree(pFree);
54752 /* The pSpace buffer will be freed after the next call to
54753 ** balance_nonroot(), or just before this function returns, whichever
54754 ** comes first. */
54755 pFree = pSpace;
54759 pPage->nOverflow = 0;
54761 /* The next iteration of the do-loop balances the parent page. */
54762 releasePage(pPage);
54763 pCur->iPage--;
54765 }while( rc==SQLITE_OK );
54767 if( pFree ){
54768 sqlite3PageFree(pFree);
54770 return rc;
54775 ** Insert a new record into the BTree. The key is given by (pKey,nKey)
54776 ** and the data is given by (pData,nData). The cursor is used only to
54777 ** define what table the record should be inserted into. The cursor
54778 ** is left pointing at a random location.
54780 ** For an INTKEY table, only the nKey value of the key is used. pKey is
54781 ** ignored. For a ZERODATA table, the pData and nData are both ignored.
54783 ** If the seekResult parameter is non-zero, then a successful call to
54784 ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
54785 ** been performed. seekResult is the search result returned (a negative
54786 ** number if pCur points at an entry that is smaller than (pKey, nKey), or
54787 ** a positive value if pCur points at an etry that is larger than
54788 ** (pKey, nKey)).
54790 ** If the seekResult parameter is non-zero, then the caller guarantees that
54791 ** cursor pCur is pointing at the existing copy of a row that is to be
54792 ** overwritten. If the seekResult parameter is 0, then cursor pCur may
54793 ** point to any entry or to no entry at all and so this function has to seek
54794 ** the cursor before the new key can be inserted.
54796 SQLITE_PRIVATE int sqlite3BtreeInsert(
54797 BtCursor *pCur, /* Insert data into the table of this cursor */
54798 const void *pKey, i64 nKey, /* The key of the new record */
54799 const void *pData, int nData, /* The data of the new record */
54800 int nZero, /* Number of extra 0 bytes to append to data */
54801 int appendBias, /* True if this is likely an append */
54802 int seekResult /* Result of prior MovetoUnpacked() call */
54804 int rc;
54805 int loc = seekResult; /* -1: before desired location +1: after */
54806 int szNew = 0;
54807 int idx;
54808 MemPage *pPage;
54809 Btree *p = pCur->pBtree;
54810 BtShared *pBt = p->pBt;
54811 unsigned char *oldCell;
54812 unsigned char *newCell = 0;
54814 if( pCur->eState==CURSOR_FAULT ){
54815 assert( pCur->skipNext!=SQLITE_OK );
54816 return pCur->skipNext;
54819 assert( cursorHoldsMutex(pCur) );
54820 assert( pCur->wrFlag && pBt->inTransaction==TRANS_WRITE && !pBt->readOnly );
54821 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
54823 /* Assert that the caller has been consistent. If this cursor was opened
54824 ** expecting an index b-tree, then the caller should be inserting blob
54825 ** keys with no associated data. If the cursor was opened expecting an
54826 ** intkey table, the caller should be inserting integer keys with a
54827 ** blob of associated data. */
54828 assert( (pKey==0)==(pCur->pKeyInfo==0) );
54830 /* If this is an insert into a table b-tree, invalidate any incrblob
54831 ** cursors open on the row being replaced (assuming this is a replace
54832 ** operation - if it is not, the following is a no-op). */
54833 if( pCur->pKeyInfo==0 ){
54834 invalidateIncrblobCursors(p, nKey, 0);
54837 /* Save the positions of any other cursors open on this table.
54839 ** In some cases, the call to btreeMoveto() below is a no-op. For
54840 ** example, when inserting data into a table with auto-generated integer
54841 ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
54842 ** integer key to use. It then calls this function to actually insert the
54843 ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
54844 ** that the cursor is already where it needs to be and returns without
54845 ** doing any work. To avoid thwarting these optimizations, it is important
54846 ** not to clear the cursor here.
54848 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
54849 if( rc ) return rc;
54850 if( !loc ){
54851 rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
54852 if( rc ) return rc;
54854 assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
54856 pPage = pCur->apPage[pCur->iPage];
54857 assert( pPage->intKey || nKey>=0 );
54858 assert( pPage->leaf || !pPage->intKey );
54860 TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
54861 pCur->pgnoRoot, nKey, nData, pPage->pgno,
54862 loc==0 ? "overwrite" : "new entry"));
54863 assert( pPage->isInit );
54864 allocateTempSpace(pBt);
54865 newCell = pBt->pTmpSpace;
54866 if( newCell==0 ) return SQLITE_NOMEM;
54867 rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
54868 if( rc ) goto end_insert;
54869 assert( szNew==cellSizePtr(pPage, newCell) );
54870 assert( szNew <= MX_CELL_SIZE(pBt) );
54871 idx = pCur->aiIdx[pCur->iPage];
54872 if( loc==0 ){
54873 u16 szOld;
54874 assert( idx<pPage->nCell );
54875 rc = sqlite3PagerWrite(pPage->pDbPage);
54876 if( rc ){
54877 goto end_insert;
54879 oldCell = findCell(pPage, idx);
54880 if( !pPage->leaf ){
54881 memcpy(newCell, oldCell, 4);
54883 szOld = cellSizePtr(pPage, oldCell);
54884 rc = clearCell(pPage, oldCell);
54885 dropCell(pPage, idx, szOld, &rc);
54886 if( rc ) goto end_insert;
54887 }else if( loc<0 && pPage->nCell>0 ){
54888 assert( pPage->leaf );
54889 idx = ++pCur->aiIdx[pCur->iPage];
54890 }else{
54891 assert( pPage->leaf );
54893 insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
54894 assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
54896 /* If no error has occured and pPage has an overflow cell, call balance()
54897 ** to redistribute the cells within the tree. Since balance() may move
54898 ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey
54899 ** variables.
54901 ** Previous versions of SQLite called moveToRoot() to move the cursor
54902 ** back to the root page as balance() used to invalidate the contents
54903 ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
54904 ** set the cursor state to "invalid". This makes common insert operations
54905 ** slightly faster.
54907 ** There is a subtle but important optimization here too. When inserting
54908 ** multiple records into an intkey b-tree using a single cursor (as can
54909 ** happen while processing an "INSERT INTO ... SELECT" statement), it
54910 ** is advantageous to leave the cursor pointing to the last entry in
54911 ** the b-tree if possible. If the cursor is left pointing to the last
54912 ** entry in the table, and the next row inserted has an integer key
54913 ** larger than the largest existing key, it is possible to insert the
54914 ** row without seeking the cursor. This can be a big performance boost.
54916 pCur->info.nSize = 0;
54917 pCur->validNKey = 0;
54918 if( rc==SQLITE_OK && pPage->nOverflow ){
54919 rc = balance(pCur);
54921 /* Must make sure nOverflow is reset to zero even if the balance()
54922 ** fails. Internal data structure corruption will result otherwise.
54923 ** Also, set the cursor state to invalid. This stops saveCursorPosition()
54924 ** from trying to save the current position of the cursor. */
54925 pCur->apPage[pCur->iPage]->nOverflow = 0;
54926 pCur->eState = CURSOR_INVALID;
54928 assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
54930 end_insert:
54931 return rc;
54935 ** Delete the entry that the cursor is pointing to. The cursor
54936 ** is left pointing at a arbitrary location.
54938 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
54939 Btree *p = pCur->pBtree;
54940 BtShared *pBt = p->pBt;
54941 int rc; /* Return code */
54942 MemPage *pPage; /* Page to delete cell from */
54943 unsigned char *pCell; /* Pointer to cell to delete */
54944 int iCellIdx; /* Index of cell to delete */
54945 int iCellDepth; /* Depth of node containing pCell */
54947 assert( cursorHoldsMutex(pCur) );
54948 assert( pBt->inTransaction==TRANS_WRITE );
54949 assert( !pBt->readOnly );
54950 assert( pCur->wrFlag );
54951 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
54952 assert( !hasReadConflicts(p, pCur->pgnoRoot) );
54954 if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell)
54955 || NEVER(pCur->eState!=CURSOR_VALID)
54957 return SQLITE_ERROR; /* Something has gone awry. */
54960 /* If this is a delete operation to remove a row from a table b-tree,
54961 ** invalidate any incrblob cursors open on the row being deleted. */
54962 if( pCur->pKeyInfo==0 ){
54963 invalidateIncrblobCursors(p, pCur->info.nKey, 0);
54966 iCellDepth = pCur->iPage;
54967 iCellIdx = pCur->aiIdx[iCellDepth];
54968 pPage = pCur->apPage[iCellDepth];
54969 pCell = findCell(pPage, iCellIdx);
54971 /* If the page containing the entry to delete is not a leaf page, move
54972 ** the cursor to the largest entry in the tree that is smaller than
54973 ** the entry being deleted. This cell will replace the cell being deleted
54974 ** from the internal node. The 'previous' entry is used for this instead
54975 ** of the 'next' entry, as the previous entry is always a part of the
54976 ** sub-tree headed by the child page of the cell being deleted. This makes
54977 ** balancing the tree following the delete operation easier. */
54978 if( !pPage->leaf ){
54979 int notUsed;
54980 rc = sqlite3BtreePrevious(pCur, &notUsed);
54981 if( rc ) return rc;
54984 /* Save the positions of any other cursors open on this table before
54985 ** making any modifications. Make the page containing the entry to be
54986 ** deleted writable. Then free any overflow pages associated with the
54987 ** entry and finally remove the cell itself from within the page.
54989 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
54990 if( rc ) return rc;
54991 rc = sqlite3PagerWrite(pPage->pDbPage);
54992 if( rc ) return rc;
54993 rc = clearCell(pPage, pCell);
54994 dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc);
54995 if( rc ) return rc;
54997 /* If the cell deleted was not located on a leaf page, then the cursor
54998 ** is currently pointing to the largest entry in the sub-tree headed
54999 ** by the child-page of the cell that was just deleted from an internal
55000 ** node. The cell from the leaf node needs to be moved to the internal
55001 ** node to replace the deleted cell. */
55002 if( !pPage->leaf ){
55003 MemPage *pLeaf = pCur->apPage[pCur->iPage];
55004 int nCell;
55005 Pgno n = pCur->apPage[iCellDepth+1]->pgno;
55006 unsigned char *pTmp;
55008 pCell = findCell(pLeaf, pLeaf->nCell-1);
55009 nCell = cellSizePtr(pLeaf, pCell);
55010 assert( MX_CELL_SIZE(pBt) >= nCell );
55012 allocateTempSpace(pBt);
55013 pTmp = pBt->pTmpSpace;
55015 rc = sqlite3PagerWrite(pLeaf->pDbPage);
55016 insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
55017 dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
55018 if( rc ) return rc;
55021 /* Balance the tree. If the entry deleted was located on a leaf page,
55022 ** then the cursor still points to that page. In this case the first
55023 ** call to balance() repairs the tree, and the if(...) condition is
55024 ** never true.
55026 ** Otherwise, if the entry deleted was on an internal node page, then
55027 ** pCur is pointing to the leaf page from which a cell was removed to
55028 ** replace the cell deleted from the internal node. This is slightly
55029 ** tricky as the leaf node may be underfull, and the internal node may
55030 ** be either under or overfull. In this case run the balancing algorithm
55031 ** on the leaf node first. If the balance proceeds far enough up the
55032 ** tree that we can be sure that any problem in the internal node has
55033 ** been corrected, so be it. Otherwise, after balancing the leaf node,
55034 ** walk the cursor up the tree to the internal node and balance it as
55035 ** well. */
55036 rc = balance(pCur);
55037 if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
55038 while( pCur->iPage>iCellDepth ){
55039 releasePage(pCur->apPage[pCur->iPage--]);
55041 rc = balance(pCur);
55044 if( rc==SQLITE_OK ){
55045 moveToRoot(pCur);
55047 return rc;
55051 ** Create a new BTree table. Write into *piTable the page
55052 ** number for the root page of the new table.
55054 ** The type of type is determined by the flags parameter. Only the
55055 ** following values of flags are currently in use. Other values for
55056 ** flags might not work:
55058 ** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
55059 ** BTREE_ZERODATA Used for SQL indices
55061 static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
55062 BtShared *pBt = p->pBt;
55063 MemPage *pRoot;
55064 Pgno pgnoRoot;
55065 int rc;
55066 int ptfFlags; /* Page-type flage for the root page of new table */
55068 assert( sqlite3BtreeHoldsMutex(p) );
55069 assert( pBt->inTransaction==TRANS_WRITE );
55070 assert( !pBt->readOnly );
55072 #ifdef SQLITE_OMIT_AUTOVACUUM
55073 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
55074 if( rc ){
55075 return rc;
55077 #else
55078 if( pBt->autoVacuum ){
55079 Pgno pgnoMove; /* Move a page here to make room for the root-page */
55080 MemPage *pPageMove; /* The page to move to. */
55082 /* Creating a new table may probably require moving an existing database
55083 ** to make room for the new tables root page. In case this page turns
55084 ** out to be an overflow page, delete all overflow page-map caches
55085 ** held by open cursors.
55087 invalidateAllOverflowCache(pBt);
55089 /* Read the value of meta[3] from the database to determine where the
55090 ** root page of the new table should go. meta[3] is the largest root-page
55091 ** created so far, so the new root-page is (meta[3]+1).
55093 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
55094 pgnoRoot++;
55096 /* The new root-page may not be allocated on a pointer-map page, or the
55097 ** PENDING_BYTE page.
55099 while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
55100 pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
55101 pgnoRoot++;
55103 assert( pgnoRoot>=3 );
55105 /* Allocate a page. The page that currently resides at pgnoRoot will
55106 ** be moved to the allocated page (unless the allocated page happens
55107 ** to reside at pgnoRoot).
55109 rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
55110 if( rc!=SQLITE_OK ){
55111 return rc;
55114 if( pgnoMove!=pgnoRoot ){
55115 /* pgnoRoot is the page that will be used for the root-page of
55116 ** the new table (assuming an error did not occur). But we were
55117 ** allocated pgnoMove. If required (i.e. if it was not allocated
55118 ** by extending the file), the current page at position pgnoMove
55119 ** is already journaled.
55121 u8 eType = 0;
55122 Pgno iPtrPage = 0;
55124 releasePage(pPageMove);
55126 /* Move the page currently at pgnoRoot to pgnoMove. */
55127 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
55128 if( rc!=SQLITE_OK ){
55129 return rc;
55131 rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
55132 if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
55133 rc = SQLITE_CORRUPT_BKPT;
55135 if( rc!=SQLITE_OK ){
55136 releasePage(pRoot);
55137 return rc;
55139 assert( eType!=PTRMAP_ROOTPAGE );
55140 assert( eType!=PTRMAP_FREEPAGE );
55141 rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
55142 releasePage(pRoot);
55144 /* Obtain the page at pgnoRoot */
55145 if( rc!=SQLITE_OK ){
55146 return rc;
55148 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
55149 if( rc!=SQLITE_OK ){
55150 return rc;
55152 rc = sqlite3PagerWrite(pRoot->pDbPage);
55153 if( rc!=SQLITE_OK ){
55154 releasePage(pRoot);
55155 return rc;
55157 }else{
55158 pRoot = pPageMove;
55161 /* Update the pointer-map and meta-data with the new root-page number. */
55162 ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
55163 if( rc ){
55164 releasePage(pRoot);
55165 return rc;
55168 /* When the new root page was allocated, page 1 was made writable in
55169 ** order either to increase the database filesize, or to decrement the
55170 ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
55172 assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
55173 rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
55174 if( NEVER(rc) ){
55175 releasePage(pRoot);
55176 return rc;
55179 }else{
55180 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
55181 if( rc ) return rc;
55183 #endif
55184 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
55185 if( createTabFlags & BTREE_INTKEY ){
55186 ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
55187 }else{
55188 ptfFlags = PTF_ZERODATA | PTF_LEAF;
55190 zeroPage(pRoot, ptfFlags);
55191 sqlite3PagerUnref(pRoot->pDbPage);
55192 assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
55193 *piTable = (int)pgnoRoot;
55194 return SQLITE_OK;
55196 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
55197 int rc;
55198 sqlite3BtreeEnter(p);
55199 rc = btreeCreateTable(p, piTable, flags);
55200 sqlite3BtreeLeave(p);
55201 return rc;
55205 ** Erase the given database page and all its children. Return
55206 ** the page to the freelist.
55208 static int clearDatabasePage(
55209 BtShared *pBt, /* The BTree that contains the table */
55210 Pgno pgno, /* Page number to clear */
55211 int freePageFlag, /* Deallocate page if true */
55212 int *pnChange /* Add number of Cells freed to this counter */
55214 MemPage *pPage;
55215 int rc;
55216 unsigned char *pCell;
55217 int i;
55219 assert( sqlite3_mutex_held(pBt->mutex) );
55220 if( pgno>btreePagecount(pBt) ){
55221 return SQLITE_CORRUPT_BKPT;
55224 rc = getAndInitPage(pBt, pgno, &pPage);
55225 if( rc ) return rc;
55226 for(i=0; i<pPage->nCell; i++){
55227 pCell = findCell(pPage, i);
55228 if( !pPage->leaf ){
55229 rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
55230 if( rc ) goto cleardatabasepage_out;
55232 rc = clearCell(pPage, pCell);
55233 if( rc ) goto cleardatabasepage_out;
55235 if( !pPage->leaf ){
55236 rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
55237 if( rc ) goto cleardatabasepage_out;
55238 }else if( pnChange ){
55239 assert( pPage->intKey );
55240 *pnChange += pPage->nCell;
55242 if( freePageFlag ){
55243 freePage(pPage, &rc);
55244 }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
55245 zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
55248 cleardatabasepage_out:
55249 releasePage(pPage);
55250 return rc;
55254 ** Delete all information from a single table in the database. iTable is
55255 ** the page number of the root of the table. After this routine returns,
55256 ** the root page is empty, but still exists.
55258 ** This routine will fail with SQLITE_LOCKED if there are any open
55259 ** read cursors on the table. Open write cursors are moved to the
55260 ** root of the table.
55262 ** If pnChange is not NULL, then table iTable must be an intkey table. The
55263 ** integer value pointed to by pnChange is incremented by the number of
55264 ** entries in the table.
55266 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
55267 int rc;
55268 BtShared *pBt = p->pBt;
55269 sqlite3BtreeEnter(p);
55270 assert( p->inTrans==TRANS_WRITE );
55272 /* Invalidate all incrblob cursors open on table iTable (assuming iTable
55273 ** is the root of a table b-tree - if it is not, the following call is
55274 ** a no-op). */
55275 invalidateIncrblobCursors(p, 0, 1);
55277 rc = saveAllCursors(pBt, (Pgno)iTable, 0);
55278 if( SQLITE_OK==rc ){
55279 rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
55281 sqlite3BtreeLeave(p);
55282 return rc;
55286 ** Erase all information in a table and add the root of the table to
55287 ** the freelist. Except, the root of the principle table (the one on
55288 ** page 1) is never added to the freelist.
55290 ** This routine will fail with SQLITE_LOCKED if there are any open
55291 ** cursors on the table.
55293 ** If AUTOVACUUM is enabled and the page at iTable is not the last
55294 ** root page in the database file, then the last root page
55295 ** in the database file is moved into the slot formerly occupied by
55296 ** iTable and that last slot formerly occupied by the last root page
55297 ** is added to the freelist instead of iTable. In this say, all
55298 ** root pages are kept at the beginning of the database file, which
55299 ** is necessary for AUTOVACUUM to work right. *piMoved is set to the
55300 ** page number that used to be the last root page in the file before
55301 ** the move. If no page gets moved, *piMoved is set to 0.
55302 ** The last root page is recorded in meta[3] and the value of
55303 ** meta[3] is updated by this procedure.
55305 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
55306 int rc;
55307 MemPage *pPage = 0;
55308 BtShared *pBt = p->pBt;
55310 assert( sqlite3BtreeHoldsMutex(p) );
55311 assert( p->inTrans==TRANS_WRITE );
55313 /* It is illegal to drop a table if any cursors are open on the
55314 ** database. This is because in auto-vacuum mode the backend may
55315 ** need to move another root-page to fill a gap left by the deleted
55316 ** root page. If an open cursor was using this page a problem would
55317 ** occur.
55319 ** This error is caught long before control reaches this point.
55321 if( NEVER(pBt->pCursor) ){
55322 sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
55323 return SQLITE_LOCKED_SHAREDCACHE;
55326 rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
55327 if( rc ) return rc;
55328 rc = sqlite3BtreeClearTable(p, iTable, 0);
55329 if( rc ){
55330 releasePage(pPage);
55331 return rc;
55334 *piMoved = 0;
55336 if( iTable>1 ){
55337 #ifdef SQLITE_OMIT_AUTOVACUUM
55338 freePage(pPage, &rc);
55339 releasePage(pPage);
55340 #else
55341 if( pBt->autoVacuum ){
55342 Pgno maxRootPgno;
55343 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
55345 if( iTable==maxRootPgno ){
55346 /* If the table being dropped is the table with the largest root-page
55347 ** number in the database, put the root page on the free list.
55349 freePage(pPage, &rc);
55350 releasePage(pPage);
55351 if( rc!=SQLITE_OK ){
55352 return rc;
55354 }else{
55355 /* The table being dropped does not have the largest root-page
55356 ** number in the database. So move the page that does into the
55357 ** gap left by the deleted root-page.
55359 MemPage *pMove;
55360 releasePage(pPage);
55361 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
55362 if( rc!=SQLITE_OK ){
55363 return rc;
55365 rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
55366 releasePage(pMove);
55367 if( rc!=SQLITE_OK ){
55368 return rc;
55370 pMove = 0;
55371 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
55372 freePage(pMove, &rc);
55373 releasePage(pMove);
55374 if( rc!=SQLITE_OK ){
55375 return rc;
55377 *piMoved = maxRootPgno;
55380 /* Set the new 'max-root-page' value in the database header. This
55381 ** is the old value less one, less one more if that happens to
55382 ** be a root-page number, less one again if that is the
55383 ** PENDING_BYTE_PAGE.
55385 maxRootPgno--;
55386 while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
55387 || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
55388 maxRootPgno--;
55390 assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
55392 rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
55393 }else{
55394 freePage(pPage, &rc);
55395 releasePage(pPage);
55397 #endif
55398 }else{
55399 /* If sqlite3BtreeDropTable was called on page 1.
55400 ** This really never should happen except in a corrupt
55401 ** database.
55403 zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
55404 releasePage(pPage);
55406 return rc;
55408 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
55409 int rc;
55410 sqlite3BtreeEnter(p);
55411 rc = btreeDropTable(p, iTable, piMoved);
55412 sqlite3BtreeLeave(p);
55413 return rc;
55418 ** This function may only be called if the b-tree connection already
55419 ** has a read or write transaction open on the database.
55421 ** Read the meta-information out of a database file. Meta[0]
55422 ** is the number of free pages currently in the database. Meta[1]
55423 ** through meta[15] are available for use by higher layers. Meta[0]
55424 ** is read-only, the others are read/write.
55426 ** The schema layer numbers meta values differently. At the schema
55427 ** layer (and the SetCookie and ReadCookie opcodes) the number of
55428 ** free pages is not visible. So Cookie[0] is the same as Meta[1].
55430 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
55431 BtShared *pBt = p->pBt;
55433 sqlite3BtreeEnter(p);
55434 assert( p->inTrans>TRANS_NONE );
55435 assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
55436 assert( pBt->pPage1 );
55437 assert( idx>=0 && idx<=15 );
55439 *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
55441 /* If auto-vacuum is disabled in this build and this is an auto-vacuum
55442 ** database, mark the database as read-only. */
55443 #ifdef SQLITE_OMIT_AUTOVACUUM
55444 if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ) pBt->readOnly = 1;
55445 #endif
55447 sqlite3BtreeLeave(p);
55451 ** Write meta-information back into the database. Meta[0] is
55452 ** read-only and may not be written.
55454 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
55455 BtShared *pBt = p->pBt;
55456 unsigned char *pP1;
55457 int rc;
55458 assert( idx>=1 && idx<=15 );
55459 sqlite3BtreeEnter(p);
55460 assert( p->inTrans==TRANS_WRITE );
55461 assert( pBt->pPage1!=0 );
55462 pP1 = pBt->pPage1->aData;
55463 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
55464 if( rc==SQLITE_OK ){
55465 put4byte(&pP1[36 + idx*4], iMeta);
55466 #ifndef SQLITE_OMIT_AUTOVACUUM
55467 if( idx==BTREE_INCR_VACUUM ){
55468 assert( pBt->autoVacuum || iMeta==0 );
55469 assert( iMeta==0 || iMeta==1 );
55470 pBt->incrVacuum = (u8)iMeta;
55472 #endif
55474 sqlite3BtreeLeave(p);
55475 return rc;
55478 #ifndef SQLITE_OMIT_BTREECOUNT
55480 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
55481 ** number of entries in the b-tree and write the result to *pnEntry.
55483 ** SQLITE_OK is returned if the operation is successfully executed.
55484 ** Otherwise, if an error is encountered (i.e. an IO error or database
55485 ** corruption) an SQLite error code is returned.
55487 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
55488 i64 nEntry = 0; /* Value to return in *pnEntry */
55489 int rc; /* Return code */
55491 if( pCur->pgnoRoot==0 ){
55492 *pnEntry = 0;
55493 return SQLITE_OK;
55495 rc = moveToRoot(pCur);
55497 /* Unless an error occurs, the following loop runs one iteration for each
55498 ** page in the B-Tree structure (not including overflow pages).
55500 while( rc==SQLITE_OK ){
55501 int iIdx; /* Index of child node in parent */
55502 MemPage *pPage; /* Current page of the b-tree */
55504 /* If this is a leaf page or the tree is not an int-key tree, then
55505 ** this page contains countable entries. Increment the entry counter
55506 ** accordingly.
55508 pPage = pCur->apPage[pCur->iPage];
55509 if( pPage->leaf || !pPage->intKey ){
55510 nEntry += pPage->nCell;
55513 /* pPage is a leaf node. This loop navigates the cursor so that it
55514 ** points to the first interior cell that it points to the parent of
55515 ** the next page in the tree that has not yet been visited. The
55516 ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
55517 ** of the page, or to the number of cells in the page if the next page
55518 ** to visit is the right-child of its parent.
55520 ** If all pages in the tree have been visited, return SQLITE_OK to the
55521 ** caller.
55523 if( pPage->leaf ){
55524 do {
55525 if( pCur->iPage==0 ){
55526 /* All pages of the b-tree have been visited. Return successfully. */
55527 *pnEntry = nEntry;
55528 return SQLITE_OK;
55530 moveToParent(pCur);
55531 }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
55533 pCur->aiIdx[pCur->iPage]++;
55534 pPage = pCur->apPage[pCur->iPage];
55537 /* Descend to the child node of the cell that the cursor currently
55538 ** points at. This is the right-child if (iIdx==pPage->nCell).
55540 iIdx = pCur->aiIdx[pCur->iPage];
55541 if( iIdx==pPage->nCell ){
55542 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
55543 }else{
55544 rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
55548 /* An error has occurred. Return an error code. */
55549 return rc;
55551 #endif
55554 ** Return the pager associated with a BTree. This routine is used for
55555 ** testing and debugging only.
55557 SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
55558 return p->pBt->pPager;
55561 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
55563 ** Append a message to the error message string.
55565 static void checkAppendMsg(
55566 IntegrityCk *pCheck,
55567 char *zMsg1,
55568 const char *zFormat,
55571 va_list ap;
55572 if( !pCheck->mxErr ) return;
55573 pCheck->mxErr--;
55574 pCheck->nErr++;
55575 va_start(ap, zFormat);
55576 if( pCheck->errMsg.nChar ){
55577 sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
55579 if( zMsg1 ){
55580 sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
55582 sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
55583 va_end(ap);
55584 if( pCheck->errMsg.mallocFailed ){
55585 pCheck->mallocFailed = 1;
55588 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
55590 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
55592 ** Add 1 to the reference count for page iPage. If this is the second
55593 ** reference to the page, add an error message to pCheck->zErrMsg.
55594 ** Return 1 if there are 2 ore more references to the page and 0 if
55595 ** if this is the first reference to the page.
55597 ** Also check that the page number is in bounds.
55599 static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
55600 if( iPage==0 ) return 1;
55601 if( iPage>pCheck->nPage ){
55602 checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
55603 return 1;
55605 if( pCheck->anRef[iPage]==1 ){
55606 checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
55607 return 1;
55609 return (pCheck->anRef[iPage]++)>1;
55612 #ifndef SQLITE_OMIT_AUTOVACUUM
55614 ** Check that the entry in the pointer-map for page iChild maps to
55615 ** page iParent, pointer type ptrType. If not, append an error message
55616 ** to pCheck.
55618 static void checkPtrmap(
55619 IntegrityCk *pCheck, /* Integrity check context */
55620 Pgno iChild, /* Child page number */
55621 u8 eType, /* Expected pointer map type */
55622 Pgno iParent, /* Expected pointer map parent page number */
55623 char *zContext /* Context description (used for error msg) */
55625 int rc;
55626 u8 ePtrmapType;
55627 Pgno iPtrmapParent;
55629 rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
55630 if( rc!=SQLITE_OK ){
55631 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
55632 checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
55633 return;
55636 if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
55637 checkAppendMsg(pCheck, zContext,
55638 "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
55639 iChild, eType, iParent, ePtrmapType, iPtrmapParent);
55642 #endif
55645 ** Check the integrity of the freelist or of an overflow page list.
55646 ** Verify that the number of pages on the list is N.
55648 static void checkList(
55649 IntegrityCk *pCheck, /* Integrity checking context */
55650 int isFreeList, /* True for a freelist. False for overflow page list */
55651 int iPage, /* Page number for first page in the list */
55652 int N, /* Expected number of pages in the list */
55653 char *zContext /* Context for error messages */
55655 int i;
55656 int expected = N;
55657 int iFirst = iPage;
55658 while( N-- > 0 && pCheck->mxErr ){
55659 DbPage *pOvflPage;
55660 unsigned char *pOvflData;
55661 if( iPage<1 ){
55662 checkAppendMsg(pCheck, zContext,
55663 "%d of %d pages missing from overflow list starting at %d",
55664 N+1, expected, iFirst);
55665 break;
55667 if( checkRef(pCheck, iPage, zContext) ) break;
55668 if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
55669 checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
55670 break;
55672 pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
55673 if( isFreeList ){
55674 int n = get4byte(&pOvflData[4]);
55675 #ifndef SQLITE_OMIT_AUTOVACUUM
55676 if( pCheck->pBt->autoVacuum ){
55677 checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
55679 #endif
55680 if( n>(int)pCheck->pBt->usableSize/4-2 ){
55681 checkAppendMsg(pCheck, zContext,
55682 "freelist leaf count too big on page %d", iPage);
55683 N--;
55684 }else{
55685 for(i=0; i<n; i++){
55686 Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
55687 #ifndef SQLITE_OMIT_AUTOVACUUM
55688 if( pCheck->pBt->autoVacuum ){
55689 checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
55691 #endif
55692 checkRef(pCheck, iFreePage, zContext);
55694 N -= n;
55697 #ifndef SQLITE_OMIT_AUTOVACUUM
55698 else{
55699 /* If this database supports auto-vacuum and iPage is not the last
55700 ** page in this overflow list, check that the pointer-map entry for
55701 ** the following page matches iPage.
55703 if( pCheck->pBt->autoVacuum && N>0 ){
55704 i = get4byte(pOvflData);
55705 checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
55708 #endif
55709 iPage = get4byte(pOvflData);
55710 sqlite3PagerUnref(pOvflPage);
55713 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
55715 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
55717 ** Do various sanity checks on a single page of a tree. Return
55718 ** the tree depth. Root pages return 0. Parents of root pages
55719 ** return 1, and so forth.
55721 ** These checks are done:
55723 ** 1. Make sure that cells and freeblocks do not overlap
55724 ** but combine to completely cover the page.
55725 ** NO 2. Make sure cell keys are in order.
55726 ** NO 3. Make sure no key is less than or equal to zLowerBound.
55727 ** NO 4. Make sure no key is greater than or equal to zUpperBound.
55728 ** 5. Check the integrity of overflow pages.
55729 ** 6. Recursively call checkTreePage on all children.
55730 ** 7. Verify that the depth of all children is the same.
55731 ** 8. Make sure this page is at least 33% full or else it is
55732 ** the root of the tree.
55734 static int checkTreePage(
55735 IntegrityCk *pCheck, /* Context for the sanity check */
55736 int iPage, /* Page number of the page to check */
55737 char *zParentContext, /* Parent context */
55738 i64 *pnParentMinKey,
55739 i64 *pnParentMaxKey
55741 MemPage *pPage;
55742 int i, rc, depth, d2, pgno, cnt;
55743 int hdr, cellStart;
55744 int nCell;
55745 u8 *data;
55746 BtShared *pBt;
55747 int usableSize;
55748 char zContext[100];
55749 char *hit = 0;
55750 i64 nMinKey = 0;
55751 i64 nMaxKey = 0;
55753 sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
55755 /* Check that the page exists
55757 pBt = pCheck->pBt;
55758 usableSize = pBt->usableSize;
55759 if( iPage==0 ) return 0;
55760 if( checkRef(pCheck, iPage, zParentContext) ) return 0;
55761 if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
55762 checkAppendMsg(pCheck, zContext,
55763 "unable to get the page. error code=%d", rc);
55764 return 0;
55767 /* Clear MemPage.isInit to make sure the corruption detection code in
55768 ** btreeInitPage() is executed. */
55769 pPage->isInit = 0;
55770 if( (rc = btreeInitPage(pPage))!=0 ){
55771 assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
55772 checkAppendMsg(pCheck, zContext,
55773 "btreeInitPage() returns error code %d", rc);
55774 releasePage(pPage);
55775 return 0;
55778 /* Check out all the cells.
55780 depth = 0;
55781 for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
55782 u8 *pCell;
55783 u32 sz;
55784 CellInfo info;
55786 /* Check payload overflow pages
55788 sqlite3_snprintf(sizeof(zContext), zContext,
55789 "On tree page %d cell %d: ", iPage, i);
55790 pCell = findCell(pPage,i);
55791 btreeParseCellPtr(pPage, pCell, &info);
55792 sz = info.nData;
55793 if( !pPage->intKey ) sz += (int)info.nKey;
55794 /* For intKey pages, check that the keys are in order.
55796 else if( i==0 ) nMinKey = nMaxKey = info.nKey;
55797 else{
55798 if( info.nKey <= nMaxKey ){
55799 checkAppendMsg(pCheck, zContext,
55800 "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
55802 nMaxKey = info.nKey;
55804 assert( sz==info.nPayload );
55805 if( (sz>info.nLocal)
55806 && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
55808 int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
55809 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
55810 #ifndef SQLITE_OMIT_AUTOVACUUM
55811 if( pBt->autoVacuum ){
55812 checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
55814 #endif
55815 checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
55818 /* Check sanity of left child page.
55820 if( !pPage->leaf ){
55821 pgno = get4byte(pCell);
55822 #ifndef SQLITE_OMIT_AUTOVACUUM
55823 if( pBt->autoVacuum ){
55824 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
55826 #endif
55827 d2 = checkTreePage(pCheck, pgno, zContext, &nMinKey, i==0 ? NULL : &nMaxKey);
55828 if( i>0 && d2!=depth ){
55829 checkAppendMsg(pCheck, zContext, "Child page depth differs");
55831 depth = d2;
55835 if( !pPage->leaf ){
55836 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
55837 sqlite3_snprintf(sizeof(zContext), zContext,
55838 "On page %d at right child: ", iPage);
55839 #ifndef SQLITE_OMIT_AUTOVACUUM
55840 if( pBt->autoVacuum ){
55841 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
55843 #endif
55844 checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey);
55847 /* For intKey leaf pages, check that the min/max keys are in order
55848 ** with any left/parent/right pages.
55850 if( pPage->leaf && pPage->intKey ){
55851 /* if we are a left child page */
55852 if( pnParentMinKey ){
55853 /* if we are the left most child page */
55854 if( !pnParentMaxKey ){
55855 if( nMaxKey > *pnParentMinKey ){
55856 checkAppendMsg(pCheck, zContext,
55857 "Rowid %lld out of order (max larger than parent min of %lld)",
55858 nMaxKey, *pnParentMinKey);
55860 }else{
55861 if( nMinKey <= *pnParentMinKey ){
55862 checkAppendMsg(pCheck, zContext,
55863 "Rowid %lld out of order (min less than parent min of %lld)",
55864 nMinKey, *pnParentMinKey);
55866 if( nMaxKey > *pnParentMaxKey ){
55867 checkAppendMsg(pCheck, zContext,
55868 "Rowid %lld out of order (max larger than parent max of %lld)",
55869 nMaxKey, *pnParentMaxKey);
55871 *pnParentMinKey = nMaxKey;
55873 /* else if we're a right child page */
55874 } else if( pnParentMaxKey ){
55875 if( nMinKey <= *pnParentMaxKey ){
55876 checkAppendMsg(pCheck, zContext,
55877 "Rowid %lld out of order (min less than parent max of %lld)",
55878 nMinKey, *pnParentMaxKey);
55883 /* Check for complete coverage of the page
55885 data = pPage->aData;
55886 hdr = pPage->hdrOffset;
55887 hit = sqlite3PageMalloc( pBt->pageSize );
55888 if( hit==0 ){
55889 pCheck->mallocFailed = 1;
55890 }else{
55891 int contentOffset = get2byteNotZero(&data[hdr+5]);
55892 assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */
55893 memset(hit+contentOffset, 0, usableSize-contentOffset);
55894 memset(hit, 1, contentOffset);
55895 nCell = get2byte(&data[hdr+3]);
55896 cellStart = hdr + 12 - 4*pPage->leaf;
55897 for(i=0; i<nCell; i++){
55898 int pc = get2byte(&data[cellStart+i*2]);
55899 u32 size = 65536;
55900 int j;
55901 if( pc<=usableSize-4 ){
55902 size = cellSizePtr(pPage, &data[pc]);
55904 if( (int)(pc+size-1)>=usableSize ){
55905 checkAppendMsg(pCheck, 0,
55906 "Corruption detected in cell %d on page %d",i,iPage);
55907 }else{
55908 for(j=pc+size-1; j>=pc; j--) hit[j]++;
55911 i = get2byte(&data[hdr+1]);
55912 while( i>0 ){
55913 int size, j;
55914 assert( i<=usableSize-4 ); /* Enforced by btreeInitPage() */
55915 size = get2byte(&data[i+2]);
55916 assert( i+size<=usableSize ); /* Enforced by btreeInitPage() */
55917 for(j=i+size-1; j>=i; j--) hit[j]++;
55918 j = get2byte(&data[i]);
55919 assert( j==0 || j>i+size ); /* Enforced by btreeInitPage() */
55920 assert( j<=usableSize-4 ); /* Enforced by btreeInitPage() */
55921 i = j;
55923 for(i=cnt=0; i<usableSize; i++){
55924 if( hit[i]==0 ){
55925 cnt++;
55926 }else if( hit[i]>1 ){
55927 checkAppendMsg(pCheck, 0,
55928 "Multiple uses for byte %d of page %d", i, iPage);
55929 break;
55932 if( cnt!=data[hdr+7] ){
55933 checkAppendMsg(pCheck, 0,
55934 "Fragmentation of %d bytes reported as %d on page %d",
55935 cnt, data[hdr+7], iPage);
55938 sqlite3PageFree(hit);
55939 releasePage(pPage);
55940 return depth+1;
55942 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
55944 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
55946 ** This routine does a complete check of the given BTree file. aRoot[] is
55947 ** an array of pages numbers were each page number is the root page of
55948 ** a table. nRoot is the number of entries in aRoot.
55950 ** A read-only or read-write transaction must be opened before calling
55951 ** this function.
55953 ** Write the number of error seen in *pnErr. Except for some memory
55954 ** allocation errors, an error message held in memory obtained from
55955 ** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
55956 ** returned. If a memory allocation error occurs, NULL is returned.
55958 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
55959 Btree *p, /* The btree to be checked */
55960 int *aRoot, /* An array of root pages numbers for individual trees */
55961 int nRoot, /* Number of entries in aRoot[] */
55962 int mxErr, /* Stop reporting errors after this many */
55963 int *pnErr /* Write number of errors seen to this variable */
55965 Pgno i;
55966 int nRef;
55967 IntegrityCk sCheck;
55968 BtShared *pBt = p->pBt;
55969 char zErr[100];
55971 sqlite3BtreeEnter(p);
55972 assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
55973 nRef = sqlite3PagerRefcount(pBt->pPager);
55974 sCheck.pBt = pBt;
55975 sCheck.pPager = pBt->pPager;
55976 sCheck.nPage = btreePagecount(sCheck.pBt);
55977 sCheck.mxErr = mxErr;
55978 sCheck.nErr = 0;
55979 sCheck.mallocFailed = 0;
55980 *pnErr = 0;
55981 if( sCheck.nPage==0 ){
55982 sqlite3BtreeLeave(p);
55983 return 0;
55985 sCheck.anRef = sqlite3Malloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
55986 if( !sCheck.anRef ){
55987 *pnErr = 1;
55988 sqlite3BtreeLeave(p);
55989 return 0;
55991 for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
55992 i = PENDING_BYTE_PAGE(pBt);
55993 if( i<=sCheck.nPage ){
55994 sCheck.anRef[i] = 1;
55996 sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), 20000);
55997 sCheck.errMsg.useMalloc = 2;
55999 /* Check the integrity of the freelist
56001 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
56002 get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
56004 /* Check all the tables.
56006 for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
56007 if( aRoot[i]==0 ) continue;
56008 #ifndef SQLITE_OMIT_AUTOVACUUM
56009 if( pBt->autoVacuum && aRoot[i]>1 ){
56010 checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
56012 #endif
56013 checkTreePage(&sCheck, aRoot[i], "List of tree roots: ", NULL, NULL);
56016 /* Make sure every page in the file is referenced
56018 for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
56019 #ifdef SQLITE_OMIT_AUTOVACUUM
56020 if( sCheck.anRef[i]==0 ){
56021 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
56023 #else
56024 /* If the database supports auto-vacuum, make sure no tables contain
56025 ** references to pointer-map pages.
56027 if( sCheck.anRef[i]==0 &&
56028 (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
56029 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
56031 if( sCheck.anRef[i]!=0 &&
56032 (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
56033 checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
56035 #endif
56038 /* Make sure this analysis did not leave any unref() pages.
56039 ** This is an internal consistency check; an integrity check
56040 ** of the integrity check.
56042 if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
56043 checkAppendMsg(&sCheck, 0,
56044 "Outstanding page count goes from %d to %d during this analysis",
56045 nRef, sqlite3PagerRefcount(pBt->pPager)
56049 /* Clean up and report errors.
56051 sqlite3BtreeLeave(p);
56052 sqlite3_free(sCheck.anRef);
56053 if( sCheck.mallocFailed ){
56054 sqlite3StrAccumReset(&sCheck.errMsg);
56055 *pnErr = sCheck.nErr+1;
56056 return 0;
56058 *pnErr = sCheck.nErr;
56059 if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
56060 return sqlite3StrAccumFinish(&sCheck.errMsg);
56062 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
56065 ** Return the full pathname of the underlying database file.
56067 ** The pager filename is invariant as long as the pager is
56068 ** open so it is safe to access without the BtShared mutex.
56070 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
56071 assert( p->pBt->pPager!=0 );
56072 return sqlite3PagerFilename(p->pBt->pPager);
56076 ** Return the pathname of the journal file for this database. The return
56077 ** value of this routine is the same regardless of whether the journal file
56078 ** has been created or not.
56080 ** The pager journal filename is invariant as long as the pager is
56081 ** open so it is safe to access without the BtShared mutex.
56083 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
56084 assert( p->pBt->pPager!=0 );
56085 return sqlite3PagerJournalname(p->pBt->pPager);
56089 ** Return non-zero if a transaction is active.
56091 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
56092 assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
56093 return (p && (p->inTrans==TRANS_WRITE));
56096 #ifndef SQLITE_OMIT_WAL
56098 ** Run a checkpoint on the Btree passed as the first argument.
56100 ** Return SQLITE_LOCKED if this or any other connection has an open
56101 ** transaction on the shared-cache the argument Btree is connected to.
56103 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
56105 SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
56106 int rc = SQLITE_OK;
56107 if( p ){
56108 BtShared *pBt = p->pBt;
56109 sqlite3BtreeEnter(p);
56110 if( pBt->inTransaction!=TRANS_NONE ){
56111 rc = SQLITE_LOCKED;
56112 }else{
56113 rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
56115 sqlite3BtreeLeave(p);
56117 return rc;
56119 #endif
56122 ** Return non-zero if a read (or write) transaction is active.
56124 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
56125 assert( p );
56126 assert( sqlite3_mutex_held(p->db->mutex) );
56127 return p->inTrans!=TRANS_NONE;
56130 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
56131 assert( p );
56132 assert( sqlite3_mutex_held(p->db->mutex) );
56133 return p->nBackup!=0;
56137 ** This function returns a pointer to a blob of memory associated with
56138 ** a single shared-btree. The memory is used by client code for its own
56139 ** purposes (for example, to store a high-level schema associated with
56140 ** the shared-btree). The btree layer manages reference counting issues.
56142 ** The first time this is called on a shared-btree, nBytes bytes of memory
56143 ** are allocated, zeroed, and returned to the caller. For each subsequent
56144 ** call the nBytes parameter is ignored and a pointer to the same blob
56145 ** of memory returned.
56147 ** If the nBytes parameter is 0 and the blob of memory has not yet been
56148 ** allocated, a null pointer is returned. If the blob has already been
56149 ** allocated, it is returned as normal.
56151 ** Just before the shared-btree is closed, the function passed as the
56152 ** xFree argument when the memory allocation was made is invoked on the
56153 ** blob of allocated memory. The xFree function should not call sqlite3_free()
56154 ** on the memory, the btree layer does that.
56156 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
56157 BtShared *pBt = p->pBt;
56158 sqlite3BtreeEnter(p);
56159 if( !pBt->pSchema && nBytes ){
56160 pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
56161 pBt->xFreeSchema = xFree;
56163 sqlite3BtreeLeave(p);
56164 return pBt->pSchema;
56168 ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
56169 ** btree as the argument handle holds an exclusive lock on the
56170 ** sqlite_master table. Otherwise SQLITE_OK.
56172 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
56173 int rc;
56174 assert( sqlite3_mutex_held(p->db->mutex) );
56175 sqlite3BtreeEnter(p);
56176 rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
56177 assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
56178 sqlite3BtreeLeave(p);
56179 return rc;
56183 #ifndef SQLITE_OMIT_SHARED_CACHE
56185 ** Obtain a lock on the table whose root page is iTab. The
56186 ** lock is a write lock if isWritelock is true or a read lock
56187 ** if it is false.
56189 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
56190 int rc = SQLITE_OK;
56191 assert( p->inTrans!=TRANS_NONE );
56192 if( p->sharable ){
56193 u8 lockType = READ_LOCK + isWriteLock;
56194 assert( READ_LOCK+1==WRITE_LOCK );
56195 assert( isWriteLock==0 || isWriteLock==1 );
56197 sqlite3BtreeEnter(p);
56198 rc = querySharedCacheTableLock(p, iTab, lockType);
56199 if( rc==SQLITE_OK ){
56200 rc = setSharedCacheTableLock(p, iTab, lockType);
56202 sqlite3BtreeLeave(p);
56204 return rc;
56206 #endif
56208 #ifndef SQLITE_OMIT_INCRBLOB
56210 ** Argument pCsr must be a cursor opened for writing on an
56211 ** INTKEY table currently pointing at a valid table entry.
56212 ** This function modifies the data stored as part of that entry.
56214 ** Only the data content may only be modified, it is not possible to
56215 ** change the length of the data stored. If this function is called with
56216 ** parameters that attempt to write past the end of the existing data,
56217 ** no modifications are made and SQLITE_CORRUPT is returned.
56219 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
56220 int rc;
56221 assert( cursorHoldsMutex(pCsr) );
56222 assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
56223 assert( pCsr->isIncrblobHandle );
56225 rc = restoreCursorPosition(pCsr);
56226 if( rc!=SQLITE_OK ){
56227 return rc;
56229 assert( pCsr->eState!=CURSOR_REQUIRESEEK );
56230 if( pCsr->eState!=CURSOR_VALID ){
56231 return SQLITE_ABORT;
56234 /* Check some assumptions:
56235 ** (a) the cursor is open for writing,
56236 ** (b) there is a read/write transaction open,
56237 ** (c) the connection holds a write-lock on the table (if required),
56238 ** (d) there are no conflicting read-locks, and
56239 ** (e) the cursor points at a valid row of an intKey table.
56241 if( !pCsr->wrFlag ){
56242 return SQLITE_READONLY;
56244 assert( !pCsr->pBt->readOnly && pCsr->pBt->inTransaction==TRANS_WRITE );
56245 assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
56246 assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
56247 assert( pCsr->apPage[pCsr->iPage]->intKey );
56249 return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
56253 ** Set a flag on this cursor to cache the locations of pages from the
56254 ** overflow list for the current row. This is used by cursors opened
56255 ** for incremental blob IO only.
56257 ** This function sets a flag only. The actual page location cache
56258 ** (stored in BtCursor.aOverflow[]) is allocated and used by function
56259 ** accessPayload() (the worker function for sqlite3BtreeData() and
56260 ** sqlite3BtreePutData()).
56262 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){
56263 assert( cursorHoldsMutex(pCur) );
56264 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
56265 invalidateOverflowCache(pCur);
56266 pCur->isIncrblobHandle = 1;
56268 #endif
56271 ** Set both the "read version" (single byte at byte offset 18) and
56272 ** "write version" (single byte at byte offset 19) fields in the database
56273 ** header to iVersion.
56275 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
56276 BtShared *pBt = pBtree->pBt;
56277 int rc; /* Return code */
56279 assert( iVersion==1 || iVersion==2 );
56281 /* If setting the version fields to 1, do not automatically open the
56282 ** WAL connection, even if the version fields are currently set to 2.
56284 pBt->doNotUseWAL = (u8)(iVersion==1);
56286 rc = sqlite3BtreeBeginTrans(pBtree, 0);
56287 if( rc==SQLITE_OK ){
56288 u8 *aData = pBt->pPage1->aData;
56289 if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
56290 rc = sqlite3BtreeBeginTrans(pBtree, 2);
56291 if( rc==SQLITE_OK ){
56292 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
56293 if( rc==SQLITE_OK ){
56294 aData[18] = (u8)iVersion;
56295 aData[19] = (u8)iVersion;
56301 pBt->doNotUseWAL = 0;
56302 return rc;
56305 /************** End of btree.c ***********************************************/
56306 /************** Begin file backup.c ******************************************/
56308 ** 2009 January 28
56310 ** The author disclaims copyright to this source code. In place of
56311 ** a legal notice, here is a blessing:
56313 ** May you do good and not evil.
56314 ** May you find forgiveness for yourself and forgive others.
56315 ** May you share freely, never taking more than you give.
56317 *************************************************************************
56318 ** This file contains the implementation of the sqlite3_backup_XXX()
56319 ** API functions and the related features.
56322 /* Macro to find the minimum of two numeric values.
56324 #ifndef MIN
56325 # define MIN(x,y) ((x)<(y)?(x):(y))
56326 #endif
56329 ** Structure allocated for each backup operation.
56331 struct sqlite3_backup {
56332 sqlite3* pDestDb; /* Destination database handle */
56333 Btree *pDest; /* Destination b-tree file */
56334 u32 iDestSchema; /* Original schema cookie in destination */
56335 int bDestLocked; /* True once a write-transaction is open on pDest */
56337 Pgno iNext; /* Page number of the next source page to copy */
56338 sqlite3* pSrcDb; /* Source database handle */
56339 Btree *pSrc; /* Source b-tree file */
56341 int rc; /* Backup process error code */
56343 /* These two variables are set by every call to backup_step(). They are
56344 ** read by calls to backup_remaining() and backup_pagecount().
56346 Pgno nRemaining; /* Number of pages left to copy */
56347 Pgno nPagecount; /* Total number of pages to copy */
56349 int isAttached; /* True once backup has been registered with pager */
56350 sqlite3_backup *pNext; /* Next backup associated with source pager */
56354 ** THREAD SAFETY NOTES:
56356 ** Once it has been created using backup_init(), a single sqlite3_backup
56357 ** structure may be accessed via two groups of thread-safe entry points:
56359 ** * Via the sqlite3_backup_XXX() API function backup_step() and
56360 ** backup_finish(). Both these functions obtain the source database
56361 ** handle mutex and the mutex associated with the source BtShared
56362 ** structure, in that order.
56364 ** * Via the BackupUpdate() and BackupRestart() functions, which are
56365 ** invoked by the pager layer to report various state changes in
56366 ** the page cache associated with the source database. The mutex
56367 ** associated with the source database BtShared structure will always
56368 ** be held when either of these functions are invoked.
56370 ** The other sqlite3_backup_XXX() API functions, backup_remaining() and
56371 ** backup_pagecount() are not thread-safe functions. If they are called
56372 ** while some other thread is calling backup_step() or backup_finish(),
56373 ** the values returned may be invalid. There is no way for a call to
56374 ** BackupUpdate() or BackupRestart() to interfere with backup_remaining()
56375 ** or backup_pagecount().
56377 ** Depending on the SQLite configuration, the database handles and/or
56378 ** the Btree objects may have their own mutexes that require locking.
56379 ** Non-sharable Btrees (in-memory databases for example), do not have
56380 ** associated mutexes.
56384 ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
56385 ** in connection handle pDb. If such a database cannot be found, return
56386 ** a NULL pointer and write an error message to pErrorDb.
56388 ** If the "temp" database is requested, it may need to be opened by this
56389 ** function. If an error occurs while doing so, return 0 and write an
56390 ** error message to pErrorDb.
56392 static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
56393 int i = sqlite3FindDbName(pDb, zDb);
56395 if( i==1 ){
56396 Parse *pParse;
56397 int rc = 0;
56398 pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
56399 if( pParse==0 ){
56400 sqlite3Error(pErrorDb, SQLITE_NOMEM, "out of memory");
56401 rc = SQLITE_NOMEM;
56402 }else{
56403 pParse->db = pDb;
56404 if( sqlite3OpenTempDatabase(pParse) ){
56405 sqlite3Error(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
56406 rc = SQLITE_ERROR;
56408 sqlite3DbFree(pErrorDb, pParse->zErrMsg);
56409 sqlite3StackFree(pErrorDb, pParse);
56411 if( rc ){
56412 return 0;
56416 if( i<0 ){
56417 sqlite3Error(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
56418 return 0;
56421 return pDb->aDb[i].pBt;
56425 ** Attempt to set the page size of the destination to match the page size
56426 ** of the source.
56428 static int setDestPgsz(sqlite3_backup *p){
56429 int rc;
56430 rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
56431 return rc;
56435 ** Create an sqlite3_backup process to copy the contents of zSrcDb from
56436 ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
56437 ** a pointer to the new sqlite3_backup object.
56439 ** If an error occurs, NULL is returned and an error code and error message
56440 ** stored in database handle pDestDb.
56442 SQLITE_API sqlite3_backup *sqlite3_backup_init(
56443 sqlite3* pDestDb, /* Database to write to */
56444 const char *zDestDb, /* Name of database within pDestDb */
56445 sqlite3* pSrcDb, /* Database connection to read from */
56446 const char *zSrcDb /* Name of database within pSrcDb */
56448 sqlite3_backup *p; /* Value to return */
56450 /* Lock the source database handle. The destination database
56451 ** handle is not locked in this routine, but it is locked in
56452 ** sqlite3_backup_step(). The user is required to ensure that no
56453 ** other thread accesses the destination handle for the duration
56454 ** of the backup operation. Any attempt to use the destination
56455 ** database connection while a backup is in progress may cause
56456 ** a malfunction or a deadlock.
56458 sqlite3_mutex_enter(pSrcDb->mutex);
56459 sqlite3_mutex_enter(pDestDb->mutex);
56461 if( pSrcDb==pDestDb ){
56462 sqlite3Error(
56463 pDestDb, SQLITE_ERROR, "source and destination must be distinct"
56465 p = 0;
56466 }else {
56467 /* Allocate space for a new sqlite3_backup object...
56468 ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
56469 ** call to sqlite3_backup_init() and is destroyed by a call to
56470 ** sqlite3_backup_finish(). */
56471 p = (sqlite3_backup *)sqlite3_malloc(sizeof(sqlite3_backup));
56472 if( !p ){
56473 sqlite3Error(pDestDb, SQLITE_NOMEM, 0);
56477 /* If the allocation succeeded, populate the new object. */
56478 if( p ){
56479 memset(p, 0, sizeof(sqlite3_backup));
56480 p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
56481 p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
56482 p->pDestDb = pDestDb;
56483 p->pSrcDb = pSrcDb;
56484 p->iNext = 1;
56485 p->isAttached = 0;
56487 if( 0==p->pSrc || 0==p->pDest || setDestPgsz(p)==SQLITE_NOMEM ){
56488 /* One (or both) of the named databases did not exist or an OOM
56489 ** error was hit. The error has already been written into the
56490 ** pDestDb handle. All that is left to do here is free the
56491 ** sqlite3_backup structure.
56493 sqlite3_free(p);
56494 p = 0;
56497 if( p ){
56498 p->pSrc->nBackup++;
56501 sqlite3_mutex_leave(pDestDb->mutex);
56502 sqlite3_mutex_leave(pSrcDb->mutex);
56503 return p;
56507 ** Argument rc is an SQLite error code. Return true if this error is
56508 ** considered fatal if encountered during a backup operation. All errors
56509 ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
56511 static int isFatalError(int rc){
56512 return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
56516 ** Parameter zSrcData points to a buffer containing the data for
56517 ** page iSrcPg from the source database. Copy this data into the
56518 ** destination database.
56520 static int backupOnePage(sqlite3_backup *p, Pgno iSrcPg, const u8 *zSrcData){
56521 Pager * const pDestPager = sqlite3BtreePager(p->pDest);
56522 const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
56523 int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
56524 const int nCopy = MIN(nSrcPgsz, nDestPgsz);
56525 const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
56526 #ifdef SQLITE_HAS_CODEC
56527 int nSrcReserve = sqlite3BtreeGetReserve(p->pSrc);
56528 int nDestReserve = sqlite3BtreeGetReserve(p->pDest);
56529 #endif
56531 int rc = SQLITE_OK;
56532 i64 iOff;
56534 assert( p->bDestLocked );
56535 assert( !isFatalError(p->rc) );
56536 assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
56537 assert( zSrcData );
56539 /* Catch the case where the destination is an in-memory database and the
56540 ** page sizes of the source and destination differ.
56542 if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
56543 rc = SQLITE_READONLY;
56546 #ifdef SQLITE_HAS_CODEC
56547 /* Backup is not possible if the page size of the destination is changing
56548 ** and a codec is in use.
56550 if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
56551 rc = SQLITE_READONLY;
56554 /* Backup is not possible if the number of bytes of reserve space differ
56555 ** between source and destination. If there is a difference, try to
56556 ** fix the destination to agree with the source. If that is not possible,
56557 ** then the backup cannot proceed.
56559 if( nSrcReserve!=nDestReserve ){
56560 u32 newPgsz = nSrcPgsz;
56561 rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
56562 if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
56564 #endif
56566 /* This loop runs once for each destination page spanned by the source
56567 ** page. For each iteration, variable iOff is set to the byte offset
56568 ** of the destination page.
56570 for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
56571 DbPage *pDestPg = 0;
56572 Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
56573 if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
56574 if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
56575 && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
56577 const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
56578 u8 *zDestData = sqlite3PagerGetData(pDestPg);
56579 u8 *zOut = &zDestData[iOff%nDestPgsz];
56581 /* Copy the data from the source page into the destination page.
56582 ** Then clear the Btree layer MemPage.isInit flag. Both this module
56583 ** and the pager code use this trick (clearing the first byte
56584 ** of the page 'extra' space to invalidate the Btree layers
56585 ** cached parse of the page). MemPage.isInit is marked
56586 ** "MUST BE FIRST" for this purpose.
56588 memcpy(zOut, zIn, nCopy);
56589 ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
56591 sqlite3PagerUnref(pDestPg);
56594 return rc;
56598 ** If pFile is currently larger than iSize bytes, then truncate it to
56599 ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
56600 ** this function is a no-op.
56602 ** Return SQLITE_OK if everything is successful, or an SQLite error
56603 ** code if an error occurs.
56605 static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
56606 i64 iCurrent;
56607 int rc = sqlite3OsFileSize(pFile, &iCurrent);
56608 if( rc==SQLITE_OK && iCurrent>iSize ){
56609 rc = sqlite3OsTruncate(pFile, iSize);
56611 return rc;
56615 ** Register this backup object with the associated source pager for
56616 ** callbacks when pages are changed or the cache invalidated.
56618 static void attachBackupObject(sqlite3_backup *p){
56619 sqlite3_backup **pp;
56620 assert( sqlite3BtreeHoldsMutex(p->pSrc) );
56621 pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
56622 p->pNext = *pp;
56623 *pp = p;
56624 p->isAttached = 1;
56628 ** Copy nPage pages from the source b-tree to the destination.
56630 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
56631 int rc;
56632 int destMode; /* Destination journal mode */
56633 int pgszSrc = 0; /* Source page size */
56634 int pgszDest = 0; /* Destination page size */
56636 sqlite3_mutex_enter(p->pSrcDb->mutex);
56637 sqlite3BtreeEnter(p->pSrc);
56638 if( p->pDestDb ){
56639 sqlite3_mutex_enter(p->pDestDb->mutex);
56642 rc = p->rc;
56643 if( !isFatalError(rc) ){
56644 Pager * const pSrcPager = sqlite3BtreePager(p->pSrc); /* Source pager */
56645 Pager * const pDestPager = sqlite3BtreePager(p->pDest); /* Dest pager */
56646 int ii; /* Iterator variable */
56647 int nSrcPage = -1; /* Size of source db in pages */
56648 int bCloseTrans = 0; /* True if src db requires unlocking */
56650 /* If the source pager is currently in a write-transaction, return
56651 ** SQLITE_BUSY immediately.
56653 if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
56654 rc = SQLITE_BUSY;
56655 }else{
56656 rc = SQLITE_OK;
56659 /* Lock the destination database, if it is not locked already. */
56660 if( SQLITE_OK==rc && p->bDestLocked==0
56661 && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
56663 p->bDestLocked = 1;
56664 sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
56667 /* If there is no open read-transaction on the source database, open
56668 ** one now. If a transaction is opened here, then it will be closed
56669 ** before this function exits.
56671 if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
56672 rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
56673 bCloseTrans = 1;
56676 /* Do not allow backup if the destination database is in WAL mode
56677 ** and the page sizes are different between source and destination */
56678 pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
56679 pgszDest = sqlite3BtreeGetPageSize(p->pDest);
56680 destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
56681 if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
56682 rc = SQLITE_READONLY;
56685 /* Now that there is a read-lock on the source database, query the
56686 ** source pager for the number of pages in the database.
56688 nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
56689 assert( nSrcPage>=0 );
56690 for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
56691 const Pgno iSrcPg = p->iNext; /* Source page number */
56692 if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
56693 DbPage *pSrcPg; /* Source page object */
56694 rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
56695 if( rc==SQLITE_OK ){
56696 rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg));
56697 sqlite3PagerUnref(pSrcPg);
56700 p->iNext++;
56702 if( rc==SQLITE_OK ){
56703 p->nPagecount = nSrcPage;
56704 p->nRemaining = nSrcPage+1-p->iNext;
56705 if( p->iNext>(Pgno)nSrcPage ){
56706 rc = SQLITE_DONE;
56707 }else if( !p->isAttached ){
56708 attachBackupObject(p);
56712 /* Update the schema version field in the destination database. This
56713 ** is to make sure that the schema-version really does change in
56714 ** the case where the source and destination databases have the
56715 ** same schema version.
56717 if( rc==SQLITE_DONE ){
56718 rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
56719 if( rc==SQLITE_OK ){
56720 if( p->pDestDb ){
56721 sqlite3ResetInternalSchema(p->pDestDb, -1);
56723 if( destMode==PAGER_JOURNALMODE_WAL ){
56724 rc = sqlite3BtreeSetVersion(p->pDest, 2);
56727 if( rc==SQLITE_OK ){
56728 int nDestTruncate;
56729 /* Set nDestTruncate to the final number of pages in the destination
56730 ** database. The complication here is that the destination page
56731 ** size may be different to the source page size.
56733 ** If the source page size is smaller than the destination page size,
56734 ** round up. In this case the call to sqlite3OsTruncate() below will
56735 ** fix the size of the file. However it is important to call
56736 ** sqlite3PagerTruncateImage() here so that any pages in the
56737 ** destination file that lie beyond the nDestTruncate page mark are
56738 ** journalled by PagerCommitPhaseOne() before they are destroyed
56739 ** by the file truncation.
56741 assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
56742 assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
56743 if( pgszSrc<pgszDest ){
56744 int ratio = pgszDest/pgszSrc;
56745 nDestTruncate = (nSrcPage+ratio-1)/ratio;
56746 if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
56747 nDestTruncate--;
56749 }else{
56750 nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
56752 sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
56754 if( pgszSrc<pgszDest ){
56755 /* If the source page-size is smaller than the destination page-size,
56756 ** two extra things may need to happen:
56758 ** * The destination may need to be truncated, and
56760 ** * Data stored on the pages immediately following the
56761 ** pending-byte page in the source database may need to be
56762 ** copied into the destination database.
56764 const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
56765 sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
56766 i64 iOff;
56767 i64 iEnd;
56769 assert( pFile );
56770 assert( (i64)nDestTruncate*(i64)pgszDest >= iSize || (
56771 nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
56772 && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
56775 /* This call ensures that all data required to recreate the original
56776 ** database has been stored in the journal for pDestPager and the
56777 ** journal synced to disk. So at this point we may safely modify
56778 ** the database file in any way, knowing that if a power failure
56779 ** occurs, the original database will be reconstructed from the
56780 ** journal file. */
56781 rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
56783 /* Write the extra pages and truncate the database file as required */
56784 iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
56785 for(
56786 iOff=PENDING_BYTE+pgszSrc;
56787 rc==SQLITE_OK && iOff<iEnd;
56788 iOff+=pgszSrc
56790 PgHdr *pSrcPg = 0;
56791 const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
56792 rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
56793 if( rc==SQLITE_OK ){
56794 u8 *zData = sqlite3PagerGetData(pSrcPg);
56795 rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
56797 sqlite3PagerUnref(pSrcPg);
56799 if( rc==SQLITE_OK ){
56800 rc = backupTruncateFile(pFile, iSize);
56803 /* Sync the database file to disk. */
56804 if( rc==SQLITE_OK ){
56805 rc = sqlite3PagerSync(pDestPager);
56807 }else{
56808 rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
56811 /* Finish committing the transaction to the destination database. */
56812 if( SQLITE_OK==rc
56813 && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
56815 rc = SQLITE_DONE;
56820 /* If bCloseTrans is true, then this function opened a read transaction
56821 ** on the source database. Close the read transaction here. There is
56822 ** no need to check the return values of the btree methods here, as
56823 ** "committing" a read-only transaction cannot fail.
56825 if( bCloseTrans ){
56826 TESTONLY( int rc2 );
56827 TESTONLY( rc2 = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
56828 TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
56829 assert( rc2==SQLITE_OK );
56832 if( rc==SQLITE_IOERR_NOMEM ){
56833 rc = SQLITE_NOMEM;
56835 p->rc = rc;
56837 if( p->pDestDb ){
56838 sqlite3_mutex_leave(p->pDestDb->mutex);
56840 sqlite3BtreeLeave(p->pSrc);
56841 sqlite3_mutex_leave(p->pSrcDb->mutex);
56842 return rc;
56846 ** Release all resources associated with an sqlite3_backup* handle.
56848 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
56849 sqlite3_backup **pp; /* Ptr to head of pagers backup list */
56850 MUTEX_LOGIC( sqlite3_mutex *mutex; ) /* Mutex to protect source database */
56851 int rc; /* Value to return */
56853 /* Enter the mutexes */
56854 if( p==0 ) return SQLITE_OK;
56855 sqlite3_mutex_enter(p->pSrcDb->mutex);
56856 sqlite3BtreeEnter(p->pSrc);
56857 MUTEX_LOGIC( mutex = p->pSrcDb->mutex; )
56858 if( p->pDestDb ){
56859 sqlite3_mutex_enter(p->pDestDb->mutex);
56862 /* Detach this backup from the source pager. */
56863 if( p->pDestDb ){
56864 p->pSrc->nBackup--;
56866 if( p->isAttached ){
56867 pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
56868 while( *pp!=p ){
56869 pp = &(*pp)->pNext;
56871 *pp = p->pNext;
56874 /* If a transaction is still open on the Btree, roll it back. */
56875 sqlite3BtreeRollback(p->pDest);
56877 /* Set the error code of the destination database handle. */
56878 rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
56879 sqlite3Error(p->pDestDb, rc, 0);
56881 /* Exit the mutexes and free the backup context structure. */
56882 if( p->pDestDb ){
56883 sqlite3_mutex_leave(p->pDestDb->mutex);
56885 sqlite3BtreeLeave(p->pSrc);
56886 if( p->pDestDb ){
56887 /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
56888 ** call to sqlite3_backup_init() and is destroyed by a call to
56889 ** sqlite3_backup_finish(). */
56890 sqlite3_free(p);
56892 sqlite3_mutex_leave(mutex);
56893 return rc;
56897 ** Return the number of pages still to be backed up as of the most recent
56898 ** call to sqlite3_backup_step().
56900 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
56901 return p->nRemaining;
56905 ** Return the total number of pages in the source database as of the most
56906 ** recent call to sqlite3_backup_step().
56908 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
56909 return p->nPagecount;
56913 ** This function is called after the contents of page iPage of the
56914 ** source database have been modified. If page iPage has already been
56915 ** copied into the destination database, then the data written to the
56916 ** destination is now invalidated. The destination copy of iPage needs
56917 ** to be updated with the new data before the backup operation is
56918 ** complete.
56920 ** It is assumed that the mutex associated with the BtShared object
56921 ** corresponding to the source database is held when this function is
56922 ** called.
56924 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
56925 sqlite3_backup *p; /* Iterator variable */
56926 for(p=pBackup; p; p=p->pNext){
56927 assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
56928 if( !isFatalError(p->rc) && iPage<p->iNext ){
56929 /* The backup process p has already copied page iPage. But now it
56930 ** has been modified by a transaction on the source pager. Copy
56931 ** the new data into the backup.
56933 int rc;
56934 assert( p->pDestDb );
56935 sqlite3_mutex_enter(p->pDestDb->mutex);
56936 rc = backupOnePage(p, iPage, aData);
56937 sqlite3_mutex_leave(p->pDestDb->mutex);
56938 assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
56939 if( rc!=SQLITE_OK ){
56940 p->rc = rc;
56947 ** Restart the backup process. This is called when the pager layer
56948 ** detects that the database has been modified by an external database
56949 ** connection. In this case there is no way of knowing which of the
56950 ** pages that have been copied into the destination database are still
56951 ** valid and which are not, so the entire process needs to be restarted.
56953 ** It is assumed that the mutex associated with the BtShared object
56954 ** corresponding to the source database is held when this function is
56955 ** called.
56957 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
56958 sqlite3_backup *p; /* Iterator variable */
56959 for(p=pBackup; p; p=p->pNext){
56960 assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
56961 p->iNext = 1;
56965 #ifndef SQLITE_OMIT_VACUUM
56967 ** Copy the complete content of pBtFrom into pBtTo. A transaction
56968 ** must be active for both files.
56970 ** The size of file pTo may be reduced by this operation. If anything
56971 ** goes wrong, the transaction on pTo is rolled back. If successful, the
56972 ** transaction is committed before returning.
56974 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
56975 int rc;
56976 sqlite3_file *pFd; /* File descriptor for database pTo */
56977 sqlite3_backup b;
56978 sqlite3BtreeEnter(pTo);
56979 sqlite3BtreeEnter(pFrom);
56981 assert( sqlite3BtreeIsInTrans(pTo) );
56982 pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
56983 if( pFd->pMethods ){
56984 i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
56985 sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
56988 /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
56989 ** to 0. This is used by the implementations of sqlite3_backup_step()
56990 ** and sqlite3_backup_finish() to detect that they are being called
56991 ** from this function, not directly by the user.
56993 memset(&b, 0, sizeof(b));
56994 b.pSrcDb = pFrom->db;
56995 b.pSrc = pFrom;
56996 b.pDest = pTo;
56997 b.iNext = 1;
56999 /* 0x7FFFFFFF is the hard limit for the number of pages in a database
57000 ** file. By passing this as the number of pages to copy to
57001 ** sqlite3_backup_step(), we can guarantee that the copy finishes
57002 ** within a single call (unless an error occurs). The assert() statement
57003 ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
57004 ** or an error code.
57006 sqlite3_backup_step(&b, 0x7FFFFFFF);
57007 assert( b.rc!=SQLITE_OK );
57008 rc = sqlite3_backup_finish(&b);
57009 if( rc==SQLITE_OK ){
57010 pTo->pBt->pageSizeFixed = 0;
57011 }else{
57012 sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
57015 assert( sqlite3BtreeIsInTrans(pTo)==0 );
57016 sqlite3BtreeLeave(pFrom);
57017 sqlite3BtreeLeave(pTo);
57018 return rc;
57020 #endif /* SQLITE_OMIT_VACUUM */
57022 /************** End of backup.c **********************************************/
57023 /************** Begin file vdbemem.c *****************************************/
57025 ** 2004 May 26
57027 ** The author disclaims copyright to this source code. In place of
57028 ** a legal notice, here is a blessing:
57030 ** May you do good and not evil.
57031 ** May you find forgiveness for yourself and forgive others.
57032 ** May you share freely, never taking more than you give.
57034 *************************************************************************
57036 ** This file contains code use to manipulate "Mem" structure. A "Mem"
57037 ** stores a single value in the VDBE. Mem is an opaque structure visible
57038 ** only within the VDBE. Interface routines refer to a Mem using the
57039 ** name sqlite_value
57043 ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
57044 ** P if required.
57046 #define expandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
57049 ** If pMem is an object with a valid string representation, this routine
57050 ** ensures the internal encoding for the string representation is
57051 ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
57053 ** If pMem is not a string object, or the encoding of the string
57054 ** representation is already stored using the requested encoding, then this
57055 ** routine is a no-op.
57057 ** SQLITE_OK is returned if the conversion is successful (or not required).
57058 ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
57059 ** between formats.
57061 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
57062 int rc;
57063 assert( (pMem->flags&MEM_RowSet)==0 );
57064 assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
57065 || desiredEnc==SQLITE_UTF16BE );
57066 if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
57067 return SQLITE_OK;
57069 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57070 #ifdef SQLITE_OMIT_UTF16
57071 return SQLITE_ERROR;
57072 #else
57074 /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
57075 ** then the encoding of the value may not have changed.
57077 rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
57078 assert(rc==SQLITE_OK || rc==SQLITE_NOMEM);
57079 assert(rc==SQLITE_OK || pMem->enc!=desiredEnc);
57080 assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
57081 return rc;
57082 #endif
57086 ** Make sure pMem->z points to a writable allocation of at least
57087 ** n bytes.
57089 ** If the memory cell currently contains string or blob data
57090 ** and the third argument passed to this function is true, the
57091 ** current content of the cell is preserved. Otherwise, it may
57092 ** be discarded.
57094 ** This function sets the MEM_Dyn flag and clears any xDel callback.
57095 ** It also clears MEM_Ephem and MEM_Static. If the preserve flag is
57096 ** not set, Mem.n is zeroed.
57098 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve){
57099 assert( 1 >=
57100 ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +
57101 (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) +
57102 ((pMem->flags&MEM_Ephem) ? 1 : 0) +
57103 ((pMem->flags&MEM_Static) ? 1 : 0)
57105 assert( (pMem->flags&MEM_RowSet)==0 );
57107 if( n<32 ) n = 32;
57108 if( sqlite3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
57109 if( preserve && pMem->z==pMem->zMalloc ){
57110 pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
57111 preserve = 0;
57112 }else{
57113 sqlite3DbFree(pMem->db, pMem->zMalloc);
57114 pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
57118 if( pMem->z && preserve && pMem->zMalloc && pMem->z!=pMem->zMalloc ){
57119 memcpy(pMem->zMalloc, pMem->z, pMem->n);
57121 if( pMem->flags&MEM_Dyn && pMem->xDel ){
57122 pMem->xDel((void *)(pMem->z));
57125 pMem->z = pMem->zMalloc;
57126 if( pMem->z==0 ){
57127 pMem->flags = MEM_Null;
57128 }else{
57129 pMem->flags &= ~(MEM_Ephem|MEM_Static);
57131 pMem->xDel = 0;
57132 return (pMem->z ? SQLITE_OK : SQLITE_NOMEM);
57136 ** Make the given Mem object MEM_Dyn. In other words, make it so
57137 ** that any TEXT or BLOB content is stored in memory obtained from
57138 ** malloc(). In this way, we know that the memory is safe to be
57139 ** overwritten or altered.
57141 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
57143 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
57144 int f;
57145 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57146 assert( (pMem->flags&MEM_RowSet)==0 );
57147 expandBlob(pMem);
57148 f = pMem->flags;
57149 if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
57150 if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
57151 return SQLITE_NOMEM;
57153 pMem->z[pMem->n] = 0;
57154 pMem->z[pMem->n+1] = 0;
57155 pMem->flags |= MEM_Term;
57156 #ifdef SQLITE_DEBUG
57157 pMem->pScopyFrom = 0;
57158 #endif
57161 return SQLITE_OK;
57165 ** If the given Mem* has a zero-filled tail, turn it into an ordinary
57166 ** blob stored in dynamically allocated space.
57168 #ifndef SQLITE_OMIT_INCRBLOB
57169 SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
57170 if( pMem->flags & MEM_Zero ){
57171 int nByte;
57172 assert( pMem->flags&MEM_Blob );
57173 assert( (pMem->flags&MEM_RowSet)==0 );
57174 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57176 /* Set nByte to the number of bytes required to store the expanded blob. */
57177 nByte = pMem->n + pMem->u.nZero;
57178 if( nByte<=0 ){
57179 nByte = 1;
57181 if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
57182 return SQLITE_NOMEM;
57185 memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
57186 pMem->n += pMem->u.nZero;
57187 pMem->flags &= ~(MEM_Zero|MEM_Term);
57189 return SQLITE_OK;
57191 #endif
57195 ** Make sure the given Mem is \u0000 terminated.
57197 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
57198 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57199 if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
57200 return SQLITE_OK; /* Nothing to do */
57202 if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
57203 return SQLITE_NOMEM;
57205 pMem->z[pMem->n] = 0;
57206 pMem->z[pMem->n+1] = 0;
57207 pMem->flags |= MEM_Term;
57208 return SQLITE_OK;
57212 ** Add MEM_Str to the set of representations for the given Mem. Numbers
57213 ** are converted using sqlite3_snprintf(). Converting a BLOB to a string
57214 ** is a no-op.
57216 ** Existing representations MEM_Int and MEM_Real are *not* invalidated.
57218 ** A MEM_Null value will never be passed to this function. This function is
57219 ** used for converting values to text for returning to the user (i.e. via
57220 ** sqlite3_value_text()), or for ensuring that values to be used as btree
57221 ** keys are strings. In the former case a NULL pointer is returned the
57222 ** user and the later is an internal programming error.
57224 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
57225 int rc = SQLITE_OK;
57226 int fg = pMem->flags;
57227 const int nByte = 32;
57229 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57230 assert( !(fg&MEM_Zero) );
57231 assert( !(fg&(MEM_Str|MEM_Blob)) );
57232 assert( fg&(MEM_Int|MEM_Real) );
57233 assert( (pMem->flags&MEM_RowSet)==0 );
57234 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
57237 if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
57238 return SQLITE_NOMEM;
57241 /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
57242 ** string representation of the value. Then, if the required encoding
57243 ** is UTF-16le or UTF-16be do a translation.
57245 ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
57247 if( fg & MEM_Int ){
57248 sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
57249 }else{
57250 assert( fg & MEM_Real );
57251 sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
57253 pMem->n = sqlite3Strlen30(pMem->z);
57254 pMem->enc = SQLITE_UTF8;
57255 pMem->flags |= MEM_Str|MEM_Term;
57256 sqlite3VdbeChangeEncoding(pMem, enc);
57257 return rc;
57261 ** Memory cell pMem contains the context of an aggregate function.
57262 ** This routine calls the finalize method for that function. The
57263 ** result of the aggregate is stored back into pMem.
57265 ** Return SQLITE_ERROR if the finalizer reports an error. SQLITE_OK
57266 ** otherwise.
57268 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
57269 int rc = SQLITE_OK;
57270 if( ALWAYS(pFunc && pFunc->xFinalize) ){
57271 sqlite3_context ctx;
57272 assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
57273 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57274 memset(&ctx, 0, sizeof(ctx));
57275 ctx.s.flags = MEM_Null;
57276 ctx.s.db = pMem->db;
57277 ctx.pMem = pMem;
57278 ctx.pFunc = pFunc;
57279 pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
57280 assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
57281 sqlite3DbFree(pMem->db, pMem->zMalloc);
57282 memcpy(pMem, &ctx.s, sizeof(ctx.s));
57283 rc = ctx.isError;
57285 return rc;
57289 ** If the memory cell contains a string value that must be freed by
57290 ** invoking an external callback, free it now. Calling this function
57291 ** does not free any Mem.zMalloc buffer.
57293 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
57294 assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
57295 if( p->flags&MEM_Agg ){
57296 sqlite3VdbeMemFinalize(p, p->u.pDef);
57297 assert( (p->flags & MEM_Agg)==0 );
57298 sqlite3VdbeMemRelease(p);
57299 }else if( p->flags&MEM_Dyn && p->xDel ){
57300 assert( (p->flags&MEM_RowSet)==0 );
57301 p->xDel((void *)p->z);
57302 p->xDel = 0;
57303 }else if( p->flags&MEM_RowSet ){
57304 sqlite3RowSetClear(p->u.pRowSet);
57305 }else if( p->flags&MEM_Frame ){
57306 sqlite3VdbeMemSetNull(p);
57311 ** Release any memory held by the Mem. This may leave the Mem in an
57312 ** inconsistent state, for example with (Mem.z==0) and
57313 ** (Mem.type==SQLITE_TEXT).
57315 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
57316 MemReleaseExt(p);
57317 sqlite3DbFree(p->db, p->zMalloc);
57318 p->z = 0;
57319 p->zMalloc = 0;
57320 p->xDel = 0;
57324 ** Convert a 64-bit IEEE double into a 64-bit signed integer.
57325 ** If the double is too large, return 0x8000000000000000.
57327 ** Most systems appear to do this simply by assigning
57328 ** variables and without the extra range tests. But
57329 ** there are reports that windows throws an expection
57330 ** if the floating point value is out of range. (See ticket #2880.)
57331 ** Because we do not completely understand the problem, we will
57332 ** take the conservative approach and always do range tests
57333 ** before attempting the conversion.
57335 static i64 doubleToInt64(double r){
57336 #ifdef SQLITE_OMIT_FLOATING_POINT
57337 /* When floating-point is omitted, double and int64 are the same thing */
57338 return r;
57339 #else
57341 ** Many compilers we encounter do not define constants for the
57342 ** minimum and maximum 64-bit integers, or they define them
57343 ** inconsistently. And many do not understand the "LL" notation.
57344 ** So we define our own static constants here using nothing
57345 ** larger than a 32-bit integer constant.
57347 static const i64 maxInt = LARGEST_INT64;
57348 static const i64 minInt = SMALLEST_INT64;
57350 if( r<(double)minInt ){
57351 return minInt;
57352 }else if( r>(double)maxInt ){
57353 /* minInt is correct here - not maxInt. It turns out that assigning
57354 ** a very large positive number to an integer results in a very large
57355 ** negative integer. This makes no sense, but it is what x86 hardware
57356 ** does so for compatibility we will do the same in software. */
57357 return minInt;
57358 }else{
57359 return (i64)r;
57361 #endif
57365 ** Return some kind of integer value which is the best we can do
57366 ** at representing the value that *pMem describes as an integer.
57367 ** If pMem is an integer, then the value is exact. If pMem is
57368 ** a floating-point then the value returned is the integer part.
57369 ** If pMem is a string or blob, then we make an attempt to convert
57370 ** it into a integer and return that. If pMem represents an
57371 ** an SQL-NULL value, return 0.
57373 ** If pMem represents a string value, its encoding might be changed.
57375 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
57376 int flags;
57377 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57378 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
57379 flags = pMem->flags;
57380 if( flags & MEM_Int ){
57381 return pMem->u.i;
57382 }else if( flags & MEM_Real ){
57383 return doubleToInt64(pMem->r);
57384 }else if( flags & (MEM_Str|MEM_Blob) ){
57385 i64 value = 0;
57386 assert( pMem->z || pMem->n==0 );
57387 testcase( pMem->z==0 );
57388 sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
57389 return value;
57390 }else{
57391 return 0;
57396 ** Return the best representation of pMem that we can get into a
57397 ** double. If pMem is already a double or an integer, return its
57398 ** value. If it is a string or blob, try to convert it to a double.
57399 ** If it is a NULL, return 0.0.
57401 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
57402 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57403 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
57404 if( pMem->flags & MEM_Real ){
57405 return pMem->r;
57406 }else if( pMem->flags & MEM_Int ){
57407 return (double)pMem->u.i;
57408 }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
57409 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
57410 double val = (double)0;
57411 sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
57412 return val;
57413 }else{
57414 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
57415 return (double)0;
57420 ** The MEM structure is already a MEM_Real. Try to also make it a
57421 ** MEM_Int if we can.
57423 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
57424 assert( pMem->flags & MEM_Real );
57425 assert( (pMem->flags & MEM_RowSet)==0 );
57426 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57427 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
57429 pMem->u.i = doubleToInt64(pMem->r);
57431 /* Only mark the value as an integer if
57433 ** (1) the round-trip conversion real->int->real is a no-op, and
57434 ** (2) The integer is neither the largest nor the smallest
57435 ** possible integer (ticket #3922)
57437 ** The second and third terms in the following conditional enforces
57438 ** the second condition under the assumption that addition overflow causes
57439 ** values to wrap around. On x86 hardware, the third term is always
57440 ** true and could be omitted. But we leave it in because other
57441 ** architectures might behave differently.
57443 if( pMem->r==(double)pMem->u.i && pMem->u.i>SMALLEST_INT64
57444 && ALWAYS(pMem->u.i<LARGEST_INT64) ){
57445 pMem->flags |= MEM_Int;
57450 ** Convert pMem to type integer. Invalidate any prior representations.
57452 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
57453 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57454 assert( (pMem->flags & MEM_RowSet)==0 );
57455 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
57457 pMem->u.i = sqlite3VdbeIntValue(pMem);
57458 MemSetTypeFlag(pMem, MEM_Int);
57459 return SQLITE_OK;
57463 ** Convert pMem so that it is of type MEM_Real.
57464 ** Invalidate any prior representations.
57466 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
57467 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57468 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
57470 pMem->r = sqlite3VdbeRealValue(pMem);
57471 MemSetTypeFlag(pMem, MEM_Real);
57472 return SQLITE_OK;
57476 ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
57477 ** Invalidate any prior representations.
57479 ** Every effort is made to force the conversion, even if the input
57480 ** is a string that does not look completely like a number. Convert
57481 ** as much of the string as we can and ignore the rest.
57483 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
57484 if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
57485 assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
57486 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57487 if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
57488 MemSetTypeFlag(pMem, MEM_Int);
57489 }else{
57490 pMem->r = sqlite3VdbeRealValue(pMem);
57491 MemSetTypeFlag(pMem, MEM_Real);
57492 sqlite3VdbeIntegerAffinity(pMem);
57495 assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
57496 pMem->flags &= ~(MEM_Str|MEM_Blob);
57497 return SQLITE_OK;
57501 ** Delete any previous value and set the value stored in *pMem to NULL.
57503 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
57504 if( pMem->flags & MEM_Frame ){
57505 VdbeFrame *pFrame = pMem->u.pFrame;
57506 pFrame->pParent = pFrame->v->pDelFrame;
57507 pFrame->v->pDelFrame = pFrame;
57509 if( pMem->flags & MEM_RowSet ){
57510 sqlite3RowSetClear(pMem->u.pRowSet);
57512 MemSetTypeFlag(pMem, MEM_Null);
57513 pMem->type = SQLITE_NULL;
57517 ** Delete any previous value and set the value to be a BLOB of length
57518 ** n containing all zeros.
57520 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
57521 sqlite3VdbeMemRelease(pMem);
57522 pMem->flags = MEM_Blob|MEM_Zero;
57523 pMem->type = SQLITE_BLOB;
57524 pMem->n = 0;
57525 if( n<0 ) n = 0;
57526 pMem->u.nZero = n;
57527 pMem->enc = SQLITE_UTF8;
57529 #ifdef SQLITE_OMIT_INCRBLOB
57530 sqlite3VdbeMemGrow(pMem, n, 0);
57531 if( pMem->z ){
57532 pMem->n = n;
57533 memset(pMem->z, 0, n);
57535 #endif
57539 ** Delete any previous value and set the value stored in *pMem to val,
57540 ** manifest type INTEGER.
57542 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
57543 sqlite3VdbeMemRelease(pMem);
57544 pMem->u.i = val;
57545 pMem->flags = MEM_Int;
57546 pMem->type = SQLITE_INTEGER;
57549 #ifndef SQLITE_OMIT_FLOATING_POINT
57551 ** Delete any previous value and set the value stored in *pMem to val,
57552 ** manifest type REAL.
57554 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
57555 if( sqlite3IsNaN(val) ){
57556 sqlite3VdbeMemSetNull(pMem);
57557 }else{
57558 sqlite3VdbeMemRelease(pMem);
57559 pMem->r = val;
57560 pMem->flags = MEM_Real;
57561 pMem->type = SQLITE_FLOAT;
57564 #endif
57567 ** Delete any previous value and set the value of pMem to be an
57568 ** empty boolean index.
57570 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
57571 sqlite3 *db = pMem->db;
57572 assert( db!=0 );
57573 assert( (pMem->flags & MEM_RowSet)==0 );
57574 sqlite3VdbeMemRelease(pMem);
57575 pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
57576 if( db->mallocFailed ){
57577 pMem->flags = MEM_Null;
57578 }else{
57579 assert( pMem->zMalloc );
57580 pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc,
57581 sqlite3DbMallocSize(db, pMem->zMalloc));
57582 assert( pMem->u.pRowSet!=0 );
57583 pMem->flags = MEM_RowSet;
57588 ** Return true if the Mem object contains a TEXT or BLOB that is
57589 ** too large - whose size exceeds SQLITE_MAX_LENGTH.
57591 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
57592 assert( p->db!=0 );
57593 if( p->flags & (MEM_Str|MEM_Blob) ){
57594 int n = p->n;
57595 if( p->flags & MEM_Zero ){
57596 n += p->u.nZero;
57598 return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
57600 return 0;
57603 #ifdef SQLITE_DEBUG
57605 ** This routine prepares a memory cell for modication by breaking
57606 ** its link to a shallow copy and by marking any current shallow
57607 ** copies of this cell as invalid.
57609 ** This is used for testing and debugging only - to make sure shallow
57610 ** copies are not misused.
57612 SQLITE_PRIVATE void sqlite3VdbeMemPrepareToChange(Vdbe *pVdbe, Mem *pMem){
57613 int i;
57614 Mem *pX;
57615 for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){
57616 if( pX->pScopyFrom==pMem ){
57617 pX->flags |= MEM_Invalid;
57618 pX->pScopyFrom = 0;
57621 pMem->pScopyFrom = 0;
57623 #endif /* SQLITE_DEBUG */
57626 ** Size of struct Mem not including the Mem.zMalloc member.
57628 #define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))
57631 ** Make an shallow copy of pFrom into pTo. Prior contents of
57632 ** pTo are freed. The pFrom->z field is not duplicated. If
57633 ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
57634 ** and flags gets srcType (either MEM_Ephem or MEM_Static).
57636 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
57637 assert( (pFrom->flags & MEM_RowSet)==0 );
57638 MemReleaseExt(pTo);
57639 memcpy(pTo, pFrom, MEMCELLSIZE);
57640 pTo->xDel = 0;
57641 if( (pFrom->flags&MEM_Static)==0 ){
57642 pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
57643 assert( srcType==MEM_Ephem || srcType==MEM_Static );
57644 pTo->flags |= srcType;
57649 ** Make a full copy of pFrom into pTo. Prior contents of pTo are
57650 ** freed before the copy is made.
57652 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
57653 int rc = SQLITE_OK;
57655 assert( (pFrom->flags & MEM_RowSet)==0 );
57656 MemReleaseExt(pTo);
57657 memcpy(pTo, pFrom, MEMCELLSIZE);
57658 pTo->flags &= ~MEM_Dyn;
57660 if( pTo->flags&(MEM_Str|MEM_Blob) ){
57661 if( 0==(pFrom->flags&MEM_Static) ){
57662 pTo->flags |= MEM_Ephem;
57663 rc = sqlite3VdbeMemMakeWriteable(pTo);
57667 return rc;
57671 ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
57672 ** freed. If pFrom contains ephemeral data, a copy is made.
57674 ** pFrom contains an SQL NULL when this routine returns.
57676 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
57677 assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
57678 assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
57679 assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
57681 sqlite3VdbeMemRelease(pTo);
57682 memcpy(pTo, pFrom, sizeof(Mem));
57683 pFrom->flags = MEM_Null;
57684 pFrom->xDel = 0;
57685 pFrom->zMalloc = 0;
57689 ** Change the value of a Mem to be a string or a BLOB.
57691 ** The memory management strategy depends on the value of the xDel
57692 ** parameter. If the value passed is SQLITE_TRANSIENT, then the
57693 ** string is copied into a (possibly existing) buffer managed by the
57694 ** Mem structure. Otherwise, any existing buffer is freed and the
57695 ** pointer copied.
57697 ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
57698 ** size limit) then no memory allocation occurs. If the string can be
57699 ** stored without allocating memory, then it is. If a memory allocation
57700 ** is required to store the string, then value of pMem is unchanged. In
57701 ** either case, SQLITE_TOOBIG is returned.
57703 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
57704 Mem *pMem, /* Memory cell to set to string value */
57705 const char *z, /* String pointer */
57706 int n, /* Bytes in string, or negative */
57707 u8 enc, /* Encoding of z. 0 for BLOBs */
57708 void (*xDel)(void*) /* Destructor function */
57710 int nByte = n; /* New value for pMem->n */
57711 int iLimit; /* Maximum allowed string or blob size */
57712 u16 flags = 0; /* New value for pMem->flags */
57714 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57715 assert( (pMem->flags & MEM_RowSet)==0 );
57717 /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
57718 if( !z ){
57719 sqlite3VdbeMemSetNull(pMem);
57720 return SQLITE_OK;
57723 if( pMem->db ){
57724 iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
57725 }else{
57726 iLimit = SQLITE_MAX_LENGTH;
57728 flags = (enc==0?MEM_Blob:MEM_Str);
57729 if( nByte<0 ){
57730 assert( enc!=0 );
57731 if( enc==SQLITE_UTF8 ){
57732 for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
57733 }else{
57734 for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
57736 flags |= MEM_Term;
57739 /* The following block sets the new values of Mem.z and Mem.xDel. It
57740 ** also sets a flag in local variable "flags" to indicate the memory
57741 ** management (one of MEM_Dyn or MEM_Static).
57743 if( xDel==SQLITE_TRANSIENT ){
57744 int nAlloc = nByte;
57745 if( flags&MEM_Term ){
57746 nAlloc += (enc==SQLITE_UTF8?1:2);
57748 if( nByte>iLimit ){
57749 return SQLITE_TOOBIG;
57751 if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
57752 return SQLITE_NOMEM;
57754 memcpy(pMem->z, z, nAlloc);
57755 }else if( xDel==SQLITE_DYNAMIC ){
57756 sqlite3VdbeMemRelease(pMem);
57757 pMem->zMalloc = pMem->z = (char *)z;
57758 pMem->xDel = 0;
57759 }else{
57760 sqlite3VdbeMemRelease(pMem);
57761 pMem->z = (char *)z;
57762 pMem->xDel = xDel;
57763 flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
57766 pMem->n = nByte;
57767 pMem->flags = flags;
57768 pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
57769 pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT);
57771 #ifndef SQLITE_OMIT_UTF16
57772 if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
57773 return SQLITE_NOMEM;
57775 #endif
57777 if( nByte>iLimit ){
57778 return SQLITE_TOOBIG;
57781 return SQLITE_OK;
57785 ** Compare the values contained by the two memory cells, returning
57786 ** negative, zero or positive if pMem1 is less than, equal to, or greater
57787 ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
57788 ** and reals) sorted numerically, followed by text ordered by the collating
57789 ** sequence pColl and finally blob's ordered by memcmp().
57791 ** Two NULL values are considered equal by this function.
57793 SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
57794 int rc;
57795 int f1, f2;
57796 int combined_flags;
57798 f1 = pMem1->flags;
57799 f2 = pMem2->flags;
57800 combined_flags = f1|f2;
57801 assert( (combined_flags & MEM_RowSet)==0 );
57803 /* If one value is NULL, it is less than the other. If both values
57804 ** are NULL, return 0.
57806 if( combined_flags&MEM_Null ){
57807 return (f2&MEM_Null) - (f1&MEM_Null);
57810 /* If one value is a number and the other is not, the number is less.
57811 ** If both are numbers, compare as reals if one is a real, or as integers
57812 ** if both values are integers.
57814 if( combined_flags&(MEM_Int|MEM_Real) ){
57815 if( !(f1&(MEM_Int|MEM_Real)) ){
57816 return 1;
57818 if( !(f2&(MEM_Int|MEM_Real)) ){
57819 return -1;
57821 if( (f1 & f2 & MEM_Int)==0 ){
57822 double r1, r2;
57823 if( (f1&MEM_Real)==0 ){
57824 r1 = (double)pMem1->u.i;
57825 }else{
57826 r1 = pMem1->r;
57828 if( (f2&MEM_Real)==0 ){
57829 r2 = (double)pMem2->u.i;
57830 }else{
57831 r2 = pMem2->r;
57833 if( r1<r2 ) return -1;
57834 if( r1>r2 ) return 1;
57835 return 0;
57836 }else{
57837 assert( f1&MEM_Int );
57838 assert( f2&MEM_Int );
57839 if( pMem1->u.i < pMem2->u.i ) return -1;
57840 if( pMem1->u.i > pMem2->u.i ) return 1;
57841 return 0;
57845 /* If one value is a string and the other is a blob, the string is less.
57846 ** If both are strings, compare using the collating functions.
57848 if( combined_flags&MEM_Str ){
57849 if( (f1 & MEM_Str)==0 ){
57850 return 1;
57852 if( (f2 & MEM_Str)==0 ){
57853 return -1;
57856 assert( pMem1->enc==pMem2->enc );
57857 assert( pMem1->enc==SQLITE_UTF8 ||
57858 pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
57860 /* The collation sequence must be defined at this point, even if
57861 ** the user deletes the collation sequence after the vdbe program is
57862 ** compiled (this was not always the case).
57864 assert( !pColl || pColl->xCmp );
57866 if( pColl ){
57867 if( pMem1->enc==pColl->enc ){
57868 /* The strings are already in the correct encoding. Call the
57869 ** comparison function directly */
57870 return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
57871 }else{
57872 const void *v1, *v2;
57873 int n1, n2;
57874 Mem c1;
57875 Mem c2;
57876 memset(&c1, 0, sizeof(c1));
57877 memset(&c2, 0, sizeof(c2));
57878 sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
57879 sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
57880 v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
57881 n1 = v1==0 ? 0 : c1.n;
57882 v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
57883 n2 = v2==0 ? 0 : c2.n;
57884 rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
57885 sqlite3VdbeMemRelease(&c1);
57886 sqlite3VdbeMemRelease(&c2);
57887 return rc;
57890 /* If a NULL pointer was passed as the collate function, fall through
57891 ** to the blob case and use memcmp(). */
57894 /* Both values must be blobs. Compare using memcmp(). */
57895 rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
57896 if( rc==0 ){
57897 rc = pMem1->n - pMem2->n;
57899 return rc;
57903 ** Move data out of a btree key or data field and into a Mem structure.
57904 ** The data or key is taken from the entry that pCur is currently pointing
57905 ** to. offset and amt determine what portion of the data or key to retrieve.
57906 ** key is true to get the key or false to get data. The result is written
57907 ** into the pMem element.
57909 ** The pMem structure is assumed to be uninitialized. Any prior content
57910 ** is overwritten without being freed.
57912 ** If this routine fails for any reason (malloc returns NULL or unable
57913 ** to read from the disk) then the pMem is left in an inconsistent state.
57915 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
57916 BtCursor *pCur, /* Cursor pointing at record to retrieve. */
57917 int offset, /* Offset from the start of data to return bytes from. */
57918 int amt, /* Number of bytes to return. */
57919 int key, /* If true, retrieve from the btree key, not data. */
57920 Mem *pMem /* OUT: Return data in this Mem structure. */
57922 char *zData; /* Data from the btree layer */
57923 int available = 0; /* Number of bytes available on the local btree page */
57924 int rc = SQLITE_OK; /* Return code */
57926 assert( sqlite3BtreeCursorIsValid(pCur) );
57928 /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
57929 ** that both the BtShared and database handle mutexes are held. */
57930 assert( (pMem->flags & MEM_RowSet)==0 );
57931 if( key ){
57932 zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
57933 }else{
57934 zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
57936 assert( zData!=0 );
57938 if( offset+amt<=available && (pMem->flags&MEM_Dyn)==0 ){
57939 sqlite3VdbeMemRelease(pMem);
57940 pMem->z = &zData[offset];
57941 pMem->flags = MEM_Blob|MEM_Ephem;
57942 }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
57943 pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
57944 pMem->enc = 0;
57945 pMem->type = SQLITE_BLOB;
57946 if( key ){
57947 rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
57948 }else{
57949 rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
57951 pMem->z[amt] = 0;
57952 pMem->z[amt+1] = 0;
57953 if( rc!=SQLITE_OK ){
57954 sqlite3VdbeMemRelease(pMem);
57957 pMem->n = amt;
57959 return rc;
57962 /* This function is only available internally, it is not part of the
57963 ** external API. It works in a similar way to sqlite3_value_text(),
57964 ** except the data returned is in the encoding specified by the second
57965 ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
57966 ** SQLITE_UTF8.
57968 ** (2006-02-16:) The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
57969 ** If that is the case, then the result must be aligned on an even byte
57970 ** boundary.
57972 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
57973 if( !pVal ) return 0;
57975 assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
57976 assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
57977 assert( (pVal->flags & MEM_RowSet)==0 );
57979 if( pVal->flags&MEM_Null ){
57980 return 0;
57982 assert( (MEM_Blob>>3) == MEM_Str );
57983 pVal->flags |= (pVal->flags & MEM_Blob)>>3;
57984 expandBlob(pVal);
57985 if( pVal->flags&MEM_Str ){
57986 sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
57987 if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
57988 assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
57989 if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
57990 return 0;
57993 sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-59893-45467 */
57994 }else{
57995 assert( (pVal->flags&MEM_Blob)==0 );
57996 sqlite3VdbeMemStringify(pVal, enc);
57997 assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
57999 assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
58000 || pVal->db->mallocFailed );
58001 if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
58002 return pVal->z;
58003 }else{
58004 return 0;
58009 ** Create a new sqlite3_value object.
58011 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
58012 Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
58013 if( p ){
58014 p->flags = MEM_Null;
58015 p->type = SQLITE_NULL;
58016 p->db = db;
58018 return p;
58022 ** Create a new sqlite3_value object, containing the value of pExpr.
58024 ** This only works for very simple expressions that consist of one constant
58025 ** token (i.e. "5", "5.1", "'a string'"). If the expression can
58026 ** be converted directly into a value, then the value is allocated and
58027 ** a pointer written to *ppVal. The caller is responsible for deallocating
58028 ** the value by passing it to sqlite3ValueFree() later on. If the expression
58029 ** cannot be converted to a value, then *ppVal is set to NULL.
58031 SQLITE_PRIVATE int sqlite3ValueFromExpr(
58032 sqlite3 *db, /* The database connection */
58033 Expr *pExpr, /* The expression to evaluate */
58034 u8 enc, /* Encoding to use */
58035 u8 affinity, /* Affinity to use */
58036 sqlite3_value **ppVal /* Write the new value here */
58038 int op;
58039 char *zVal = 0;
58040 sqlite3_value *pVal = 0;
58041 int negInt = 1;
58042 const char *zNeg = "";
58044 if( !pExpr ){
58045 *ppVal = 0;
58046 return SQLITE_OK;
58048 op = pExpr->op;
58050 /* op can only be TK_REGISTER if we have compiled with SQLITE_ENABLE_STAT3.
58051 ** The ifdef here is to enable us to achieve 100% branch test coverage even
58052 ** when SQLITE_ENABLE_STAT3 is omitted.
58054 #ifdef SQLITE_ENABLE_STAT3
58055 if( op==TK_REGISTER ) op = pExpr->op2;
58056 #else
58057 if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
58058 #endif
58060 /* Handle negative integers in a single step. This is needed in the
58061 ** case when the value is -9223372036854775808.
58063 if( op==TK_UMINUS
58064 && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
58065 pExpr = pExpr->pLeft;
58066 op = pExpr->op;
58067 negInt = -1;
58068 zNeg = "-";
58071 if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
58072 pVal = sqlite3ValueNew(db);
58073 if( pVal==0 ) goto no_mem;
58074 if( ExprHasProperty(pExpr, EP_IntValue) ){
58075 sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
58076 }else{
58077 zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
58078 if( zVal==0 ) goto no_mem;
58079 sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
58080 if( op==TK_FLOAT ) pVal->type = SQLITE_FLOAT;
58082 if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
58083 sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
58084 }else{
58085 sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
58087 if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
58088 if( enc!=SQLITE_UTF8 ){
58089 sqlite3VdbeChangeEncoding(pVal, enc);
58091 }else if( op==TK_UMINUS ) {
58092 /* This branch happens for multiple negative signs. Ex: -(-5) */
58093 if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) ){
58094 sqlite3VdbeMemNumerify(pVal);
58095 if( pVal->u.i==SMALLEST_INT64 ){
58096 pVal->flags &= MEM_Int;
58097 pVal->flags |= MEM_Real;
58098 pVal->r = (double)LARGEST_INT64;
58099 }else{
58100 pVal->u.i = -pVal->u.i;
58102 pVal->r = -pVal->r;
58103 sqlite3ValueApplyAffinity(pVal, affinity, enc);
58105 }else if( op==TK_NULL ){
58106 pVal = sqlite3ValueNew(db);
58107 if( pVal==0 ) goto no_mem;
58109 #ifndef SQLITE_OMIT_BLOB_LITERAL
58110 else if( op==TK_BLOB ){
58111 int nVal;
58112 assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
58113 assert( pExpr->u.zToken[1]=='\'' );
58114 pVal = sqlite3ValueNew(db);
58115 if( !pVal ) goto no_mem;
58116 zVal = &pExpr->u.zToken[2];
58117 nVal = sqlite3Strlen30(zVal)-1;
58118 assert( zVal[nVal]=='\'' );
58119 sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
58120 0, SQLITE_DYNAMIC);
58122 #endif
58124 if( pVal ){
58125 sqlite3VdbeMemStoreType(pVal);
58127 *ppVal = pVal;
58128 return SQLITE_OK;
58130 no_mem:
58131 db->mallocFailed = 1;
58132 sqlite3DbFree(db, zVal);
58133 sqlite3ValueFree(pVal);
58134 *ppVal = 0;
58135 return SQLITE_NOMEM;
58139 ** Change the string value of an sqlite3_value object
58141 SQLITE_PRIVATE void sqlite3ValueSetStr(
58142 sqlite3_value *v, /* Value to be set */
58143 int n, /* Length of string z */
58144 const void *z, /* Text of the new string */
58145 u8 enc, /* Encoding to use */
58146 void (*xDel)(void*) /* Destructor for the string */
58148 if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
58152 ** Free an sqlite3_value object
58154 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
58155 if( !v ) return;
58156 sqlite3VdbeMemRelease((Mem *)v);
58157 sqlite3DbFree(((Mem*)v)->db, v);
58161 ** Return the number of bytes in the sqlite3_value object assuming
58162 ** that it uses the encoding "enc"
58164 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
58165 Mem *p = (Mem*)pVal;
58166 if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
58167 if( p->flags & MEM_Zero ){
58168 return p->n + p->u.nZero;
58169 }else{
58170 return p->n;
58173 return 0;
58176 /************** End of vdbemem.c *********************************************/
58177 /************** Begin file vdbeaux.c *****************************************/
58179 ** 2003 September 6
58181 ** The author disclaims copyright to this source code. In place of
58182 ** a legal notice, here is a blessing:
58184 ** May you do good and not evil.
58185 ** May you find forgiveness for yourself and forgive others.
58186 ** May you share freely, never taking more than you give.
58188 *************************************************************************
58189 ** This file contains code used for creating, destroying, and populating
58190 ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.) Prior
58191 ** to version 2.8.7, all this code was combined into the vdbe.c source file.
58192 ** But that file was getting too big so this subroutines were split out.
58198 ** When debugging the code generator in a symbolic debugger, one can
58199 ** set the sqlite3VdbeAddopTrace to 1 and all opcodes will be printed
58200 ** as they are added to the instruction stream.
58202 #ifdef SQLITE_DEBUG
58203 SQLITE_PRIVATE int sqlite3VdbeAddopTrace = 0;
58204 #endif
58208 ** Create a new virtual database engine.
58210 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3 *db){
58211 Vdbe *p;
58212 p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
58213 if( p==0 ) return 0;
58214 p->db = db;
58215 if( db->pVdbe ){
58216 db->pVdbe->pPrev = p;
58218 p->pNext = db->pVdbe;
58219 p->pPrev = 0;
58220 db->pVdbe = p;
58221 p->magic = VDBE_MAGIC_INIT;
58222 return p;
58226 ** Remember the SQL string for a prepared statement.
58228 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
58229 assert( isPrepareV2==1 || isPrepareV2==0 );
58230 if( p==0 ) return;
58231 #ifdef SQLITE_OMIT_TRACE
58232 if( !isPrepareV2 ) return;
58233 #endif
58234 assert( p->zSql==0 );
58235 p->zSql = sqlite3DbStrNDup(p->db, z, n);
58236 p->isPrepareV2 = (u8)isPrepareV2;
58240 ** Return the SQL associated with a prepared statement
58242 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
58243 Vdbe *p = (Vdbe *)pStmt;
58244 return (p && p->isPrepareV2) ? p->zSql : 0;
58248 ** Swap all content between two VDBE structures.
58250 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
58251 Vdbe tmp, *pTmp;
58252 char *zTmp;
58253 tmp = *pA;
58254 *pA = *pB;
58255 *pB = tmp;
58256 pTmp = pA->pNext;
58257 pA->pNext = pB->pNext;
58258 pB->pNext = pTmp;
58259 pTmp = pA->pPrev;
58260 pA->pPrev = pB->pPrev;
58261 pB->pPrev = pTmp;
58262 zTmp = pA->zSql;
58263 pA->zSql = pB->zSql;
58264 pB->zSql = zTmp;
58265 pB->isPrepareV2 = pA->isPrepareV2;
58268 #ifdef SQLITE_DEBUG
58270 ** Turn tracing on or off
58272 SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
58273 p->trace = trace;
58275 #endif
58278 ** Resize the Vdbe.aOp array so that it is at least one op larger than
58279 ** it was.
58281 ** If an out-of-memory error occurs while resizing the array, return
58282 ** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain
58283 ** unchanged (this is so that any opcodes already allocated can be
58284 ** correctly deallocated along with the rest of the Vdbe).
58286 static int growOpArray(Vdbe *p){
58287 VdbeOp *pNew;
58288 int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
58289 pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op));
58290 if( pNew ){
58291 p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
58292 p->aOp = pNew;
58294 return (pNew ? SQLITE_OK : SQLITE_NOMEM);
58298 ** Add a new instruction to the list of instructions current in the
58299 ** VDBE. Return the address of the new instruction.
58301 ** Parameters:
58303 ** p Pointer to the VDBE
58305 ** op The opcode for this instruction
58307 ** p1, p2, p3 Operands
58309 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
58310 ** the sqlite3VdbeChangeP4() function to change the value of the P4
58311 ** operand.
58313 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
58314 int i;
58315 VdbeOp *pOp;
58317 i = p->nOp;
58318 assert( p->magic==VDBE_MAGIC_INIT );
58319 assert( op>0 && op<0xff );
58320 if( p->nOpAlloc<=i ){
58321 if( growOpArray(p) ){
58322 return 1;
58325 p->nOp++;
58326 pOp = &p->aOp[i];
58327 pOp->opcode = (u8)op;
58328 pOp->p5 = 0;
58329 pOp->p1 = p1;
58330 pOp->p2 = p2;
58331 pOp->p3 = p3;
58332 pOp->p4.p = 0;
58333 pOp->p4type = P4_NOTUSED;
58334 #ifdef SQLITE_DEBUG
58335 pOp->zComment = 0;
58336 if( sqlite3VdbeAddopTrace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]);
58337 #endif
58338 #ifdef VDBE_PROFILE
58339 pOp->cycles = 0;
58340 pOp->cnt = 0;
58341 #endif
58342 return i;
58344 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
58345 return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
58347 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
58348 return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
58350 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
58351 return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
58356 ** Add an opcode that includes the p4 value as a pointer.
58358 SQLITE_PRIVATE int sqlite3VdbeAddOp4(
58359 Vdbe *p, /* Add the opcode to this VM */
58360 int op, /* The new opcode */
58361 int p1, /* The P1 operand */
58362 int p2, /* The P2 operand */
58363 int p3, /* The P3 operand */
58364 const char *zP4, /* The P4 operand */
58365 int p4type /* P4 operand type */
58367 int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
58368 sqlite3VdbeChangeP4(p, addr, zP4, p4type);
58369 return addr;
58373 ** Add an OP_ParseSchema opcode. This routine is broken out from
58374 ** sqlite3VdbeAddOp4() since it needs to also local all btrees.
58376 ** The zWhere string must have been obtained from sqlite3_malloc().
58377 ** This routine will take ownership of the allocated memory.
58379 SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
58380 int j;
58381 int addr = sqlite3VdbeAddOp3(p, OP_ParseSchema, iDb, 0, 0);
58382 sqlite3VdbeChangeP4(p, addr, zWhere, P4_DYNAMIC);
58383 for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
58387 ** Add an opcode that includes the p4 value as an integer.
58389 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
58390 Vdbe *p, /* Add the opcode to this VM */
58391 int op, /* The new opcode */
58392 int p1, /* The P1 operand */
58393 int p2, /* The P2 operand */
58394 int p3, /* The P3 operand */
58395 int p4 /* The P4 operand as an integer */
58397 int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
58398 sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
58399 return addr;
58403 ** Create a new symbolic label for an instruction that has yet to be
58404 ** coded. The symbolic label is really just a negative number. The
58405 ** label can be used as the P2 value of an operation. Later, when
58406 ** the label is resolved to a specific address, the VDBE will scan
58407 ** through its operation list and change all values of P2 which match
58408 ** the label into the resolved address.
58410 ** The VDBE knows that a P2 value is a label because labels are
58411 ** always negative and P2 values are suppose to be non-negative.
58412 ** Hence, a negative P2 value is a label that has yet to be resolved.
58414 ** Zero is returned if a malloc() fails.
58416 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *p){
58417 int i;
58418 i = p->nLabel++;
58419 assert( p->magic==VDBE_MAGIC_INIT );
58420 if( i>=p->nLabelAlloc ){
58421 int n = p->nLabelAlloc*2 + 5;
58422 p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
58423 n*sizeof(p->aLabel[0]));
58424 p->nLabelAlloc = sqlite3DbMallocSize(p->db, p->aLabel)/sizeof(p->aLabel[0]);
58426 if( p->aLabel ){
58427 p->aLabel[i] = -1;
58429 return -1-i;
58433 ** Resolve label "x" to be the address of the next instruction to
58434 ** be inserted. The parameter "x" must have been obtained from
58435 ** a prior call to sqlite3VdbeMakeLabel().
58437 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *p, int x){
58438 int j = -1-x;
58439 assert( p->magic==VDBE_MAGIC_INIT );
58440 assert( j>=0 && j<p->nLabel );
58441 if( p->aLabel ){
58442 p->aLabel[j] = p->nOp;
58447 ** Mark the VDBE as one that can only be run one time.
58449 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
58450 p->runOnlyOnce = 1;
58453 #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
58456 ** The following type and function are used to iterate through all opcodes
58457 ** in a Vdbe main program and each of the sub-programs (triggers) it may
58458 ** invoke directly or indirectly. It should be used as follows:
58460 ** Op *pOp;
58461 ** VdbeOpIter sIter;
58463 ** memset(&sIter, 0, sizeof(sIter));
58464 ** sIter.v = v; // v is of type Vdbe*
58465 ** while( (pOp = opIterNext(&sIter)) ){
58466 ** // Do something with pOp
58467 ** }
58468 ** sqlite3DbFree(v->db, sIter.apSub);
58471 typedef struct VdbeOpIter VdbeOpIter;
58472 struct VdbeOpIter {
58473 Vdbe *v; /* Vdbe to iterate through the opcodes of */
58474 SubProgram **apSub; /* Array of subprograms */
58475 int nSub; /* Number of entries in apSub */
58476 int iAddr; /* Address of next instruction to return */
58477 int iSub; /* 0 = main program, 1 = first sub-program etc. */
58479 static Op *opIterNext(VdbeOpIter *p){
58480 Vdbe *v = p->v;
58481 Op *pRet = 0;
58482 Op *aOp;
58483 int nOp;
58485 if( p->iSub<=p->nSub ){
58487 if( p->iSub==0 ){
58488 aOp = v->aOp;
58489 nOp = v->nOp;
58490 }else{
58491 aOp = p->apSub[p->iSub-1]->aOp;
58492 nOp = p->apSub[p->iSub-1]->nOp;
58494 assert( p->iAddr<nOp );
58496 pRet = &aOp[p->iAddr];
58497 p->iAddr++;
58498 if( p->iAddr==nOp ){
58499 p->iSub++;
58500 p->iAddr = 0;
58503 if( pRet->p4type==P4_SUBPROGRAM ){
58504 int nByte = (p->nSub+1)*sizeof(SubProgram*);
58505 int j;
58506 for(j=0; j<p->nSub; j++){
58507 if( p->apSub[j]==pRet->p4.pProgram ) break;
58509 if( j==p->nSub ){
58510 p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
58511 if( !p->apSub ){
58512 pRet = 0;
58513 }else{
58514 p->apSub[p->nSub++] = pRet->p4.pProgram;
58520 return pRet;
58524 ** Check if the program stored in the VM associated with pParse may
58525 ** throw an ABORT exception (causing the statement, but not entire transaction
58526 ** to be rolled back). This condition is true if the main program or any
58527 ** sub-programs contains any of the following:
58529 ** * OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
58530 ** * OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
58531 ** * OP_Destroy
58532 ** * OP_VUpdate
58533 ** * OP_VRename
58534 ** * OP_FkCounter with P2==0 (immediate foreign key constraint)
58536 ** Then check that the value of Parse.mayAbort is true if an
58537 ** ABORT may be thrown, or false otherwise. Return true if it does
58538 ** match, or false otherwise. This function is intended to be used as
58539 ** part of an assert statement in the compiler. Similar to:
58541 ** assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
58543 SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
58544 int hasAbort = 0;
58545 Op *pOp;
58546 VdbeOpIter sIter;
58547 memset(&sIter, 0, sizeof(sIter));
58548 sIter.v = v;
58550 while( (pOp = opIterNext(&sIter))!=0 ){
58551 int opcode = pOp->opcode;
58552 if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
58553 #ifndef SQLITE_OMIT_FOREIGN_KEY
58554 || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1)
58555 #endif
58556 || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
58557 && (pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
58559 hasAbort = 1;
58560 break;
58563 sqlite3DbFree(v->db, sIter.apSub);
58565 /* Return true if hasAbort==mayAbort. Or if a malloc failure occured.
58566 ** If malloc failed, then the while() loop above may not have iterated
58567 ** through all opcodes and hasAbort may be set incorrectly. Return
58568 ** true for this case to prevent the assert() in the callers frame
58569 ** from failing. */
58570 return ( v->db->mallocFailed || hasAbort==mayAbort );
58572 #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
58575 ** Loop through the program looking for P2 values that are negative
58576 ** on jump instructions. Each such value is a label. Resolve the
58577 ** label by setting the P2 value to its correct non-zero value.
58579 ** This routine is called once after all opcodes have been inserted.
58581 ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument
58582 ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by
58583 ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
58585 ** The Op.opflags field is set on all opcodes.
58587 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
58588 int i;
58589 int nMaxArgs = *pMaxFuncArgs;
58590 Op *pOp;
58591 int *aLabel = p->aLabel;
58592 p->readOnly = 1;
58593 for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
58594 u8 opcode = pOp->opcode;
58596 pOp->opflags = sqlite3OpcodeProperty[opcode];
58597 if( opcode==OP_Function || opcode==OP_AggStep ){
58598 if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
58599 }else if( (opcode==OP_Transaction && pOp->p2!=0) || opcode==OP_Vacuum ){
58600 p->readOnly = 0;
58601 #ifndef SQLITE_OMIT_VIRTUALTABLE
58602 }else if( opcode==OP_VUpdate ){
58603 if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
58604 }else if( opcode==OP_VFilter ){
58605 int n;
58606 assert( p->nOp - i >= 3 );
58607 assert( pOp[-1].opcode==OP_Integer );
58608 n = pOp[-1].p1;
58609 if( n>nMaxArgs ) nMaxArgs = n;
58610 #endif
58611 }else if( opcode==OP_Next || opcode==OP_SorterNext ){
58612 pOp->p4.xAdvance = sqlite3BtreeNext;
58613 pOp->p4type = P4_ADVANCE;
58614 }else if( opcode==OP_Prev ){
58615 pOp->p4.xAdvance = sqlite3BtreePrevious;
58616 pOp->p4type = P4_ADVANCE;
58619 if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
58620 assert( -1-pOp->p2<p->nLabel );
58621 pOp->p2 = aLabel[-1-pOp->p2];
58624 sqlite3DbFree(p->db, p->aLabel);
58625 p->aLabel = 0;
58627 *pMaxFuncArgs = nMaxArgs;
58631 ** Return the address of the next instruction to be inserted.
58633 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
58634 assert( p->magic==VDBE_MAGIC_INIT );
58635 return p->nOp;
58639 ** This function returns a pointer to the array of opcodes associated with
58640 ** the Vdbe passed as the first argument. It is the callers responsibility
58641 ** to arrange for the returned array to be eventually freed using the
58642 ** vdbeFreeOpArray() function.
58644 ** Before returning, *pnOp is set to the number of entries in the returned
58645 ** array. Also, *pnMaxArg is set to the larger of its current value and
58646 ** the number of entries in the Vdbe.apArg[] array required to execute the
58647 ** returned program.
58649 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
58650 VdbeOp *aOp = p->aOp;
58651 assert( aOp && !p->db->mallocFailed );
58653 /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
58654 assert( p->btreeMask==0 );
58656 resolveP2Values(p, pnMaxArg);
58657 *pnOp = p->nOp;
58658 p->aOp = 0;
58659 return aOp;
58663 ** Add a whole list of operations to the operation stack. Return the
58664 ** address of the first operation added.
58666 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
58667 int addr;
58668 assert( p->magic==VDBE_MAGIC_INIT );
58669 if( p->nOp + nOp > p->nOpAlloc && growOpArray(p) ){
58670 return 0;
58672 addr = p->nOp;
58673 if( ALWAYS(nOp>0) ){
58674 int i;
58675 VdbeOpList const *pIn = aOp;
58676 for(i=0; i<nOp; i++, pIn++){
58677 int p2 = pIn->p2;
58678 VdbeOp *pOut = &p->aOp[i+addr];
58679 pOut->opcode = pIn->opcode;
58680 pOut->p1 = pIn->p1;
58681 if( p2<0 && (sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP)!=0 ){
58682 pOut->p2 = addr + ADDR(p2);
58683 }else{
58684 pOut->p2 = p2;
58686 pOut->p3 = pIn->p3;
58687 pOut->p4type = P4_NOTUSED;
58688 pOut->p4.p = 0;
58689 pOut->p5 = 0;
58690 #ifdef SQLITE_DEBUG
58691 pOut->zComment = 0;
58692 if( sqlite3VdbeAddopTrace ){
58693 sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
58695 #endif
58697 p->nOp += nOp;
58699 return addr;
58703 ** Change the value of the P1 operand for a specific instruction.
58704 ** This routine is useful when a large program is loaded from a
58705 ** static array using sqlite3VdbeAddOpList but we want to make a
58706 ** few minor changes to the program.
58708 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
58709 assert( p!=0 );
58710 if( ((u32)p->nOp)>addr ){
58711 p->aOp[addr].p1 = val;
58716 ** Change the value of the P2 operand for a specific instruction.
58717 ** This routine is useful for setting a jump destination.
58719 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
58720 assert( p!=0 );
58721 if( ((u32)p->nOp)>addr ){
58722 p->aOp[addr].p2 = val;
58727 ** Change the value of the P3 operand for a specific instruction.
58729 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
58730 assert( p!=0 );
58731 if( ((u32)p->nOp)>addr ){
58732 p->aOp[addr].p3 = val;
58737 ** Change the value of the P5 operand for the most recently
58738 ** added operation.
58740 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
58741 assert( p!=0 );
58742 if( p->aOp ){
58743 assert( p->nOp>0 );
58744 p->aOp[p->nOp-1].p5 = val;
58749 ** Change the P2 operand of instruction addr so that it points to
58750 ** the address of the next instruction to be coded.
58752 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
58753 assert( addr>=0 || p->db->mallocFailed );
58754 if( addr>=0 ) sqlite3VdbeChangeP2(p, addr, p->nOp);
58759 ** If the input FuncDef structure is ephemeral, then free it. If
58760 ** the FuncDef is not ephermal, then do nothing.
58762 static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
58763 if( ALWAYS(pDef) && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
58764 sqlite3DbFree(db, pDef);
58768 static void vdbeFreeOpArray(sqlite3 *, Op *, int);
58771 ** Delete a P4 value if necessary.
58773 static void freeP4(sqlite3 *db, int p4type, void *p4){
58774 if( p4 ){
58775 assert( db );
58776 switch( p4type ){
58777 case P4_REAL:
58778 case P4_INT64:
58779 case P4_DYNAMIC:
58780 case P4_KEYINFO:
58781 case P4_INTARRAY:
58782 case P4_KEYINFO_HANDOFF: {
58783 sqlite3DbFree(db, p4);
58784 break;
58786 case P4_MPRINTF: {
58787 if( db->pnBytesFreed==0 ) sqlite3_free(p4);
58788 break;
58790 case P4_VDBEFUNC: {
58791 VdbeFunc *pVdbeFunc = (VdbeFunc *)p4;
58792 freeEphemeralFunction(db, pVdbeFunc->pFunc);
58793 if( db->pnBytesFreed==0 ) sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
58794 sqlite3DbFree(db, pVdbeFunc);
58795 break;
58797 case P4_FUNCDEF: {
58798 freeEphemeralFunction(db, (FuncDef*)p4);
58799 break;
58801 case P4_MEM: {
58802 if( db->pnBytesFreed==0 ){
58803 sqlite3ValueFree((sqlite3_value*)p4);
58804 }else{
58805 Mem *p = (Mem*)p4;
58806 sqlite3DbFree(db, p->zMalloc);
58807 sqlite3DbFree(db, p);
58809 break;
58811 case P4_VTAB : {
58812 if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
58813 break;
58820 ** Free the space allocated for aOp and any p4 values allocated for the
58821 ** opcodes contained within. If aOp is not NULL it is assumed to contain
58822 ** nOp entries.
58824 static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
58825 if( aOp ){
58826 Op *pOp;
58827 for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
58828 freeP4(db, pOp->p4type, pOp->p4.p);
58829 #ifdef SQLITE_DEBUG
58830 sqlite3DbFree(db, pOp->zComment);
58831 #endif
58834 sqlite3DbFree(db, aOp);
58838 ** Link the SubProgram object passed as the second argument into the linked
58839 ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
58840 ** objects when the VM is no longer required.
58842 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
58843 p->pNext = pVdbe->pProgram;
58844 pVdbe->pProgram = p;
58848 ** Change the opcode at addr into OP_Noop
58850 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
58851 if( p->aOp ){
58852 VdbeOp *pOp = &p->aOp[addr];
58853 sqlite3 *db = p->db;
58854 freeP4(db, pOp->p4type, pOp->p4.p);
58855 memset(pOp, 0, sizeof(pOp[0]));
58856 pOp->opcode = OP_Noop;
58861 ** Change the value of the P4 operand for a specific instruction.
58862 ** This routine is useful when a large program is loaded from a
58863 ** static array using sqlite3VdbeAddOpList but we want to make a
58864 ** few minor changes to the program.
58866 ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
58867 ** the string is made into memory obtained from sqlite3_malloc().
58868 ** A value of n==0 means copy bytes of zP4 up to and including the
58869 ** first null byte. If n>0 then copy n+1 bytes of zP4.
58871 ** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
58872 ** A copy is made of the KeyInfo structure into memory obtained from
58873 ** sqlite3_malloc, to be freed when the Vdbe is finalized.
58874 ** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
58875 ** stored in memory that the caller has obtained from sqlite3_malloc. The
58876 ** caller should not free the allocation, it will be freed when the Vdbe is
58877 ** finalized.
58879 ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
58880 ** to a string or structure that is guaranteed to exist for the lifetime of
58881 ** the Vdbe. In these cases we can just copy the pointer.
58883 ** If addr<0 then change P4 on the most recently inserted instruction.
58885 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
58886 Op *pOp;
58887 sqlite3 *db;
58888 assert( p!=0 );
58889 db = p->db;
58890 assert( p->magic==VDBE_MAGIC_INIT );
58891 if( p->aOp==0 || db->mallocFailed ){
58892 if ( n!=P4_KEYINFO && n!=P4_VTAB ) {
58893 freeP4(db, n, (void*)*(char**)&zP4);
58895 return;
58897 assert( p->nOp>0 );
58898 assert( addr<p->nOp );
58899 if( addr<0 ){
58900 addr = p->nOp - 1;
58902 pOp = &p->aOp[addr];
58903 freeP4(db, pOp->p4type, pOp->p4.p);
58904 pOp->p4.p = 0;
58905 if( n==P4_INT32 ){
58906 /* Note: this cast is safe, because the origin data point was an int
58907 ** that was cast to a (const char *). */
58908 pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
58909 pOp->p4type = P4_INT32;
58910 }else if( zP4==0 ){
58911 pOp->p4.p = 0;
58912 pOp->p4type = P4_NOTUSED;
58913 }else if( n==P4_KEYINFO ){
58914 KeyInfo *pKeyInfo;
58915 int nField, nByte;
58917 nField = ((KeyInfo*)zP4)->nField;
58918 nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
58919 pKeyInfo = sqlite3DbMallocRaw(0, nByte);
58920 pOp->p4.pKeyInfo = pKeyInfo;
58921 if( pKeyInfo ){
58922 u8 *aSortOrder;
58923 memcpy((char*)pKeyInfo, zP4, nByte - nField);
58924 aSortOrder = pKeyInfo->aSortOrder;
58925 if( aSortOrder ){
58926 pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
58927 memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
58929 pOp->p4type = P4_KEYINFO;
58930 }else{
58931 p->db->mallocFailed = 1;
58932 pOp->p4type = P4_NOTUSED;
58934 }else if( n==P4_KEYINFO_HANDOFF ){
58935 pOp->p4.p = (void*)zP4;
58936 pOp->p4type = P4_KEYINFO;
58937 }else if( n==P4_VTAB ){
58938 pOp->p4.p = (void*)zP4;
58939 pOp->p4type = P4_VTAB;
58940 sqlite3VtabLock((VTable *)zP4);
58941 assert( ((VTable *)zP4)->db==p->db );
58942 }else if( n<0 ){
58943 pOp->p4.p = (void*)zP4;
58944 pOp->p4type = (signed char)n;
58945 }else{
58946 if( n==0 ) n = sqlite3Strlen30(zP4);
58947 pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
58948 pOp->p4type = P4_DYNAMIC;
58952 #ifndef NDEBUG
58954 ** Change the comment on the the most recently coded instruction. Or
58955 ** insert a No-op and add the comment to that new instruction. This
58956 ** makes the code easier to read during debugging. None of this happens
58957 ** in a production build.
58959 static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
58960 assert( p->nOp>0 || p->aOp==0 );
58961 assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
58962 if( p->nOp ){
58963 assert( p->aOp );
58964 sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
58965 p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
58968 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
58969 va_list ap;
58970 if( p ){
58971 va_start(ap, zFormat);
58972 vdbeVComment(p, zFormat, ap);
58973 va_end(ap);
58976 SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
58977 va_list ap;
58978 if( p ){
58979 sqlite3VdbeAddOp0(p, OP_Noop);
58980 va_start(ap, zFormat);
58981 vdbeVComment(p, zFormat, ap);
58982 va_end(ap);
58985 #endif /* NDEBUG */
58988 ** Return the opcode for a given address. If the address is -1, then
58989 ** return the most recently inserted opcode.
58991 ** If a memory allocation error has occurred prior to the calling of this
58992 ** routine, then a pointer to a dummy VdbeOp will be returned. That opcode
58993 ** is readable but not writable, though it is cast to a writable value.
58994 ** The return of a dummy opcode allows the call to continue functioning
58995 ** after a OOM fault without having to check to see if the return from
58996 ** this routine is a valid pointer. But because the dummy.opcode is 0,
58997 ** dummy will never be written to. This is verified by code inspection and
58998 ** by running with Valgrind.
59000 ** About the #ifdef SQLITE_OMIT_TRACE: Normally, this routine is never called
59001 ** unless p->nOp>0. This is because in the absense of SQLITE_OMIT_TRACE,
59002 ** an OP_Trace instruction is always inserted by sqlite3VdbeGet() as soon as
59003 ** a new VDBE is created. So we are free to set addr to p->nOp-1 without
59004 ** having to double-check to make sure that the result is non-negative. But
59005 ** if SQLITE_OMIT_TRACE is defined, the OP_Trace is omitted and we do need to
59006 ** check the value of p->nOp-1 before continuing.
59008 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
59009 /* C89 specifies that the constant "dummy" will be initialized to all
59010 ** zeros, which is correct. MSVC generates a warning, nevertheless. */
59011 static VdbeOp dummy; /* Ignore the MSVC warning about no initializer */
59012 assert( p->magic==VDBE_MAGIC_INIT );
59013 if( addr<0 ){
59014 #ifdef SQLITE_OMIT_TRACE
59015 if( p->nOp==0 ) return (VdbeOp*)&dummy;
59016 #endif
59017 addr = p->nOp - 1;
59019 assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
59020 if( p->db->mallocFailed ){
59021 return (VdbeOp*)&dummy;
59022 }else{
59023 return &p->aOp[addr];
59027 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
59028 || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
59030 ** Compute a string that describes the P4 parameter for an opcode.
59031 ** Use zTemp for any required temporary buffer space.
59033 static char *displayP4(Op *pOp, char *zTemp, int nTemp){
59034 char *zP4 = zTemp;
59035 assert( nTemp>=20 );
59036 switch( pOp->p4type ){
59037 case P4_KEYINFO_STATIC:
59038 case P4_KEYINFO: {
59039 int i, j;
59040 KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
59041 sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
59042 i = sqlite3Strlen30(zTemp);
59043 for(j=0; j<pKeyInfo->nField; j++){
59044 CollSeq *pColl = pKeyInfo->aColl[j];
59045 if( pColl ){
59046 int n = sqlite3Strlen30(pColl->zName);
59047 if( i+n>nTemp-6 ){
59048 memcpy(&zTemp[i],",...",4);
59049 break;
59051 zTemp[i++] = ',';
59052 if( pKeyInfo->aSortOrder && pKeyInfo->aSortOrder[j] ){
59053 zTemp[i++] = '-';
59055 memcpy(&zTemp[i], pColl->zName,n+1);
59056 i += n;
59057 }else if( i+4<nTemp-6 ){
59058 memcpy(&zTemp[i],",nil",4);
59059 i += 4;
59062 zTemp[i++] = ')';
59063 zTemp[i] = 0;
59064 assert( i<nTemp );
59065 break;
59067 case P4_COLLSEQ: {
59068 CollSeq *pColl = pOp->p4.pColl;
59069 sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
59070 break;
59072 case P4_FUNCDEF: {
59073 FuncDef *pDef = pOp->p4.pFunc;
59074 sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
59075 break;
59077 case P4_INT64: {
59078 sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
59079 break;
59081 case P4_INT32: {
59082 sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
59083 break;
59085 case P4_REAL: {
59086 sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
59087 break;
59089 case P4_MEM: {
59090 Mem *pMem = pOp->p4.pMem;
59091 assert( (pMem->flags & MEM_Null)==0 );
59092 if( pMem->flags & MEM_Str ){
59093 zP4 = pMem->z;
59094 }else if( pMem->flags & MEM_Int ){
59095 sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
59096 }else if( pMem->flags & MEM_Real ){
59097 sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
59098 }else{
59099 assert( pMem->flags & MEM_Blob );
59100 zP4 = "(blob)";
59102 break;
59104 #ifndef SQLITE_OMIT_VIRTUALTABLE
59105 case P4_VTAB: {
59106 sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
59107 sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
59108 break;
59110 #endif
59111 case P4_INTARRAY: {
59112 sqlite3_snprintf(nTemp, zTemp, "intarray");
59113 break;
59115 case P4_SUBPROGRAM: {
59116 sqlite3_snprintf(nTemp, zTemp, "program");
59117 break;
59119 case P4_ADVANCE: {
59120 zTemp[0] = 0;
59121 break;
59123 default: {
59124 zP4 = pOp->p4.z;
59125 if( zP4==0 ){
59126 zP4 = zTemp;
59127 zTemp[0] = 0;
59131 assert( zP4!=0 );
59132 return zP4;
59134 #endif
59137 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
59139 ** The prepared statements need to know in advance the complete set of
59140 ** attached databases that they will be using. A mask of these databases
59141 ** is maintained in p->btreeMask and is used for locking and other purposes.
59143 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
59144 assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
59145 assert( i<(int)sizeof(p->btreeMask)*8 );
59146 p->btreeMask |= ((yDbMask)1)<<i;
59147 if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
59148 p->lockMask |= ((yDbMask)1)<<i;
59152 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
59154 ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
59155 ** this routine obtains the mutex associated with each BtShared structure
59156 ** that may be accessed by the VM passed as an argument. In doing so it also
59157 ** sets the BtShared.db member of each of the BtShared structures, ensuring
59158 ** that the correct busy-handler callback is invoked if required.
59160 ** If SQLite is not threadsafe but does support shared-cache mode, then
59161 ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
59162 ** of all of BtShared structures accessible via the database handle
59163 ** associated with the VM.
59165 ** If SQLite is not threadsafe and does not support shared-cache mode, this
59166 ** function is a no-op.
59168 ** The p->btreeMask field is a bitmask of all btrees that the prepared
59169 ** statement p will ever use. Let N be the number of bits in p->btreeMask
59170 ** corresponding to btrees that use shared cache. Then the runtime of
59171 ** this routine is N*N. But as N is rarely more than 1, this should not
59172 ** be a problem.
59174 SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
59175 int i;
59176 yDbMask mask;
59177 sqlite3 *db;
59178 Db *aDb;
59179 int nDb;
59180 if( p->lockMask==0 ) return; /* The common case */
59181 db = p->db;
59182 aDb = db->aDb;
59183 nDb = db->nDb;
59184 for(i=0, mask=1; i<nDb; i++, mask += mask){
59185 if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
59186 sqlite3BtreeEnter(aDb[i].pBt);
59190 #endif
59192 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
59194 ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
59196 SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
59197 int i;
59198 yDbMask mask;
59199 sqlite3 *db;
59200 Db *aDb;
59201 int nDb;
59202 if( p->lockMask==0 ) return; /* The common case */
59203 db = p->db;
59204 aDb = db->aDb;
59205 nDb = db->nDb;
59206 for(i=0, mask=1; i<nDb; i++, mask += mask){
59207 if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
59208 sqlite3BtreeLeave(aDb[i].pBt);
59212 #endif
59214 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
59216 ** Print a single opcode. This routine is used for debugging only.
59218 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
59219 char *zP4;
59220 char zPtr[50];
59221 static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
59222 if( pOut==0 ) pOut = stdout;
59223 zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
59224 fprintf(pOut, zFormat1, pc,
59225 sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
59226 #ifdef SQLITE_DEBUG
59227 pOp->zComment ? pOp->zComment : ""
59228 #else
59230 #endif
59232 fflush(pOut);
59234 #endif
59237 ** Release an array of N Mem elements
59239 static void releaseMemArray(Mem *p, int N){
59240 if( p && N ){
59241 Mem *pEnd;
59242 sqlite3 *db = p->db;
59243 u8 malloc_failed = db->mallocFailed;
59244 if( db->pnBytesFreed ){
59245 for(pEnd=&p[N]; p<pEnd; p++){
59246 sqlite3DbFree(db, p->zMalloc);
59248 return;
59250 for(pEnd=&p[N]; p<pEnd; p++){
59251 assert( (&p[1])==pEnd || p[0].db==p[1].db );
59253 /* This block is really an inlined version of sqlite3VdbeMemRelease()
59254 ** that takes advantage of the fact that the memory cell value is
59255 ** being set to NULL after releasing any dynamic resources.
59257 ** The justification for duplicating code is that according to
59258 ** callgrind, this causes a certain test case to hit the CPU 4.7
59259 ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
59260 ** sqlite3MemRelease() were called from here. With -O2, this jumps
59261 ** to 6.6 percent. The test case is inserting 1000 rows into a table
59262 ** with no indexes using a single prepared INSERT statement, bind()
59263 ** and reset(). Inserts are grouped into a transaction.
59265 if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
59266 sqlite3VdbeMemRelease(p);
59267 }else if( p->zMalloc ){
59268 sqlite3DbFree(db, p->zMalloc);
59269 p->zMalloc = 0;
59272 p->flags = MEM_Null;
59274 db->mallocFailed = malloc_failed;
59279 ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
59280 ** allocated by the OP_Program opcode in sqlite3VdbeExec().
59282 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
59283 int i;
59284 Mem *aMem = VdbeFrameMem(p);
59285 VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
59286 for(i=0; i<p->nChildCsr; i++){
59287 sqlite3VdbeFreeCursor(p->v, apCsr[i]);
59289 releaseMemArray(aMem, p->nChildMem);
59290 sqlite3DbFree(p->v->db, p);
59293 #ifndef SQLITE_OMIT_EXPLAIN
59295 ** Give a listing of the program in the virtual machine.
59297 ** The interface is the same as sqlite3VdbeExec(). But instead of
59298 ** running the code, it invokes the callback once for each instruction.
59299 ** This feature is used to implement "EXPLAIN".
59301 ** When p->explain==1, each instruction is listed. When
59302 ** p->explain==2, only OP_Explain instructions are listed and these
59303 ** are shown in a different format. p->explain==2 is used to implement
59304 ** EXPLAIN QUERY PLAN.
59306 ** When p->explain==1, first the main program is listed, then each of
59307 ** the trigger subprograms are listed one by one.
59309 SQLITE_PRIVATE int sqlite3VdbeList(
59310 Vdbe *p /* The VDBE */
59312 int nRow; /* Stop when row count reaches this */
59313 int nSub = 0; /* Number of sub-vdbes seen so far */
59314 SubProgram **apSub = 0; /* Array of sub-vdbes */
59315 Mem *pSub = 0; /* Memory cell hold array of subprogs */
59316 sqlite3 *db = p->db; /* The database connection */
59317 int i; /* Loop counter */
59318 int rc = SQLITE_OK; /* Return code */
59319 Mem *pMem = &p->aMem[1]; /* First Mem of result set */
59321 assert( p->explain );
59322 assert( p->magic==VDBE_MAGIC_RUN );
59323 assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
59325 /* Even though this opcode does not use dynamic strings for
59326 ** the result, result columns may become dynamic if the user calls
59327 ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
59329 releaseMemArray(pMem, 8);
59330 p->pResultSet = 0;
59332 if( p->rc==SQLITE_NOMEM ){
59333 /* This happens if a malloc() inside a call to sqlite3_column_text() or
59334 ** sqlite3_column_text16() failed. */
59335 db->mallocFailed = 1;
59336 return SQLITE_ERROR;
59339 /* When the number of output rows reaches nRow, that means the
59340 ** listing has finished and sqlite3_step() should return SQLITE_DONE.
59341 ** nRow is the sum of the number of rows in the main program, plus
59342 ** the sum of the number of rows in all trigger subprograms encountered
59343 ** so far. The nRow value will increase as new trigger subprograms are
59344 ** encountered, but p->pc will eventually catch up to nRow.
59346 nRow = p->nOp;
59347 if( p->explain==1 ){
59348 /* The first 8 memory cells are used for the result set. So we will
59349 ** commandeer the 9th cell to use as storage for an array of pointers
59350 ** to trigger subprograms. The VDBE is guaranteed to have at least 9
59351 ** cells. */
59352 assert( p->nMem>9 );
59353 pSub = &p->aMem[9];
59354 if( pSub->flags&MEM_Blob ){
59355 /* On the first call to sqlite3_step(), pSub will hold a NULL. It is
59356 ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
59357 nSub = pSub->n/sizeof(Vdbe*);
59358 apSub = (SubProgram **)pSub->z;
59360 for(i=0; i<nSub; i++){
59361 nRow += apSub[i]->nOp;
59366 i = p->pc++;
59367 }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
59368 if( i>=nRow ){
59369 p->rc = SQLITE_OK;
59370 rc = SQLITE_DONE;
59371 }else if( db->u1.isInterrupted ){
59372 p->rc = SQLITE_INTERRUPT;
59373 rc = SQLITE_ERROR;
59374 sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
59375 }else{
59376 char *z;
59377 Op *pOp;
59378 if( i<p->nOp ){
59379 /* The output line number is small enough that we are still in the
59380 ** main program. */
59381 pOp = &p->aOp[i];
59382 }else{
59383 /* We are currently listing subprograms. Figure out which one and
59384 ** pick up the appropriate opcode. */
59385 int j;
59386 i -= p->nOp;
59387 for(j=0; i>=apSub[j]->nOp; j++){
59388 i -= apSub[j]->nOp;
59390 pOp = &apSub[j]->aOp[i];
59392 if( p->explain==1 ){
59393 pMem->flags = MEM_Int;
59394 pMem->type = SQLITE_INTEGER;
59395 pMem->u.i = i; /* Program counter */
59396 pMem++;
59398 pMem->flags = MEM_Static|MEM_Str|MEM_Term;
59399 pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
59400 assert( pMem->z!=0 );
59401 pMem->n = sqlite3Strlen30(pMem->z);
59402 pMem->type = SQLITE_TEXT;
59403 pMem->enc = SQLITE_UTF8;
59404 pMem++;
59406 /* When an OP_Program opcode is encounter (the only opcode that has
59407 ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
59408 ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
59409 ** has not already been seen.
59411 if( pOp->p4type==P4_SUBPROGRAM ){
59412 int nByte = (nSub+1)*sizeof(SubProgram*);
59413 int j;
59414 for(j=0; j<nSub; j++){
59415 if( apSub[j]==pOp->p4.pProgram ) break;
59417 if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, 1) ){
59418 apSub = (SubProgram **)pSub->z;
59419 apSub[nSub++] = pOp->p4.pProgram;
59420 pSub->flags |= MEM_Blob;
59421 pSub->n = nSub*sizeof(SubProgram*);
59426 pMem->flags = MEM_Int;
59427 pMem->u.i = pOp->p1; /* P1 */
59428 pMem->type = SQLITE_INTEGER;
59429 pMem++;
59431 pMem->flags = MEM_Int;
59432 pMem->u.i = pOp->p2; /* P2 */
59433 pMem->type = SQLITE_INTEGER;
59434 pMem++;
59436 pMem->flags = MEM_Int;
59437 pMem->u.i = pOp->p3; /* P3 */
59438 pMem->type = SQLITE_INTEGER;
59439 pMem++;
59441 if( sqlite3VdbeMemGrow(pMem, 32, 0) ){ /* P4 */
59442 assert( p->db->mallocFailed );
59443 return SQLITE_ERROR;
59445 pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
59446 z = displayP4(pOp, pMem->z, 32);
59447 if( z!=pMem->z ){
59448 sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0);
59449 }else{
59450 assert( pMem->z!=0 );
59451 pMem->n = sqlite3Strlen30(pMem->z);
59452 pMem->enc = SQLITE_UTF8;
59454 pMem->type = SQLITE_TEXT;
59455 pMem++;
59457 if( p->explain==1 ){
59458 if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
59459 assert( p->db->mallocFailed );
59460 return SQLITE_ERROR;
59462 pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
59463 pMem->n = 2;
59464 sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5); /* P5 */
59465 pMem->type = SQLITE_TEXT;
59466 pMem->enc = SQLITE_UTF8;
59467 pMem++;
59469 #ifdef SQLITE_DEBUG
59470 if( pOp->zComment ){
59471 pMem->flags = MEM_Str|MEM_Term;
59472 pMem->z = pOp->zComment;
59473 pMem->n = sqlite3Strlen30(pMem->z);
59474 pMem->enc = SQLITE_UTF8;
59475 pMem->type = SQLITE_TEXT;
59476 }else
59477 #endif
59479 pMem->flags = MEM_Null; /* Comment */
59480 pMem->type = SQLITE_NULL;
59484 p->nResColumn = 8 - 4*(p->explain-1);
59485 p->pResultSet = &p->aMem[1];
59486 p->rc = SQLITE_OK;
59487 rc = SQLITE_ROW;
59489 return rc;
59491 #endif /* SQLITE_OMIT_EXPLAIN */
59493 #ifdef SQLITE_DEBUG
59495 ** Print the SQL that was used to generate a VDBE program.
59497 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
59498 int nOp = p->nOp;
59499 VdbeOp *pOp;
59500 if( nOp<1 ) return;
59501 pOp = &p->aOp[0];
59502 if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
59503 const char *z = pOp->p4.z;
59504 while( sqlite3Isspace(*z) ) z++;
59505 printf("SQL: [%s]\n", z);
59508 #endif
59510 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
59512 ** Print an IOTRACE message showing SQL content.
59514 SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
59515 int nOp = p->nOp;
59516 VdbeOp *pOp;
59517 if( sqlite3IoTrace==0 ) return;
59518 if( nOp<1 ) return;
59519 pOp = &p->aOp[0];
59520 if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
59521 int i, j;
59522 char z[1000];
59523 sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
59524 for(i=0; sqlite3Isspace(z[i]); i++){}
59525 for(j=0; z[i]; i++){
59526 if( sqlite3Isspace(z[i]) ){
59527 if( z[i-1]!=' ' ){
59528 z[j++] = ' ';
59530 }else{
59531 z[j++] = z[i];
59534 z[j] = 0;
59535 sqlite3IoTrace("SQL %s\n", z);
59538 #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
59541 ** Allocate space from a fixed size buffer and return a pointer to
59542 ** that space. If insufficient space is available, return NULL.
59544 ** The pBuf parameter is the initial value of a pointer which will
59545 ** receive the new memory. pBuf is normally NULL. If pBuf is not
59546 ** NULL, it means that memory space has already been allocated and that
59547 ** this routine should not allocate any new memory. When pBuf is not
59548 ** NULL simply return pBuf. Only allocate new memory space when pBuf
59549 ** is NULL.
59551 ** nByte is the number of bytes of space needed.
59553 ** *ppFrom points to available space and pEnd points to the end of the
59554 ** available space. When space is allocated, *ppFrom is advanced past
59555 ** the end of the allocated space.
59557 ** *pnByte is a counter of the number of bytes of space that have failed
59558 ** to allocate. If there is insufficient space in *ppFrom to satisfy the
59559 ** request, then increment *pnByte by the amount of the request.
59561 static void *allocSpace(
59562 void *pBuf, /* Where return pointer will be stored */
59563 int nByte, /* Number of bytes to allocate */
59564 u8 **ppFrom, /* IN/OUT: Allocate from *ppFrom */
59565 u8 *pEnd, /* Pointer to 1 byte past the end of *ppFrom buffer */
59566 int *pnByte /* If allocation cannot be made, increment *pnByte */
59568 assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
59569 if( pBuf ) return pBuf;
59570 nByte = ROUND8(nByte);
59571 if( &(*ppFrom)[nByte] <= pEnd ){
59572 pBuf = (void*)*ppFrom;
59573 *ppFrom += nByte;
59574 }else{
59575 *pnByte += nByte;
59577 return pBuf;
59581 ** Rewind the VDBE back to the beginning in preparation for
59582 ** running it.
59584 SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
59585 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
59586 int i;
59587 #endif
59588 assert( p!=0 );
59589 assert( p->magic==VDBE_MAGIC_INIT );
59591 /* There should be at least one opcode.
59593 assert( p->nOp>0 );
59595 /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
59596 p->magic = VDBE_MAGIC_RUN;
59598 #ifdef SQLITE_DEBUG
59599 for(i=1; i<p->nMem; i++){
59600 assert( p->aMem[i].db==p->db );
59602 #endif
59603 p->pc = -1;
59604 p->rc = SQLITE_OK;
59605 p->errorAction = OE_Abort;
59606 p->magic = VDBE_MAGIC_RUN;
59607 p->nChange = 0;
59608 p->cacheCtr = 1;
59609 p->minWriteFileFormat = 255;
59610 p->iStatement = 0;
59611 p->nFkConstraint = 0;
59612 #ifdef VDBE_PROFILE
59613 for(i=0; i<p->nOp; i++){
59614 p->aOp[i].cnt = 0;
59615 p->aOp[i].cycles = 0;
59617 #endif
59621 ** Prepare a virtual machine for execution for the first time after
59622 ** creating the virtual machine. This involves things such
59623 ** as allocating stack space and initializing the program counter.
59624 ** After the VDBE has be prepped, it can be executed by one or more
59625 ** calls to sqlite3VdbeExec().
59627 ** This function may be called exact once on a each virtual machine.
59628 ** After this routine is called the VM has been "packaged" and is ready
59629 ** to run. After this routine is called, futher calls to
59630 ** sqlite3VdbeAddOp() functions are prohibited. This routine disconnects
59631 ** the Vdbe from the Parse object that helped generate it so that the
59632 ** the Vdbe becomes an independent entity and the Parse object can be
59633 ** destroyed.
59635 ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
59636 ** to its initial state after it has been run.
59638 SQLITE_PRIVATE void sqlite3VdbeMakeReady(
59639 Vdbe *p, /* The VDBE */
59640 Parse *pParse /* Parsing context */
59642 sqlite3 *db; /* The database connection */
59643 int nVar; /* Number of parameters */
59644 int nMem; /* Number of VM memory registers */
59645 int nCursor; /* Number of cursors required */
59646 int nArg; /* Number of arguments in subprograms */
59647 int n; /* Loop counter */
59648 u8 *zCsr; /* Memory available for allocation */
59649 u8 *zEnd; /* First byte past allocated memory */
59650 int nByte; /* How much extra memory is needed */
59652 assert( p!=0 );
59653 assert( p->nOp>0 );
59654 assert( pParse!=0 );
59655 assert( p->magic==VDBE_MAGIC_INIT );
59656 db = p->db;
59657 assert( db->mallocFailed==0 );
59658 nVar = pParse->nVar;
59659 nMem = pParse->nMem;
59660 nCursor = pParse->nTab;
59661 nArg = pParse->nMaxArg;
59663 /* For each cursor required, also allocate a memory cell. Memory
59664 ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
59665 ** the vdbe program. Instead they are used to allocate space for
59666 ** VdbeCursor/BtCursor structures. The blob of memory associated with
59667 ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
59668 ** stores the blob of memory associated with cursor 1, etc.
59670 ** See also: allocateCursor().
59672 nMem += nCursor;
59674 /* Allocate space for memory registers, SQL variables, VDBE cursors and
59675 ** an array to marshal SQL function arguments in.
59677 zCsr = (u8*)&p->aOp[p->nOp]; /* Memory avaliable for allocation */
59678 zEnd = (u8*)&p->aOp[p->nOpAlloc]; /* First byte past end of zCsr[] */
59680 resolveP2Values(p, &nArg);
59681 p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
59682 if( pParse->explain && nMem<10 ){
59683 nMem = 10;
59685 memset(zCsr, 0, zEnd-zCsr);
59686 zCsr += (zCsr - (u8*)0)&7;
59687 assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
59688 p->expired = 0;
59690 /* Memory for registers, parameters, cursor, etc, is allocated in two
59691 ** passes. On the first pass, we try to reuse unused space at the
59692 ** end of the opcode array. If we are unable to satisfy all memory
59693 ** requirements by reusing the opcode array tail, then the second
59694 ** pass will fill in the rest using a fresh allocation.
59696 ** This two-pass approach that reuses as much memory as possible from
59697 ** the leftover space at the end of the opcode array can significantly
59698 ** reduce the amount of memory held by a prepared statement.
59700 do {
59701 nByte = 0;
59702 p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
59703 p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
59704 p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
59705 p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
59706 p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
59707 &zCsr, zEnd, &nByte);
59708 if( nByte ){
59709 p->pFree = sqlite3DbMallocZero(db, nByte);
59711 zCsr = p->pFree;
59712 zEnd = &zCsr[nByte];
59713 }while( nByte && !db->mallocFailed );
59715 p->nCursor = (u16)nCursor;
59716 if( p->aVar ){
59717 p->nVar = (ynVar)nVar;
59718 for(n=0; n<nVar; n++){
59719 p->aVar[n].flags = MEM_Null;
59720 p->aVar[n].db = db;
59723 if( p->azVar ){
59724 p->nzVar = pParse->nzVar;
59725 memcpy(p->azVar, pParse->azVar, p->nzVar*sizeof(p->azVar[0]));
59726 memset(pParse->azVar, 0, pParse->nzVar*sizeof(pParse->azVar[0]));
59728 if( p->aMem ){
59729 p->aMem--; /* aMem[] goes from 1..nMem */
59730 p->nMem = nMem; /* not from 0..nMem-1 */
59731 for(n=1; n<=nMem; n++){
59732 p->aMem[n].flags = MEM_Null;
59733 p->aMem[n].db = db;
59736 p->explain = pParse->explain;
59737 sqlite3VdbeRewind(p);
59741 ** Close a VDBE cursor and release all the resources that cursor
59742 ** happens to hold.
59744 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
59745 if( pCx==0 ){
59746 return;
59748 sqlite3VdbeSorterClose(p->db, pCx);
59749 if( pCx->pBt ){
59750 sqlite3BtreeClose(pCx->pBt);
59751 /* The pCx->pCursor will be close automatically, if it exists, by
59752 ** the call above. */
59753 }else if( pCx->pCursor ){
59754 sqlite3BtreeCloseCursor(pCx->pCursor);
59756 #ifndef SQLITE_OMIT_VIRTUALTABLE
59757 if( pCx->pVtabCursor ){
59758 sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
59759 const sqlite3_module *pModule = pCx->pModule;
59760 p->inVtabMethod = 1;
59761 pModule->xClose(pVtabCursor);
59762 p->inVtabMethod = 0;
59764 #endif
59768 ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
59769 ** is used, for example, when a trigger sub-program is halted to restore
59770 ** control to the main program.
59772 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
59773 Vdbe *v = pFrame->v;
59774 v->aOp = pFrame->aOp;
59775 v->nOp = pFrame->nOp;
59776 v->aMem = pFrame->aMem;
59777 v->nMem = pFrame->nMem;
59778 v->apCsr = pFrame->apCsr;
59779 v->nCursor = pFrame->nCursor;
59780 v->db->lastRowid = pFrame->lastRowid;
59781 v->nChange = pFrame->nChange;
59782 return pFrame->pc;
59786 ** Close all cursors.
59788 ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
59789 ** cell array. This is necessary as the memory cell array may contain
59790 ** pointers to VdbeFrame objects, which may in turn contain pointers to
59791 ** open cursors.
59793 static void closeAllCursors(Vdbe *p){
59794 if( p->pFrame ){
59795 VdbeFrame *pFrame;
59796 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
59797 sqlite3VdbeFrameRestore(pFrame);
59799 p->pFrame = 0;
59800 p->nFrame = 0;
59802 if( p->apCsr ){
59803 int i;
59804 for(i=0; i<p->nCursor; i++){
59805 VdbeCursor *pC = p->apCsr[i];
59806 if( pC ){
59807 sqlite3VdbeFreeCursor(p, pC);
59808 p->apCsr[i] = 0;
59812 if( p->aMem ){
59813 releaseMemArray(&p->aMem[1], p->nMem);
59815 while( p->pDelFrame ){
59816 VdbeFrame *pDel = p->pDelFrame;
59817 p->pDelFrame = pDel->pParent;
59818 sqlite3VdbeFrameDelete(pDel);
59823 ** Clean up the VM after execution.
59825 ** This routine will automatically close any cursors, lists, and/or
59826 ** sorters that were left open. It also deletes the values of
59827 ** variables in the aVar[] array.
59829 static void Cleanup(Vdbe *p){
59830 sqlite3 *db = p->db;
59832 #ifdef SQLITE_DEBUG
59833 /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
59834 ** Vdbe.aMem[] arrays have already been cleaned up. */
59835 int i;
59836 for(i=0; i<p->nCursor; i++) assert( p->apCsr==0 || p->apCsr[i]==0 );
59837 for(i=1; i<=p->nMem; i++) assert( p->aMem==0 || p->aMem[i].flags==MEM_Null );
59838 #endif
59840 sqlite3DbFree(db, p->zErrMsg);
59841 p->zErrMsg = 0;
59842 p->pResultSet = 0;
59846 ** Set the number of result columns that will be returned by this SQL
59847 ** statement. This is now set at compile time, rather than during
59848 ** execution of the vdbe program so that sqlite3_column_count() can
59849 ** be called on an SQL statement before sqlite3_step().
59851 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
59852 Mem *pColName;
59853 int n;
59854 sqlite3 *db = p->db;
59856 releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
59857 sqlite3DbFree(db, p->aColName);
59858 n = nResColumn*COLNAME_N;
59859 p->nResColumn = (u16)nResColumn;
59860 p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
59861 if( p->aColName==0 ) return;
59862 while( n-- > 0 ){
59863 pColName->flags = MEM_Null;
59864 pColName->db = p->db;
59865 pColName++;
59870 ** Set the name of the idx'th column to be returned by the SQL statement.
59871 ** zName must be a pointer to a nul terminated string.
59873 ** This call must be made after a call to sqlite3VdbeSetNumCols().
59875 ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
59876 ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
59877 ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
59879 SQLITE_PRIVATE int sqlite3VdbeSetColName(
59880 Vdbe *p, /* Vdbe being configured */
59881 int idx, /* Index of column zName applies to */
59882 int var, /* One of the COLNAME_* constants */
59883 const char *zName, /* Pointer to buffer containing name */
59884 void (*xDel)(void*) /* Memory management strategy for zName */
59886 int rc;
59887 Mem *pColName;
59888 assert( idx<p->nResColumn );
59889 assert( var<COLNAME_N );
59890 if( p->db->mallocFailed ){
59891 assert( !zName || xDel!=SQLITE_DYNAMIC );
59892 return SQLITE_NOMEM;
59894 assert( p->aColName!=0 );
59895 pColName = &(p->aColName[idx+var*p->nResColumn]);
59896 rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
59897 assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
59898 return rc;
59902 ** A read or write transaction may or may not be active on database handle
59903 ** db. If a transaction is active, commit it. If there is a
59904 ** write-transaction spanning more than one database file, this routine
59905 ** takes care of the master journal trickery.
59907 static int vdbeCommit(sqlite3 *db, Vdbe *p){
59908 int i;
59909 int nTrans = 0; /* Number of databases with an active write-transaction */
59910 int rc = SQLITE_OK;
59911 int needXcommit = 0;
59913 #ifdef SQLITE_OMIT_VIRTUALTABLE
59914 /* With this option, sqlite3VtabSync() is defined to be simply
59915 ** SQLITE_OK so p is not used.
59917 UNUSED_PARAMETER(p);
59918 #endif
59920 /* Before doing anything else, call the xSync() callback for any
59921 ** virtual module tables written in this transaction. This has to
59922 ** be done before determining whether a master journal file is
59923 ** required, as an xSync() callback may add an attached database
59924 ** to the transaction.
59926 rc = sqlite3VtabSync(db, &p->zErrMsg);
59928 /* This loop determines (a) if the commit hook should be invoked and
59929 ** (b) how many database files have open write transactions, not
59930 ** including the temp database. (b) is important because if more than
59931 ** one database file has an open write transaction, a master journal
59932 ** file is required for an atomic commit.
59934 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
59935 Btree *pBt = db->aDb[i].pBt;
59936 if( sqlite3BtreeIsInTrans(pBt) ){
59937 needXcommit = 1;
59938 if( i!=1 ) nTrans++;
59939 rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
59942 if( rc!=SQLITE_OK ){
59943 return rc;
59946 /* If there are any write-transactions at all, invoke the commit hook */
59947 if( needXcommit && db->xCommitCallback ){
59948 rc = db->xCommitCallback(db->pCommitArg);
59949 if( rc ){
59950 return SQLITE_CONSTRAINT;
59954 /* The simple case - no more than one database file (not counting the
59955 ** TEMP database) has a transaction active. There is no need for the
59956 ** master-journal.
59958 ** If the return value of sqlite3BtreeGetFilename() is a zero length
59959 ** string, it means the main database is :memory: or a temp file. In
59960 ** that case we do not support atomic multi-file commits, so use the
59961 ** simple case then too.
59963 if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
59964 || nTrans<=1
59966 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
59967 Btree *pBt = db->aDb[i].pBt;
59968 if( pBt ){
59969 rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
59973 /* Do the commit only if all databases successfully complete phase 1.
59974 ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
59975 ** IO error while deleting or truncating a journal file. It is unlikely,
59976 ** but could happen. In this case abandon processing and return the error.
59978 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
59979 Btree *pBt = db->aDb[i].pBt;
59980 if( pBt ){
59981 rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
59984 if( rc==SQLITE_OK ){
59985 sqlite3VtabCommit(db);
59989 /* The complex case - There is a multi-file write-transaction active.
59990 ** This requires a master journal file to ensure the transaction is
59991 ** committed atomicly.
59993 #ifndef SQLITE_OMIT_DISKIO
59994 else{
59995 sqlite3_vfs *pVfs = db->pVfs;
59996 int needSync = 0;
59997 char *zMaster = 0; /* File-name for the master journal */
59998 char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
59999 sqlite3_file *pMaster = 0;
60000 i64 offset = 0;
60001 int res;
60003 /* Select a master journal file name */
60004 do {
60005 u32 iRandom;
60006 sqlite3DbFree(db, zMaster);
60007 sqlite3_randomness(sizeof(iRandom), &iRandom);
60008 zMaster = sqlite3MPrintf(db, "%s-mj%08X", zMainFile, iRandom&0x7fffffff);
60009 if( !zMaster ){
60010 return SQLITE_NOMEM;
60012 sqlite3FileSuffix3(zMainFile, zMaster);
60013 rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
60014 }while( rc==SQLITE_OK && res );
60015 if( rc==SQLITE_OK ){
60016 /* Open the master journal. */
60017 rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
60018 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
60019 SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
60022 if( rc!=SQLITE_OK ){
60023 sqlite3DbFree(db, zMaster);
60024 return rc;
60027 /* Write the name of each database file in the transaction into the new
60028 ** master journal file. If an error occurs at this point close
60029 ** and delete the master journal file. All the individual journal files
60030 ** still have 'null' as the master journal pointer, so they will roll
60031 ** back independently if a failure occurs.
60033 for(i=0; i<db->nDb; i++){
60034 Btree *pBt = db->aDb[i].pBt;
60035 if( sqlite3BtreeIsInTrans(pBt) ){
60036 char const *zFile = sqlite3BtreeGetJournalname(pBt);
60037 if( zFile==0 ){
60038 continue; /* Ignore TEMP and :memory: databases */
60040 assert( zFile[0]!=0 );
60041 if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
60042 needSync = 1;
60044 rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
60045 offset += sqlite3Strlen30(zFile)+1;
60046 if( rc!=SQLITE_OK ){
60047 sqlite3OsCloseFree(pMaster);
60048 sqlite3OsDelete(pVfs, zMaster, 0);
60049 sqlite3DbFree(db, zMaster);
60050 return rc;
60055 /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
60056 ** flag is set this is not required.
60058 if( needSync
60059 && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
60060 && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
60062 sqlite3OsCloseFree(pMaster);
60063 sqlite3OsDelete(pVfs, zMaster, 0);
60064 sqlite3DbFree(db, zMaster);
60065 return rc;
60068 /* Sync all the db files involved in the transaction. The same call
60069 ** sets the master journal pointer in each individual journal. If
60070 ** an error occurs here, do not delete the master journal file.
60072 ** If the error occurs during the first call to
60073 ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
60074 ** master journal file will be orphaned. But we cannot delete it,
60075 ** in case the master journal file name was written into the journal
60076 ** file before the failure occurred.
60078 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
60079 Btree *pBt = db->aDb[i].pBt;
60080 if( pBt ){
60081 rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
60084 sqlite3OsCloseFree(pMaster);
60085 assert( rc!=SQLITE_BUSY );
60086 if( rc!=SQLITE_OK ){
60087 sqlite3DbFree(db, zMaster);
60088 return rc;
60091 /* Delete the master journal file. This commits the transaction. After
60092 ** doing this the directory is synced again before any individual
60093 ** transaction files are deleted.
60095 rc = sqlite3OsDelete(pVfs, zMaster, 1);
60096 sqlite3DbFree(db, zMaster);
60097 zMaster = 0;
60098 if( rc ){
60099 return rc;
60102 /* All files and directories have already been synced, so the following
60103 ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
60104 ** deleting or truncating journals. If something goes wrong while
60105 ** this is happening we don't really care. The integrity of the
60106 ** transaction is already guaranteed, but some stray 'cold' journals
60107 ** may be lying around. Returning an error code won't help matters.
60109 disable_simulated_io_errors();
60110 sqlite3BeginBenignMalloc();
60111 for(i=0; i<db->nDb; i++){
60112 Btree *pBt = db->aDb[i].pBt;
60113 if( pBt ){
60114 sqlite3BtreeCommitPhaseTwo(pBt, 1);
60117 sqlite3EndBenignMalloc();
60118 enable_simulated_io_errors();
60120 sqlite3VtabCommit(db);
60122 #endif
60124 return rc;
60128 ** This routine checks that the sqlite3.activeVdbeCnt count variable
60129 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
60130 ** currently active. An assertion fails if the two counts do not match.
60131 ** This is an internal self-check only - it is not an essential processing
60132 ** step.
60134 ** This is a no-op if NDEBUG is defined.
60136 #ifndef NDEBUG
60137 static void checkActiveVdbeCnt(sqlite3 *db){
60138 Vdbe *p;
60139 int cnt = 0;
60140 int nWrite = 0;
60141 p = db->pVdbe;
60142 while( p ){
60143 if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
60144 cnt++;
60145 if( p->readOnly==0 ) nWrite++;
60147 p = p->pNext;
60149 assert( cnt==db->activeVdbeCnt );
60150 assert( nWrite==db->writeVdbeCnt );
60152 #else
60153 #define checkActiveVdbeCnt(x)
60154 #endif
60157 ** For every Btree that in database connection db which
60158 ** has been modified, "trip" or invalidate each cursor in
60159 ** that Btree might have been modified so that the cursor
60160 ** can never be used again. This happens when a rollback
60161 *** occurs. We have to trip all the other cursors, even
60162 ** cursor from other VMs in different database connections,
60163 ** so that none of them try to use the data at which they
60164 ** were pointing and which now may have been changed due
60165 ** to the rollback.
60167 ** Remember that a rollback can delete tables complete and
60168 ** reorder rootpages. So it is not sufficient just to save
60169 ** the state of the cursor. We have to invalidate the cursor
60170 ** so that it is never used again.
60172 static void invalidateCursorsOnModifiedBtrees(sqlite3 *db){
60173 int i;
60174 for(i=0; i<db->nDb; i++){
60175 Btree *p = db->aDb[i].pBt;
60176 if( p && sqlite3BtreeIsInTrans(p) ){
60177 sqlite3BtreeTripAllCursors(p, SQLITE_ABORT);
60183 ** If the Vdbe passed as the first argument opened a statement-transaction,
60184 ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
60185 ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
60186 ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
60187 ** statement transaction is commtted.
60189 ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
60190 ** Otherwise SQLITE_OK.
60192 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
60193 sqlite3 *const db = p->db;
60194 int rc = SQLITE_OK;
60196 /* If p->iStatement is greater than zero, then this Vdbe opened a
60197 ** statement transaction that should be closed here. The only exception
60198 ** is that an IO error may have occured, causing an emergency rollback.
60199 ** In this case (db->nStatement==0), and there is nothing to do.
60201 if( db->nStatement && p->iStatement ){
60202 int i;
60203 const int iSavepoint = p->iStatement-1;
60205 assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
60206 assert( db->nStatement>0 );
60207 assert( p->iStatement==(db->nStatement+db->nSavepoint) );
60209 for(i=0; i<db->nDb; i++){
60210 int rc2 = SQLITE_OK;
60211 Btree *pBt = db->aDb[i].pBt;
60212 if( pBt ){
60213 if( eOp==SAVEPOINT_ROLLBACK ){
60214 rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
60216 if( rc2==SQLITE_OK ){
60217 rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
60219 if( rc==SQLITE_OK ){
60220 rc = rc2;
60224 db->nStatement--;
60225 p->iStatement = 0;
60227 if( rc==SQLITE_OK ){
60228 if( eOp==SAVEPOINT_ROLLBACK ){
60229 rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
60231 if( rc==SQLITE_OK ){
60232 rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
60236 /* If the statement transaction is being rolled back, also restore the
60237 ** database handles deferred constraint counter to the value it had when
60238 ** the statement transaction was opened. */
60239 if( eOp==SAVEPOINT_ROLLBACK ){
60240 db->nDeferredCons = p->nStmtDefCons;
60243 return rc;
60247 ** This function is called when a transaction opened by the database
60248 ** handle associated with the VM passed as an argument is about to be
60249 ** committed. If there are outstanding deferred foreign key constraint
60250 ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
60252 ** If there are outstanding FK violations and this function returns
60253 ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT and write
60254 ** an error message to it. Then return SQLITE_ERROR.
60256 #ifndef SQLITE_OMIT_FOREIGN_KEY
60257 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
60258 sqlite3 *db = p->db;
60259 if( (deferred && db->nDeferredCons>0) || (!deferred && p->nFkConstraint>0) ){
60260 p->rc = SQLITE_CONSTRAINT;
60261 p->errorAction = OE_Abort;
60262 sqlite3SetString(&p->zErrMsg, db, "foreign key constraint failed");
60263 return SQLITE_ERROR;
60265 return SQLITE_OK;
60267 #endif
60270 ** This routine is called the when a VDBE tries to halt. If the VDBE
60271 ** has made changes and is in autocommit mode, then commit those
60272 ** changes. If a rollback is needed, then do the rollback.
60274 ** This routine is the only way to move the state of a VM from
60275 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT. It is harmless to
60276 ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
60278 ** Return an error code. If the commit could not complete because of
60279 ** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it
60280 ** means the close did not happen and needs to be repeated.
60282 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
60283 int rc; /* Used to store transient return codes */
60284 sqlite3 *db = p->db;
60286 /* This function contains the logic that determines if a statement or
60287 ** transaction will be committed or rolled back as a result of the
60288 ** execution of this virtual machine.
60290 ** If any of the following errors occur:
60292 ** SQLITE_NOMEM
60293 ** SQLITE_IOERR
60294 ** SQLITE_FULL
60295 ** SQLITE_INTERRUPT
60297 ** Then the internal cache might have been left in an inconsistent
60298 ** state. We need to rollback the statement transaction, if there is
60299 ** one, or the complete transaction if there is no statement transaction.
60302 if( p->db->mallocFailed ){
60303 p->rc = SQLITE_NOMEM;
60305 closeAllCursors(p);
60306 if( p->magic!=VDBE_MAGIC_RUN ){
60307 return SQLITE_OK;
60309 checkActiveVdbeCnt(db);
60311 /* No commit or rollback needed if the program never started */
60312 if( p->pc>=0 ){
60313 int mrc; /* Primary error code from p->rc */
60314 int eStatementOp = 0;
60315 int isSpecialError; /* Set to true if a 'special' error */
60317 /* Lock all btrees used by the statement */
60318 sqlite3VdbeEnter(p);
60320 /* Check for one of the special errors */
60321 mrc = p->rc & 0xff;
60322 assert( p->rc!=SQLITE_IOERR_BLOCKED ); /* This error no longer exists */
60323 isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
60324 || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
60325 if( isSpecialError ){
60326 /* If the query was read-only and the error code is SQLITE_INTERRUPT,
60327 ** no rollback is necessary. Otherwise, at least a savepoint
60328 ** transaction must be rolled back to restore the database to a
60329 ** consistent state.
60331 ** Even if the statement is read-only, it is important to perform
60332 ** a statement or transaction rollback operation. If the error
60333 ** occured while writing to the journal, sub-journal or database
60334 ** file as part of an effort to free up cache space (see function
60335 ** pagerStress() in pager.c), the rollback is required to restore
60336 ** the pager to a consistent state.
60338 if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
60339 if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
60340 eStatementOp = SAVEPOINT_ROLLBACK;
60341 }else{
60342 /* We are forced to roll back the active transaction. Before doing
60343 ** so, abort any other statements this handle currently has active.
60345 invalidateCursorsOnModifiedBtrees(db);
60346 sqlite3RollbackAll(db);
60347 sqlite3CloseSavepoints(db);
60348 db->autoCommit = 1;
60353 /* Check for immediate foreign key violations. */
60354 if( p->rc==SQLITE_OK ){
60355 sqlite3VdbeCheckFk(p, 0);
60358 /* If the auto-commit flag is set and this is the only active writer
60359 ** VM, then we do either a commit or rollback of the current transaction.
60361 ** Note: This block also runs if one of the special errors handled
60362 ** above has occurred.
60364 if( !sqlite3VtabInSync(db)
60365 && db->autoCommit
60366 && db->writeVdbeCnt==(p->readOnly==0)
60368 if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
60369 rc = sqlite3VdbeCheckFk(p, 1);
60370 if( rc!=SQLITE_OK ){
60371 if( NEVER(p->readOnly) ){
60372 sqlite3VdbeLeave(p);
60373 return SQLITE_ERROR;
60375 rc = SQLITE_CONSTRAINT;
60376 }else{
60377 /* The auto-commit flag is true, the vdbe program was successful
60378 ** or hit an 'OR FAIL' constraint and there are no deferred foreign
60379 ** key constraints to hold up the transaction. This means a commit
60380 ** is required. */
60381 rc = vdbeCommit(db, p);
60383 if( rc==SQLITE_BUSY && p->readOnly ){
60384 sqlite3VdbeLeave(p);
60385 return SQLITE_BUSY;
60386 }else if( rc!=SQLITE_OK ){
60387 p->rc = rc;
60388 sqlite3RollbackAll(db);
60389 }else{
60390 db->nDeferredCons = 0;
60391 sqlite3CommitInternalChanges(db);
60393 }else{
60394 sqlite3RollbackAll(db);
60396 db->nStatement = 0;
60397 }else if( eStatementOp==0 ){
60398 if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
60399 eStatementOp = SAVEPOINT_RELEASE;
60400 }else if( p->errorAction==OE_Abort ){
60401 eStatementOp = SAVEPOINT_ROLLBACK;
60402 }else{
60403 invalidateCursorsOnModifiedBtrees(db);
60404 sqlite3RollbackAll(db);
60405 sqlite3CloseSavepoints(db);
60406 db->autoCommit = 1;
60410 /* If eStatementOp is non-zero, then a statement transaction needs to
60411 ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
60412 ** do so. If this operation returns an error, and the current statement
60413 ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
60414 ** current statement error code.
60416 if( eStatementOp ){
60417 rc = sqlite3VdbeCloseStatement(p, eStatementOp);
60418 if( rc ){
60419 if( p->rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT ){
60420 p->rc = rc;
60421 sqlite3DbFree(db, p->zErrMsg);
60422 p->zErrMsg = 0;
60424 invalidateCursorsOnModifiedBtrees(db);
60425 sqlite3RollbackAll(db);
60426 sqlite3CloseSavepoints(db);
60427 db->autoCommit = 1;
60431 /* If this was an INSERT, UPDATE or DELETE and no statement transaction
60432 ** has been rolled back, update the database connection change-counter.
60434 if( p->changeCntOn ){
60435 if( eStatementOp!=SAVEPOINT_ROLLBACK ){
60436 sqlite3VdbeSetChanges(db, p->nChange);
60437 }else{
60438 sqlite3VdbeSetChanges(db, 0);
60440 p->nChange = 0;
60443 /* Rollback or commit any schema changes that occurred. */
60444 if( p->rc!=SQLITE_OK && db->flags&SQLITE_InternChanges ){
60445 sqlite3ResetInternalSchema(db, -1);
60446 db->flags = (db->flags | SQLITE_InternChanges);
60449 /* Release the locks */
60450 sqlite3VdbeLeave(p);
60453 /* We have successfully halted and closed the VM. Record this fact. */
60454 if( p->pc>=0 ){
60455 db->activeVdbeCnt--;
60456 if( !p->readOnly ){
60457 db->writeVdbeCnt--;
60459 assert( db->activeVdbeCnt>=db->writeVdbeCnt );
60461 p->magic = VDBE_MAGIC_HALT;
60462 checkActiveVdbeCnt(db);
60463 if( p->db->mallocFailed ){
60464 p->rc = SQLITE_NOMEM;
60467 /* If the auto-commit flag is set to true, then any locks that were held
60468 ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
60469 ** to invoke any required unlock-notify callbacks.
60471 if( db->autoCommit ){
60472 sqlite3ConnectionUnlocked(db);
60475 assert( db->activeVdbeCnt>0 || db->autoCommit==0 || db->nStatement==0 );
60476 return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
60481 ** Each VDBE holds the result of the most recent sqlite3_step() call
60482 ** in p->rc. This routine sets that result back to SQLITE_OK.
60484 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
60485 p->rc = SQLITE_OK;
60489 ** Copy the error code and error message belonging to the VDBE passed
60490 ** as the first argument to its database handle (so that they will be
60491 ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
60493 ** This function does not clear the VDBE error code or message, just
60494 ** copies them to the database handle.
60496 SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
60497 sqlite3 *db = p->db;
60498 int rc = p->rc;
60499 if( p->zErrMsg ){
60500 u8 mallocFailed = db->mallocFailed;
60501 sqlite3BeginBenignMalloc();
60502 sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
60503 sqlite3EndBenignMalloc();
60504 db->mallocFailed = mallocFailed;
60505 db->errCode = rc;
60506 }else{
60507 sqlite3Error(db, rc, 0);
60509 return rc;
60513 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
60514 ** Write any error messages into *pzErrMsg. Return the result code.
60516 ** After this routine is run, the VDBE should be ready to be executed
60517 ** again.
60519 ** To look at it another way, this routine resets the state of the
60520 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
60521 ** VDBE_MAGIC_INIT.
60523 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
60524 sqlite3 *db;
60525 db = p->db;
60527 /* If the VM did not run to completion or if it encountered an
60528 ** error, then it might not have been halted properly. So halt
60529 ** it now.
60531 sqlite3VdbeHalt(p);
60533 /* If the VDBE has be run even partially, then transfer the error code
60534 ** and error message from the VDBE into the main database structure. But
60535 ** if the VDBE has just been set to run but has not actually executed any
60536 ** instructions yet, leave the main database error information unchanged.
60538 if( p->pc>=0 ){
60539 sqlite3VdbeTransferError(p);
60540 sqlite3DbFree(db, p->zErrMsg);
60541 p->zErrMsg = 0;
60542 if( p->runOnlyOnce ) p->expired = 1;
60543 }else if( p->rc && p->expired ){
60544 /* The expired flag was set on the VDBE before the first call
60545 ** to sqlite3_step(). For consistency (since sqlite3_step() was
60546 ** called), set the database error in this case as well.
60548 sqlite3Error(db, p->rc, 0);
60549 sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
60550 sqlite3DbFree(db, p->zErrMsg);
60551 p->zErrMsg = 0;
60554 /* Reclaim all memory used by the VDBE
60556 Cleanup(p);
60558 /* Save profiling information from this VDBE run.
60560 #ifdef VDBE_PROFILE
60562 FILE *out = fopen("vdbe_profile.out", "a");
60563 if( out ){
60564 int i;
60565 fprintf(out, "---- ");
60566 for(i=0; i<p->nOp; i++){
60567 fprintf(out, "%02x", p->aOp[i].opcode);
60569 fprintf(out, "\n");
60570 for(i=0; i<p->nOp; i++){
60571 fprintf(out, "%6d %10lld %8lld ",
60572 p->aOp[i].cnt,
60573 p->aOp[i].cycles,
60574 p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
60576 sqlite3VdbePrintOp(out, i, &p->aOp[i]);
60578 fclose(out);
60581 #endif
60582 p->magic = VDBE_MAGIC_INIT;
60583 return p->rc & db->errMask;
60587 ** Clean up and delete a VDBE after execution. Return an integer which is
60588 ** the result code. Write any error message text into *pzErrMsg.
60590 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
60591 int rc = SQLITE_OK;
60592 if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
60593 rc = sqlite3VdbeReset(p);
60594 assert( (rc & p->db->errMask)==rc );
60596 sqlite3VdbeDelete(p);
60597 return rc;
60601 ** Call the destructor for each auxdata entry in pVdbeFunc for which
60602 ** the corresponding bit in mask is clear. Auxdata entries beyond 31
60603 ** are always destroyed. To destroy all auxdata entries, call this
60604 ** routine with mask==0.
60606 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
60607 int i;
60608 for(i=0; i<pVdbeFunc->nAux; i++){
60609 struct AuxData *pAux = &pVdbeFunc->apAux[i];
60610 if( (i>31 || !(mask&(((u32)1)<<i))) && pAux->pAux ){
60611 if( pAux->xDelete ){
60612 pAux->xDelete(pAux->pAux);
60614 pAux->pAux = 0;
60620 ** Free all memory associated with the Vdbe passed as the second argument.
60621 ** The difference between this function and sqlite3VdbeDelete() is that
60622 ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
60623 ** the database connection.
60625 SQLITE_PRIVATE void sqlite3VdbeDeleteObject(sqlite3 *db, Vdbe *p){
60626 SubProgram *pSub, *pNext;
60627 int i;
60628 assert( p->db==0 || p->db==db );
60629 releaseMemArray(p->aVar, p->nVar);
60630 releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
60631 for(pSub=p->pProgram; pSub; pSub=pNext){
60632 pNext = pSub->pNext;
60633 vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
60634 sqlite3DbFree(db, pSub);
60636 for(i=p->nzVar-1; i>=0; i--) sqlite3DbFree(db, p->azVar[i]);
60637 vdbeFreeOpArray(db, p->aOp, p->nOp);
60638 sqlite3DbFree(db, p->aLabel);
60639 sqlite3DbFree(db, p->aColName);
60640 sqlite3DbFree(db, p->zSql);
60641 sqlite3DbFree(db, p->pFree);
60642 sqlite3DbFree(db, p);
60646 ** Delete an entire VDBE.
60648 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
60649 sqlite3 *db;
60651 if( NEVER(p==0) ) return;
60652 db = p->db;
60653 if( p->pPrev ){
60654 p->pPrev->pNext = p->pNext;
60655 }else{
60656 assert( db->pVdbe==p );
60657 db->pVdbe = p->pNext;
60659 if( p->pNext ){
60660 p->pNext->pPrev = p->pPrev;
60662 p->magic = VDBE_MAGIC_DEAD;
60663 p->db = 0;
60664 sqlite3VdbeDeleteObject(db, p);
60668 ** Make sure the cursor p is ready to read or write the row to which it
60669 ** was last positioned. Return an error code if an OOM fault or I/O error
60670 ** prevents us from positioning the cursor to its correct position.
60672 ** If a MoveTo operation is pending on the given cursor, then do that
60673 ** MoveTo now. If no move is pending, check to see if the row has been
60674 ** deleted out from under the cursor and if it has, mark the row as
60675 ** a NULL row.
60677 ** If the cursor is already pointing to the correct row and that row has
60678 ** not been deleted out from under the cursor, then this routine is a no-op.
60680 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
60681 if( p->deferredMoveto ){
60682 int res, rc;
60683 #ifdef SQLITE_TEST
60684 extern int sqlite3_search_count;
60685 #endif
60686 assert( p->isTable );
60687 rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
60688 if( rc ) return rc;
60689 p->lastRowid = p->movetoTarget;
60690 if( res!=0 ) return SQLITE_CORRUPT_BKPT;
60691 p->rowidIsValid = 1;
60692 #ifdef SQLITE_TEST
60693 sqlite3_search_count++;
60694 #endif
60695 p->deferredMoveto = 0;
60696 p->cacheStatus = CACHE_STALE;
60697 }else if( ALWAYS(p->pCursor) ){
60698 int hasMoved;
60699 int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
60700 if( rc ) return rc;
60701 if( hasMoved ){
60702 p->cacheStatus = CACHE_STALE;
60703 p->nullRow = 1;
60706 return SQLITE_OK;
60710 ** The following functions:
60712 ** sqlite3VdbeSerialType()
60713 ** sqlite3VdbeSerialTypeLen()
60714 ** sqlite3VdbeSerialLen()
60715 ** sqlite3VdbeSerialPut()
60716 ** sqlite3VdbeSerialGet()
60718 ** encapsulate the code that serializes values for storage in SQLite
60719 ** data and index records. Each serialized value consists of a
60720 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
60721 ** integer, stored as a varint.
60723 ** In an SQLite index record, the serial type is stored directly before
60724 ** the blob of data that it corresponds to. In a table record, all serial
60725 ** types are stored at the start of the record, and the blobs of data at
60726 ** the end. Hence these functions allow the caller to handle the
60727 ** serial-type and data blob seperately.
60729 ** The following table describes the various storage classes for data:
60731 ** serial type bytes of data type
60732 ** -------------- --------------- ---------------
60733 ** 0 0 NULL
60734 ** 1 1 signed integer
60735 ** 2 2 signed integer
60736 ** 3 3 signed integer
60737 ** 4 4 signed integer
60738 ** 5 6 signed integer
60739 ** 6 8 signed integer
60740 ** 7 8 IEEE float
60741 ** 8 0 Integer constant 0
60742 ** 9 0 Integer constant 1
60743 ** 10,11 reserved for expansion
60744 ** N>=12 and even (N-12)/2 BLOB
60745 ** N>=13 and odd (N-13)/2 text
60747 ** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions
60748 ** of SQLite will not understand those serial types.
60752 ** Return the serial-type for the value stored in pMem.
60754 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
60755 int flags = pMem->flags;
60756 int n;
60758 if( flags&MEM_Null ){
60759 return 0;
60761 if( flags&MEM_Int ){
60762 /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
60763 # define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
60764 i64 i = pMem->u.i;
60765 u64 u;
60766 if( file_format>=4 && (i&1)==i ){
60767 return 8+(u32)i;
60769 if( i<0 ){
60770 if( i<(-MAX_6BYTE) ) return 6;
60771 /* Previous test prevents: u = -(-9223372036854775808) */
60772 u = -i;
60773 }else{
60774 u = i;
60776 if( u<=127 ) return 1;
60777 if( u<=32767 ) return 2;
60778 if( u<=8388607 ) return 3;
60779 if( u<=2147483647 ) return 4;
60780 if( u<=MAX_6BYTE ) return 5;
60781 return 6;
60783 if( flags&MEM_Real ){
60784 return 7;
60786 assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
60787 n = pMem->n;
60788 if( flags & MEM_Zero ){
60789 n += pMem->u.nZero;
60791 assert( n>=0 );
60792 return ((n*2) + 12 + ((flags&MEM_Str)!=0));
60796 ** Return the length of the data corresponding to the supplied serial-type.
60798 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
60799 if( serial_type>=12 ){
60800 return (serial_type-12)/2;
60801 }else{
60802 static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
60803 return aSize[serial_type];
60808 ** If we are on an architecture with mixed-endian floating
60809 ** points (ex: ARM7) then swap the lower 4 bytes with the
60810 ** upper 4 bytes. Return the result.
60812 ** For most architectures, this is a no-op.
60814 ** (later): It is reported to me that the mixed-endian problem
60815 ** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems
60816 ** that early versions of GCC stored the two words of a 64-bit
60817 ** float in the wrong order. And that error has been propagated
60818 ** ever since. The blame is not necessarily with GCC, though.
60819 ** GCC might have just copying the problem from a prior compiler.
60820 ** I am also told that newer versions of GCC that follow a different
60821 ** ABI get the byte order right.
60823 ** Developers using SQLite on an ARM7 should compile and run their
60824 ** application using -DSQLITE_DEBUG=1 at least once. With DEBUG
60825 ** enabled, some asserts below will ensure that the byte order of
60826 ** floating point values is correct.
60828 ** (2007-08-30) Frank van Vugt has studied this problem closely
60829 ** and has send his findings to the SQLite developers. Frank
60830 ** writes that some Linux kernels offer floating point hardware
60831 ** emulation that uses only 32-bit mantissas instead of a full
60832 ** 48-bits as required by the IEEE standard. (This is the
60833 ** CONFIG_FPE_FASTFPE option.) On such systems, floating point
60834 ** byte swapping becomes very complicated. To avoid problems,
60835 ** the necessary byte swapping is carried out using a 64-bit integer
60836 ** rather than a 64-bit float. Frank assures us that the code here
60837 ** works for him. We, the developers, have no way to independently
60838 ** verify this, but Frank seems to know what he is talking about
60839 ** so we trust him.
60841 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
60842 static u64 floatSwap(u64 in){
60843 union {
60844 u64 r;
60845 u32 i[2];
60846 } u;
60847 u32 t;
60849 u.r = in;
60850 t = u.i[0];
60851 u.i[0] = u.i[1];
60852 u.i[1] = t;
60853 return u.r;
60855 # define swapMixedEndianFloat(X) X = floatSwap(X)
60856 #else
60857 # define swapMixedEndianFloat(X)
60858 #endif
60861 ** Write the serialized data blob for the value stored in pMem into
60862 ** buf. It is assumed that the caller has allocated sufficient space.
60863 ** Return the number of bytes written.
60865 ** nBuf is the amount of space left in buf[]. nBuf must always be
60866 ** large enough to hold the entire field. Except, if the field is
60867 ** a blob with a zero-filled tail, then buf[] might be just the right
60868 ** size to hold everything except for the zero-filled tail. If buf[]
60869 ** is only big enough to hold the non-zero prefix, then only write that
60870 ** prefix into buf[]. But if buf[] is large enough to hold both the
60871 ** prefix and the tail then write the prefix and set the tail to all
60872 ** zeros.
60874 ** Return the number of bytes actually written into buf[]. The number
60875 ** of bytes in the zero-filled tail is included in the return value only
60876 ** if those bytes were zeroed in buf[].
60878 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
60879 u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
60880 u32 len;
60882 /* Integer and Real */
60883 if( serial_type<=7 && serial_type>0 ){
60884 u64 v;
60885 u32 i;
60886 if( serial_type==7 ){
60887 assert( sizeof(v)==sizeof(pMem->r) );
60888 memcpy(&v, &pMem->r, sizeof(v));
60889 swapMixedEndianFloat(v);
60890 }else{
60891 v = pMem->u.i;
60893 len = i = sqlite3VdbeSerialTypeLen(serial_type);
60894 assert( len<=(u32)nBuf );
60895 while( i-- ){
60896 buf[i] = (u8)(v&0xFF);
60897 v >>= 8;
60899 return len;
60902 /* String or blob */
60903 if( serial_type>=12 ){
60904 assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
60905 == (int)sqlite3VdbeSerialTypeLen(serial_type) );
60906 assert( pMem->n<=nBuf );
60907 len = pMem->n;
60908 memcpy(buf, pMem->z, len);
60909 if( pMem->flags & MEM_Zero ){
60910 len += pMem->u.nZero;
60911 assert( nBuf>=0 );
60912 if( len > (u32)nBuf ){
60913 len = (u32)nBuf;
60915 memset(&buf[pMem->n], 0, len-pMem->n);
60917 return len;
60920 /* NULL or constants 0 or 1 */
60921 return 0;
60925 ** Deserialize the data blob pointed to by buf as serial type serial_type
60926 ** and store the result in pMem. Return the number of bytes read.
60928 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
60929 const unsigned char *buf, /* Buffer to deserialize from */
60930 u32 serial_type, /* Serial type to deserialize */
60931 Mem *pMem /* Memory cell to write value into */
60933 switch( serial_type ){
60934 case 10: /* Reserved for future use */
60935 case 11: /* Reserved for future use */
60936 case 0: { /* NULL */
60937 pMem->flags = MEM_Null;
60938 break;
60940 case 1: { /* 1-byte signed integer */
60941 pMem->u.i = (signed char)buf[0];
60942 pMem->flags = MEM_Int;
60943 return 1;
60945 case 2: { /* 2-byte signed integer */
60946 pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
60947 pMem->flags = MEM_Int;
60948 return 2;
60950 case 3: { /* 3-byte signed integer */
60951 pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
60952 pMem->flags = MEM_Int;
60953 return 3;
60955 case 4: { /* 4-byte signed integer */
60956 pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
60957 pMem->flags = MEM_Int;
60958 return 4;
60960 case 5: { /* 6-byte signed integer */
60961 u64 x = (((signed char)buf[0])<<8) | buf[1];
60962 u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
60963 x = (x<<32) | y;
60964 pMem->u.i = *(i64*)&x;
60965 pMem->flags = MEM_Int;
60966 return 6;
60968 case 6: /* 8-byte signed integer */
60969 case 7: { /* IEEE floating point */
60970 u64 x;
60971 u32 y;
60972 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
60973 /* Verify that integers and floating point values use the same
60974 ** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
60975 ** defined that 64-bit floating point values really are mixed
60976 ** endian.
60978 static const u64 t1 = ((u64)0x3ff00000)<<32;
60979 static const double r1 = 1.0;
60980 u64 t2 = t1;
60981 swapMixedEndianFloat(t2);
60982 assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
60983 #endif
60985 x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
60986 y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
60987 x = (x<<32) | y;
60988 if( serial_type==6 ){
60989 pMem->u.i = *(i64*)&x;
60990 pMem->flags = MEM_Int;
60991 }else{
60992 assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
60993 swapMixedEndianFloat(x);
60994 memcpy(&pMem->r, &x, sizeof(x));
60995 pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
60997 return 8;
60999 case 8: /* Integer 0 */
61000 case 9: { /* Integer 1 */
61001 pMem->u.i = serial_type-8;
61002 pMem->flags = MEM_Int;
61003 return 0;
61005 default: {
61006 u32 len = (serial_type-12)/2;
61007 pMem->z = (char *)buf;
61008 pMem->n = len;
61009 pMem->xDel = 0;
61010 if( serial_type&0x01 ){
61011 pMem->flags = MEM_Str | MEM_Ephem;
61012 }else{
61013 pMem->flags = MEM_Blob | MEM_Ephem;
61015 return len;
61018 return 0;
61022 ** This routine is used to allocate sufficient space for an UnpackedRecord
61023 ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
61024 ** the first argument is a pointer to KeyInfo structure pKeyInfo.
61026 ** The space is either allocated using sqlite3DbMallocRaw() or from within
61027 ** the unaligned buffer passed via the second and third arguments (presumably
61028 ** stack space). If the former, then *ppFree is set to a pointer that should
61029 ** be eventually freed by the caller using sqlite3DbFree(). Or, if the
61030 ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
61031 ** before returning.
61033 ** If an OOM error occurs, NULL is returned.
61035 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
61036 KeyInfo *pKeyInfo, /* Description of the record */
61037 char *pSpace, /* Unaligned space available */
61038 int szSpace, /* Size of pSpace[] in bytes */
61039 char **ppFree /* OUT: Caller should free this pointer */
61041 UnpackedRecord *p; /* Unpacked record to return */
61042 int nOff; /* Increment pSpace by nOff to align it */
61043 int nByte; /* Number of bytes required for *p */
61045 /* We want to shift the pointer pSpace up such that it is 8-byte aligned.
61046 ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
61047 ** it by. If pSpace is already 8-byte aligned, nOff should be zero.
61049 nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
61050 nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
61051 if( nByte>szSpace+nOff ){
61052 p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
61053 *ppFree = (char *)p;
61054 if( !p ) return 0;
61055 }else{
61056 p = (UnpackedRecord*)&pSpace[nOff];
61057 *ppFree = 0;
61060 p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
61061 p->pKeyInfo = pKeyInfo;
61062 p->nField = pKeyInfo->nField + 1;
61063 return p;
61067 ** Given the nKey-byte encoding of a record in pKey[], populate the
61068 ** UnpackedRecord structure indicated by the fourth argument with the
61069 ** contents of the decoded record.
61071 SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
61072 KeyInfo *pKeyInfo, /* Information about the record format */
61073 int nKey, /* Size of the binary record */
61074 const void *pKey, /* The binary record */
61075 UnpackedRecord *p /* Populate this structure before returning. */
61077 const unsigned char *aKey = (const unsigned char *)pKey;
61078 int d;
61079 u32 idx; /* Offset in aKey[] to read from */
61080 u16 u; /* Unsigned loop counter */
61081 u32 szHdr;
61082 Mem *pMem = p->aMem;
61084 p->flags = 0;
61085 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
61086 idx = getVarint32(aKey, szHdr);
61087 d = szHdr;
61088 u = 0;
61089 while( idx<szHdr && u<p->nField && d<=nKey ){
61090 u32 serial_type;
61092 idx += getVarint32(&aKey[idx], serial_type);
61093 pMem->enc = pKeyInfo->enc;
61094 pMem->db = pKeyInfo->db;
61095 /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
61096 pMem->zMalloc = 0;
61097 d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
61098 pMem++;
61099 u++;
61101 assert( u<=pKeyInfo->nField + 1 );
61102 p->nField = u;
61106 ** This function compares the two table rows or index records
61107 ** specified by {nKey1, pKey1} and pPKey2. It returns a negative, zero
61108 ** or positive integer if key1 is less than, equal to or
61109 ** greater than key2. The {nKey1, pKey1} key must be a blob
61110 ** created by th OP_MakeRecord opcode of the VDBE. The pPKey2
61111 ** key must be a parsed key such as obtained from
61112 ** sqlite3VdbeParseRecord.
61114 ** Key1 and Key2 do not have to contain the same number of fields.
61115 ** The key with fewer fields is usually compares less than the
61116 ** longer key. However if the UNPACKED_INCRKEY flags in pPKey2 is set
61117 ** and the common prefixes are equal, then key1 is less than key2.
61118 ** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
61119 ** equal, then the keys are considered to be equal and
61120 ** the parts beyond the common prefix are ignored.
61122 ** If the UNPACKED_IGNORE_ROWID flag is set, then the last byte of
61123 ** the header of pKey1 is ignored. It is assumed that pKey1 is
61124 ** an index key, and thus ends with a rowid value. The last byte
61125 ** of the header will therefore be the serial type of the rowid:
61126 ** one of 1, 2, 3, 4, 5, 6, 8, or 9 - the integer serial types.
61127 ** The serial type of the final rowid will always be a single byte.
61128 ** By ignoring this last byte of the header, we force the comparison
61129 ** to ignore the rowid at the end of key1.
61131 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
61132 int nKey1, const void *pKey1, /* Left key */
61133 UnpackedRecord *pPKey2 /* Right key */
61135 int d1; /* Offset into aKey[] of next data element */
61136 u32 idx1; /* Offset into aKey[] of next header element */
61137 u32 szHdr1; /* Number of bytes in header */
61138 int i = 0;
61139 int nField;
61140 int rc = 0;
61141 const unsigned char *aKey1 = (const unsigned char *)pKey1;
61142 KeyInfo *pKeyInfo;
61143 Mem mem1;
61145 pKeyInfo = pPKey2->pKeyInfo;
61146 mem1.enc = pKeyInfo->enc;
61147 mem1.db = pKeyInfo->db;
61148 /* mem1.flags = 0; // Will be initialized by sqlite3VdbeSerialGet() */
61149 VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
61151 /* Compilers may complain that mem1.u.i is potentially uninitialized.
61152 ** We could initialize it, as shown here, to silence those complaints.
61153 ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
61154 ** the unnecessary initialization has a measurable negative performance
61155 ** impact, since this routine is a very high runner. And so, we choose
61156 ** to ignore the compiler warnings and leave this variable uninitialized.
61158 /* mem1.u.i = 0; // not needed, here to silence compiler warning */
61160 idx1 = getVarint32(aKey1, szHdr1);
61161 d1 = szHdr1;
61162 if( pPKey2->flags & UNPACKED_IGNORE_ROWID ){
61163 szHdr1--;
61165 nField = pKeyInfo->nField;
61166 while( idx1<szHdr1 && i<pPKey2->nField ){
61167 u32 serial_type1;
61169 /* Read the serial types for the next element in each key. */
61170 idx1 += getVarint32( aKey1+idx1, serial_type1 );
61171 if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
61173 /* Extract the values to be compared.
61175 d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
61177 /* Do the comparison
61179 rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
61180 i<nField ? pKeyInfo->aColl[i] : 0);
61181 if( rc!=0 ){
61182 assert( mem1.zMalloc==0 ); /* See comment below */
61184 /* Invert the result if we are using DESC sort order. */
61185 if( pKeyInfo->aSortOrder && i<nField && pKeyInfo->aSortOrder[i] ){
61186 rc = -rc;
61189 /* If the PREFIX_SEARCH flag is set and all fields except the final
61190 ** rowid field were equal, then clear the PREFIX_SEARCH flag and set
61191 ** pPKey2->rowid to the value of the rowid field in (pKey1, nKey1).
61192 ** This is used by the OP_IsUnique opcode.
61194 if( (pPKey2->flags & UNPACKED_PREFIX_SEARCH) && i==(pPKey2->nField-1) ){
61195 assert( idx1==szHdr1 && rc );
61196 assert( mem1.flags & MEM_Int );
61197 pPKey2->flags &= ~UNPACKED_PREFIX_SEARCH;
61198 pPKey2->rowid = mem1.u.i;
61201 return rc;
61203 i++;
61206 /* No memory allocation is ever used on mem1. Prove this using
61207 ** the following assert(). If the assert() fails, it indicates a
61208 ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
61210 assert( mem1.zMalloc==0 );
61212 /* rc==0 here means that one of the keys ran out of fields and
61213 ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
61214 ** flag is set, then break the tie by treating key2 as larger.
61215 ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
61216 ** are considered to be equal. Otherwise, the longer key is the
61217 ** larger. As it happens, the pPKey2 will always be the longer
61218 ** if there is a difference.
61220 assert( rc==0 );
61221 if( pPKey2->flags & UNPACKED_INCRKEY ){
61222 rc = -1;
61223 }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){
61224 /* Leave rc==0 */
61225 }else if( idx1<szHdr1 ){
61226 rc = 1;
61228 return rc;
61233 ** pCur points at an index entry created using the OP_MakeRecord opcode.
61234 ** Read the rowid (the last field in the record) and store it in *rowid.
61235 ** Return SQLITE_OK if everything works, or an error code otherwise.
61237 ** pCur might be pointing to text obtained from a corrupt database file.
61238 ** So the content cannot be trusted. Do appropriate checks on the content.
61240 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
61241 i64 nCellKey = 0;
61242 int rc;
61243 u32 szHdr; /* Size of the header */
61244 u32 typeRowid; /* Serial type of the rowid */
61245 u32 lenRowid; /* Size of the rowid */
61246 Mem m, v;
61248 UNUSED_PARAMETER(db);
61250 /* Get the size of the index entry. Only indices entries of less
61251 ** than 2GiB are support - anything large must be database corruption.
61252 ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
61253 ** this code can safely assume that nCellKey is 32-bits
61255 assert( sqlite3BtreeCursorIsValid(pCur) );
61256 VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
61257 assert( rc==SQLITE_OK ); /* pCur is always valid so KeySize cannot fail */
61258 assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
61260 /* Read in the complete content of the index entry */
61261 memset(&m, 0, sizeof(m));
61262 rc = sqlite3VdbeMemFromBtree(pCur, 0, (int)nCellKey, 1, &m);
61263 if( rc ){
61264 return rc;
61267 /* The index entry must begin with a header size */
61268 (void)getVarint32((u8*)m.z, szHdr);
61269 testcase( szHdr==3 );
61270 testcase( szHdr==m.n );
61271 if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
61272 goto idx_rowid_corruption;
61275 /* The last field of the index should be an integer - the ROWID.
61276 ** Verify that the last entry really is an integer. */
61277 (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
61278 testcase( typeRowid==1 );
61279 testcase( typeRowid==2 );
61280 testcase( typeRowid==3 );
61281 testcase( typeRowid==4 );
61282 testcase( typeRowid==5 );
61283 testcase( typeRowid==6 );
61284 testcase( typeRowid==8 );
61285 testcase( typeRowid==9 );
61286 if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
61287 goto idx_rowid_corruption;
61289 lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
61290 testcase( (u32)m.n==szHdr+lenRowid );
61291 if( unlikely((u32)m.n<szHdr+lenRowid) ){
61292 goto idx_rowid_corruption;
61295 /* Fetch the integer off the end of the index record */
61296 sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
61297 *rowid = v.u.i;
61298 sqlite3VdbeMemRelease(&m);
61299 return SQLITE_OK;
61301 /* Jump here if database corruption is detected after m has been
61302 ** allocated. Free the m object and return SQLITE_CORRUPT. */
61303 idx_rowid_corruption:
61304 testcase( m.zMalloc!=0 );
61305 sqlite3VdbeMemRelease(&m);
61306 return SQLITE_CORRUPT_BKPT;
61310 ** Compare the key of the index entry that cursor pC is pointing to against
61311 ** the key string in pUnpacked. Write into *pRes a number
61312 ** that is negative, zero, or positive if pC is less than, equal to,
61313 ** or greater than pUnpacked. Return SQLITE_OK on success.
61315 ** pUnpacked is either created without a rowid or is truncated so that it
61316 ** omits the rowid at the end. The rowid at the end of the index entry
61317 ** is ignored as well. Hence, this routine only compares the prefixes
61318 ** of the keys prior to the final rowid, not the entire key.
61320 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
61321 VdbeCursor *pC, /* The cursor to compare against */
61322 UnpackedRecord *pUnpacked, /* Unpacked version of key to compare against */
61323 int *res /* Write the comparison result here */
61325 i64 nCellKey = 0;
61326 int rc;
61327 BtCursor *pCur = pC->pCursor;
61328 Mem m;
61330 assert( sqlite3BtreeCursorIsValid(pCur) );
61331 VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
61332 assert( rc==SQLITE_OK ); /* pCur is always valid so KeySize cannot fail */
61333 /* nCellKey will always be between 0 and 0xffffffff because of the say
61334 ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
61335 if( nCellKey<=0 || nCellKey>0x7fffffff ){
61336 *res = 0;
61337 return SQLITE_CORRUPT_BKPT;
61339 memset(&m, 0, sizeof(m));
61340 rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (int)nCellKey, 1, &m);
61341 if( rc ){
61342 return rc;
61344 assert( pUnpacked->flags & UNPACKED_IGNORE_ROWID );
61345 *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
61346 sqlite3VdbeMemRelease(&m);
61347 return SQLITE_OK;
61351 ** This routine sets the value to be returned by subsequent calls to
61352 ** sqlite3_changes() on the database handle 'db'.
61354 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
61355 assert( sqlite3_mutex_held(db->mutex) );
61356 db->nChange = nChange;
61357 db->nTotalChange += nChange;
61361 ** Set a flag in the vdbe to update the change counter when it is finalised
61362 ** or reset.
61364 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
61365 v->changeCntOn = 1;
61369 ** Mark every prepared statement associated with a database connection
61370 ** as expired.
61372 ** An expired statement means that recompilation of the statement is
61373 ** recommend. Statements expire when things happen that make their
61374 ** programs obsolete. Removing user-defined functions or collating
61375 ** sequences, or changing an authorization function are the types of
61376 ** things that make prepared statements obsolete.
61378 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
61379 Vdbe *p;
61380 for(p = db->pVdbe; p; p=p->pNext){
61381 p->expired = 1;
61386 ** Return the database associated with the Vdbe.
61388 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
61389 return v->db;
61393 ** Return a pointer to an sqlite3_value structure containing the value bound
61394 ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
61395 ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
61396 ** constants) to the value before returning it.
61398 ** The returned value must be freed by the caller using sqlite3ValueFree().
61400 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe *v, int iVar, u8 aff){
61401 assert( iVar>0 );
61402 if( v ){
61403 Mem *pMem = &v->aVar[iVar-1];
61404 if( 0==(pMem->flags & MEM_Null) ){
61405 sqlite3_value *pRet = sqlite3ValueNew(v->db);
61406 if( pRet ){
61407 sqlite3VdbeMemCopy((Mem *)pRet, pMem);
61408 sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
61409 sqlite3VdbeMemStoreType((Mem *)pRet);
61411 return pRet;
61414 return 0;
61418 ** Configure SQL variable iVar so that binding a new value to it signals
61419 ** to sqlite3_reoptimize() that re-preparing the statement may result
61420 ** in a better query plan.
61422 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
61423 assert( iVar>0 );
61424 if( iVar>32 ){
61425 v->expmask = 0xffffffff;
61426 }else{
61427 v->expmask |= ((u32)1 << (iVar-1));
61431 /************** End of vdbeaux.c *********************************************/
61432 /************** Begin file vdbeapi.c *****************************************/
61434 ** 2004 May 26
61436 ** The author disclaims copyright to this source code. In place of
61437 ** a legal notice, here is a blessing:
61439 ** May you do good and not evil.
61440 ** May you find forgiveness for yourself and forgive others.
61441 ** May you share freely, never taking more than you give.
61443 *************************************************************************
61445 ** This file contains code use to implement APIs that are part of the
61446 ** VDBE.
61449 #ifndef SQLITE_OMIT_DEPRECATED
61451 ** Return TRUE (non-zero) of the statement supplied as an argument needs
61452 ** to be recompiled. A statement needs to be recompiled whenever the
61453 ** execution environment changes in a way that would alter the program
61454 ** that sqlite3_prepare() generates. For example, if new functions or
61455 ** collating sequences are registered or if an authorizer function is
61456 ** added or changed.
61458 SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
61459 Vdbe *p = (Vdbe*)pStmt;
61460 return p==0 || p->expired;
61462 #endif
61465 ** Check on a Vdbe to make sure it has not been finalized. Log
61466 ** an error and return true if it has been finalized (or is otherwise
61467 ** invalid). Return false if it is ok.
61469 static int vdbeSafety(Vdbe *p){
61470 if( p->db==0 ){
61471 sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
61472 return 1;
61473 }else{
61474 return 0;
61477 static int vdbeSafetyNotNull(Vdbe *p){
61478 if( p==0 ){
61479 sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
61480 return 1;
61481 }else{
61482 return vdbeSafety(p);
61487 ** The following routine destroys a virtual machine that is created by
61488 ** the sqlite3_compile() routine. The integer returned is an SQLITE_
61489 ** success/failure code that describes the result of executing the virtual
61490 ** machine.
61492 ** This routine sets the error code and string returned by
61493 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
61495 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
61496 int rc;
61497 if( pStmt==0 ){
61498 /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
61499 ** pointer is a harmless no-op. */
61500 rc = SQLITE_OK;
61501 }else{
61502 Vdbe *v = (Vdbe*)pStmt;
61503 sqlite3 *db = v->db;
61504 #if SQLITE_THREADSAFE
61505 sqlite3_mutex *mutex;
61506 #endif
61507 if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
61508 #if SQLITE_THREADSAFE
61509 mutex = v->db->mutex;
61510 #endif
61511 sqlite3_mutex_enter(mutex);
61512 rc = sqlite3VdbeFinalize(v);
61513 rc = sqlite3ApiExit(db, rc);
61514 sqlite3_mutex_leave(mutex);
61516 return rc;
61520 ** Terminate the current execution of an SQL statement and reset it
61521 ** back to its starting state so that it can be reused. A success code from
61522 ** the prior execution is returned.
61524 ** This routine sets the error code and string returned by
61525 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
61527 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
61528 int rc;
61529 if( pStmt==0 ){
61530 rc = SQLITE_OK;
61531 }else{
61532 Vdbe *v = (Vdbe*)pStmt;
61533 sqlite3_mutex_enter(v->db->mutex);
61534 rc = sqlite3VdbeReset(v);
61535 sqlite3VdbeRewind(v);
61536 assert( (rc & (v->db->errMask))==rc );
61537 rc = sqlite3ApiExit(v->db, rc);
61538 sqlite3_mutex_leave(v->db->mutex);
61540 return rc;
61544 ** Set all the parameters in the compiled SQL statement to NULL.
61546 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
61547 int i;
61548 int rc = SQLITE_OK;
61549 Vdbe *p = (Vdbe*)pStmt;
61550 #if SQLITE_THREADSAFE
61551 sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
61552 #endif
61553 sqlite3_mutex_enter(mutex);
61554 for(i=0; i<p->nVar; i++){
61555 sqlite3VdbeMemRelease(&p->aVar[i]);
61556 p->aVar[i].flags = MEM_Null;
61558 if( p->isPrepareV2 && p->expmask ){
61559 p->expired = 1;
61561 sqlite3_mutex_leave(mutex);
61562 return rc;
61566 /**************************** sqlite3_value_ *******************************
61567 ** The following routines extract information from a Mem or sqlite3_value
61568 ** structure.
61570 SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
61571 Mem *p = (Mem*)pVal;
61572 if( p->flags & (MEM_Blob|MEM_Str) ){
61573 sqlite3VdbeMemExpandBlob(p);
61574 p->flags &= ~MEM_Str;
61575 p->flags |= MEM_Blob;
61576 return p->n ? p->z : 0;
61577 }else{
61578 return sqlite3_value_text(pVal);
61581 SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
61582 return sqlite3ValueBytes(pVal, SQLITE_UTF8);
61584 SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
61585 return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
61587 SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
61588 return sqlite3VdbeRealValue((Mem*)pVal);
61590 SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
61591 return (int)sqlite3VdbeIntValue((Mem*)pVal);
61593 SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
61594 return sqlite3VdbeIntValue((Mem*)pVal);
61596 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
61597 return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
61599 #ifndef SQLITE_OMIT_UTF16
61600 SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
61601 return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
61603 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
61604 return sqlite3ValueText(pVal, SQLITE_UTF16BE);
61606 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
61607 return sqlite3ValueText(pVal, SQLITE_UTF16LE);
61609 #endif /* SQLITE_OMIT_UTF16 */
61610 SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
61611 return pVal->type;
61614 /**************************** sqlite3_result_ *******************************
61615 ** The following routines are used by user-defined functions to specify
61616 ** the function result.
61618 ** The setStrOrError() funtion calls sqlite3VdbeMemSetStr() to store the
61619 ** result as a string or blob but if the string or blob is too large, it
61620 ** then sets the error code to SQLITE_TOOBIG
61622 static void setResultStrOrError(
61623 sqlite3_context *pCtx, /* Function context */
61624 const char *z, /* String pointer */
61625 int n, /* Bytes in string, or negative */
61626 u8 enc, /* Encoding of z. 0 for BLOBs */
61627 void (*xDel)(void*) /* Destructor function */
61629 if( sqlite3VdbeMemSetStr(&pCtx->s, z, n, enc, xDel)==SQLITE_TOOBIG ){
61630 sqlite3_result_error_toobig(pCtx);
61633 SQLITE_API void sqlite3_result_blob(
61634 sqlite3_context *pCtx,
61635 const void *z,
61636 int n,
61637 void (*xDel)(void *)
61639 assert( n>=0 );
61640 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61641 setResultStrOrError(pCtx, z, n, 0, xDel);
61643 SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
61644 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61645 sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
61647 SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
61648 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61649 pCtx->isError = SQLITE_ERROR;
61650 sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
61652 #ifndef SQLITE_OMIT_UTF16
61653 SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
61654 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61655 pCtx->isError = SQLITE_ERROR;
61656 sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
61658 #endif
61659 SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
61660 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61661 sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
61663 SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
61664 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61665 sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
61667 SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
61668 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61669 sqlite3VdbeMemSetNull(&pCtx->s);
61671 SQLITE_API void sqlite3_result_text(
61672 sqlite3_context *pCtx,
61673 const char *z,
61674 int n,
61675 void (*xDel)(void *)
61677 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61678 setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
61680 #ifndef SQLITE_OMIT_UTF16
61681 SQLITE_API void sqlite3_result_text16(
61682 sqlite3_context *pCtx,
61683 const void *z,
61684 int n,
61685 void (*xDel)(void *)
61687 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61688 setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
61690 SQLITE_API void sqlite3_result_text16be(
61691 sqlite3_context *pCtx,
61692 const void *z,
61693 int n,
61694 void (*xDel)(void *)
61696 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61697 setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
61699 SQLITE_API void sqlite3_result_text16le(
61700 sqlite3_context *pCtx,
61701 const void *z,
61702 int n,
61703 void (*xDel)(void *)
61705 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61706 setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
61708 #endif /* SQLITE_OMIT_UTF16 */
61709 SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
61710 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61711 sqlite3VdbeMemCopy(&pCtx->s, pValue);
61713 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
61714 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61715 sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
61717 SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
61718 pCtx->isError = errCode;
61719 if( pCtx->s.flags & MEM_Null ){
61720 sqlite3VdbeMemSetStr(&pCtx->s, sqlite3ErrStr(errCode), -1,
61721 SQLITE_UTF8, SQLITE_STATIC);
61725 /* Force an SQLITE_TOOBIG error. */
61726 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
61727 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61728 pCtx->isError = SQLITE_TOOBIG;
61729 sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1,
61730 SQLITE_UTF8, SQLITE_STATIC);
61733 /* An SQLITE_NOMEM error. */
61734 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
61735 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61736 sqlite3VdbeMemSetNull(&pCtx->s);
61737 pCtx->isError = SQLITE_NOMEM;
61738 pCtx->s.db->mallocFailed = 1;
61742 ** This function is called after a transaction has been committed. It
61743 ** invokes callbacks registered with sqlite3_wal_hook() as required.
61745 static int doWalCallbacks(sqlite3 *db){
61746 int rc = SQLITE_OK;
61747 #ifndef SQLITE_OMIT_WAL
61748 int i;
61749 for(i=0; i<db->nDb; i++){
61750 Btree *pBt = db->aDb[i].pBt;
61751 if( pBt ){
61752 int nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
61753 if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
61754 rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
61758 #endif
61759 return rc;
61763 ** Execute the statement pStmt, either until a row of data is ready, the
61764 ** statement is completely executed or an error occurs.
61766 ** This routine implements the bulk of the logic behind the sqlite_step()
61767 ** API. The only thing omitted is the automatic recompile if a
61768 ** schema change has occurred. That detail is handled by the
61769 ** outer sqlite3_step() wrapper procedure.
61771 static int sqlite3Step(Vdbe *p){
61772 sqlite3 *db;
61773 int rc;
61775 assert(p);
61776 if( p->magic!=VDBE_MAGIC_RUN ){
61777 /* We used to require that sqlite3_reset() be called before retrying
61778 ** sqlite3_step() after any error or after SQLITE_DONE. But beginning
61779 ** with version 3.7.0, we changed this so that sqlite3_reset() would
61780 ** be called automatically instead of throwing the SQLITE_MISUSE error.
61781 ** This "automatic-reset" change is not technically an incompatibility,
61782 ** since any application that receives an SQLITE_MISUSE is broken by
61783 ** definition.
61785 ** Nevertheless, some published applications that were originally written
61786 ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
61787 ** returns, and the so were broken by the automatic-reset change. As a
61788 ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
61789 ** legacy behavior of returning SQLITE_MISUSE for cases where the
61790 ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
61791 ** or SQLITE_BUSY error.
61793 #ifdef SQLITE_OMIT_AUTORESET
61794 if( p->rc==SQLITE_BUSY || p->rc==SQLITE_LOCKED ){
61795 sqlite3_reset((sqlite3_stmt*)p);
61796 }else{
61797 return SQLITE_MISUSE_BKPT;
61799 #else
61800 sqlite3_reset((sqlite3_stmt*)p);
61801 #endif
61804 /* Check that malloc() has not failed. If it has, return early. */
61805 db = p->db;
61806 if( db->mallocFailed ){
61807 p->rc = SQLITE_NOMEM;
61808 return SQLITE_NOMEM;
61811 if( p->pc<=0 && p->expired ){
61812 p->rc = SQLITE_SCHEMA;
61813 rc = SQLITE_ERROR;
61814 goto end_of_step;
61816 if( p->pc<0 ){
61817 /* If there are no other statements currently running, then
61818 ** reset the interrupt flag. This prevents a call to sqlite3_interrupt
61819 ** from interrupting a statement that has not yet started.
61821 if( db->activeVdbeCnt==0 ){
61822 db->u1.isInterrupted = 0;
61825 assert( db->writeVdbeCnt>0 || db->autoCommit==0 || db->nDeferredCons==0 );
61827 #ifndef SQLITE_OMIT_TRACE
61828 if( db->xProfile && !db->init.busy ){
61829 sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
61831 #endif
61833 db->activeVdbeCnt++;
61834 if( p->readOnly==0 ) db->writeVdbeCnt++;
61835 p->pc = 0;
61837 #ifndef SQLITE_OMIT_EXPLAIN
61838 if( p->explain ){
61839 rc = sqlite3VdbeList(p);
61840 }else
61841 #endif /* SQLITE_OMIT_EXPLAIN */
61843 db->vdbeExecCnt++;
61844 rc = sqlite3VdbeExec(p);
61845 db->vdbeExecCnt--;
61848 #ifndef SQLITE_OMIT_TRACE
61849 /* Invoke the profile callback if there is one
61851 if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
61852 sqlite3_int64 iNow;
61853 sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
61854 db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000);
61856 #endif
61858 if( rc==SQLITE_DONE ){
61859 assert( p->rc==SQLITE_OK );
61860 p->rc = doWalCallbacks(db);
61861 if( p->rc!=SQLITE_OK ){
61862 rc = SQLITE_ERROR;
61866 db->errCode = rc;
61867 if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
61868 p->rc = SQLITE_NOMEM;
61870 end_of_step:
61871 /* At this point local variable rc holds the value that should be
61872 ** returned if this statement was compiled using the legacy
61873 ** sqlite3_prepare() interface. According to the docs, this can only
61874 ** be one of the values in the first assert() below. Variable p->rc
61875 ** contains the value that would be returned if sqlite3_finalize()
61876 ** were called on statement p.
61878 assert( rc==SQLITE_ROW || rc==SQLITE_DONE || rc==SQLITE_ERROR
61879 || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
61881 assert( p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE );
61882 if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
61883 /* If this statement was prepared using sqlite3_prepare_v2(), and an
61884 ** error has occured, then return the error code in p->rc to the
61885 ** caller. Set the error code in the database handle to the same value.
61887 rc = sqlite3VdbeTransferError(p);
61889 return (rc&db->errMask);
61893 ** The maximum number of times that a statement will try to reparse
61894 ** itself before giving up and returning SQLITE_SCHEMA.
61896 #ifndef SQLITE_MAX_SCHEMA_RETRY
61897 # define SQLITE_MAX_SCHEMA_RETRY 5
61898 #endif
61901 ** This is the top-level implementation of sqlite3_step(). Call
61902 ** sqlite3Step() to do most of the work. If a schema error occurs,
61903 ** call sqlite3Reprepare() and try again.
61905 SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
61906 int rc = SQLITE_OK; /* Result from sqlite3Step() */
61907 int rc2 = SQLITE_OK; /* Result from sqlite3Reprepare() */
61908 Vdbe *v = (Vdbe*)pStmt; /* the prepared statement */
61909 int cnt = 0; /* Counter to prevent infinite loop of reprepares */
61910 sqlite3 *db; /* The database connection */
61912 if( vdbeSafetyNotNull(v) ){
61913 return SQLITE_MISUSE_BKPT;
61915 db = v->db;
61916 sqlite3_mutex_enter(db->mutex);
61917 while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
61918 && cnt++ < SQLITE_MAX_SCHEMA_RETRY
61919 && (rc2 = rc = sqlite3Reprepare(v))==SQLITE_OK ){
61920 sqlite3_reset(pStmt);
61921 assert( v->expired==0 );
61923 if( rc2!=SQLITE_OK && ALWAYS(v->isPrepareV2) && ALWAYS(db->pErr) ){
61924 /* This case occurs after failing to recompile an sql statement.
61925 ** The error message from the SQL compiler has already been loaded
61926 ** into the database handle. This block copies the error message
61927 ** from the database handle into the statement and sets the statement
61928 ** program counter to 0 to ensure that when the statement is
61929 ** finalized or reset the parser error message is available via
61930 ** sqlite3_errmsg() and sqlite3_errcode().
61932 const char *zErr = (const char *)sqlite3_value_text(db->pErr);
61933 sqlite3DbFree(db, v->zErrMsg);
61934 if( !db->mallocFailed ){
61935 v->zErrMsg = sqlite3DbStrDup(db, zErr);
61936 v->rc = rc2;
61937 } else {
61938 v->zErrMsg = 0;
61939 v->rc = rc = SQLITE_NOMEM;
61942 rc = sqlite3ApiExit(db, rc);
61943 sqlite3_mutex_leave(db->mutex);
61944 return rc;
61948 ** Extract the user data from a sqlite3_context structure and return a
61949 ** pointer to it.
61951 SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
61952 assert( p && p->pFunc );
61953 return p->pFunc->pUserData;
61957 ** Extract the user data from a sqlite3_context structure and return a
61958 ** pointer to it.
61960 ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
61961 ** returns a copy of the pointer to the database connection (the 1st
61962 ** parameter) of the sqlite3_create_function() and
61963 ** sqlite3_create_function16() routines that originally registered the
61964 ** application defined function.
61966 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
61967 assert( p && p->pFunc );
61968 return p->s.db;
61972 ** The following is the implementation of an SQL function that always
61973 ** fails with an error message stating that the function is used in the
61974 ** wrong context. The sqlite3_overload_function() API might construct
61975 ** SQL function that use this routine so that the functions will exist
61976 ** for name resolution but are actually overloaded by the xFindFunction
61977 ** method of virtual tables.
61979 SQLITE_PRIVATE void sqlite3InvalidFunction(
61980 sqlite3_context *context, /* The function calling context */
61981 int NotUsed, /* Number of arguments to the function */
61982 sqlite3_value **NotUsed2 /* Value of each argument */
61984 const char *zName = context->pFunc->zName;
61985 char *zErr;
61986 UNUSED_PARAMETER2(NotUsed, NotUsed2);
61987 zErr = sqlite3_mprintf(
61988 "unable to use function %s in the requested context", zName);
61989 sqlite3_result_error(context, zErr, -1);
61990 sqlite3_free(zErr);
61994 ** Allocate or return the aggregate context for a user function. A new
61995 ** context is allocated on the first call. Subsequent calls return the
61996 ** same context that was returned on prior calls.
61998 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
61999 Mem *pMem;
62000 assert( p && p->pFunc && p->pFunc->xStep );
62001 assert( sqlite3_mutex_held(p->s.db->mutex) );
62002 pMem = p->pMem;
62003 testcase( nByte<0 );
62004 if( (pMem->flags & MEM_Agg)==0 ){
62005 if( nByte<=0 ){
62006 sqlite3VdbeMemReleaseExternal(pMem);
62007 pMem->flags = MEM_Null;
62008 pMem->z = 0;
62009 }else{
62010 sqlite3VdbeMemGrow(pMem, nByte, 0);
62011 pMem->flags = MEM_Agg;
62012 pMem->u.pDef = p->pFunc;
62013 if( pMem->z ){
62014 memset(pMem->z, 0, nByte);
62018 return (void*)pMem->z;
62022 ** Return the auxilary data pointer, if any, for the iArg'th argument to
62023 ** the user-function defined by pCtx.
62025 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
62026 VdbeFunc *pVdbeFunc;
62028 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62029 pVdbeFunc = pCtx->pVdbeFunc;
62030 if( !pVdbeFunc || iArg>=pVdbeFunc->nAux || iArg<0 ){
62031 return 0;
62033 return pVdbeFunc->apAux[iArg].pAux;
62037 ** Set the auxilary data pointer and delete function, for the iArg'th
62038 ** argument to the user-function defined by pCtx. Any previous value is
62039 ** deleted by calling the delete function specified when it was set.
62041 SQLITE_API void sqlite3_set_auxdata(
62042 sqlite3_context *pCtx,
62043 int iArg,
62044 void *pAux,
62045 void (*xDelete)(void*)
62047 struct AuxData *pAuxData;
62048 VdbeFunc *pVdbeFunc;
62049 if( iArg<0 ) goto failed;
62051 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62052 pVdbeFunc = pCtx->pVdbeFunc;
62053 if( !pVdbeFunc || pVdbeFunc->nAux<=iArg ){
62054 int nAux = (pVdbeFunc ? pVdbeFunc->nAux : 0);
62055 int nMalloc = sizeof(VdbeFunc) + sizeof(struct AuxData)*iArg;
62056 pVdbeFunc = sqlite3DbRealloc(pCtx->s.db, pVdbeFunc, nMalloc);
62057 if( !pVdbeFunc ){
62058 goto failed;
62060 pCtx->pVdbeFunc = pVdbeFunc;
62061 memset(&pVdbeFunc->apAux[nAux], 0, sizeof(struct AuxData)*(iArg+1-nAux));
62062 pVdbeFunc->nAux = iArg+1;
62063 pVdbeFunc->pFunc = pCtx->pFunc;
62066 pAuxData = &pVdbeFunc->apAux[iArg];
62067 if( pAuxData->pAux && pAuxData->xDelete ){
62068 pAuxData->xDelete(pAuxData->pAux);
62070 pAuxData->pAux = pAux;
62071 pAuxData->xDelete = xDelete;
62072 return;
62074 failed:
62075 if( xDelete ){
62076 xDelete(pAux);
62080 #ifndef SQLITE_OMIT_DEPRECATED
62082 ** Return the number of times the Step function of a aggregate has been
62083 ** called.
62085 ** This function is deprecated. Do not use it for new code. It is
62086 ** provide only to avoid breaking legacy code. New aggregate function
62087 ** implementations should keep their own counts within their aggregate
62088 ** context.
62090 SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
62091 assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
62092 return p->pMem->n;
62094 #endif
62097 ** Return the number of columns in the result set for the statement pStmt.
62099 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
62100 Vdbe *pVm = (Vdbe *)pStmt;
62101 return pVm ? pVm->nResColumn : 0;
62105 ** Return the number of values available from the current row of the
62106 ** currently executing statement pStmt.
62108 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
62109 Vdbe *pVm = (Vdbe *)pStmt;
62110 if( pVm==0 || pVm->pResultSet==0 ) return 0;
62111 return pVm->nResColumn;
62116 ** Check to see if column iCol of the given statement is valid. If
62117 ** it is, return a pointer to the Mem for the value of that column.
62118 ** If iCol is not valid, return a pointer to a Mem which has a value
62119 ** of NULL.
62121 static Mem *columnMem(sqlite3_stmt *pStmt, int i){
62122 Vdbe *pVm;
62123 Mem *pOut;
62125 pVm = (Vdbe *)pStmt;
62126 if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
62127 sqlite3_mutex_enter(pVm->db->mutex);
62128 pOut = &pVm->pResultSet[i];
62129 }else{
62130 /* If the value passed as the second argument is out of range, return
62131 ** a pointer to the following static Mem object which contains the
62132 ** value SQL NULL. Even though the Mem structure contains an element
62133 ** of type i64, on certain architecture (x86) with certain compiler
62134 ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
62135 ** instead of an 8-byte one. This all works fine, except that when
62136 ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
62137 ** that a Mem structure is located on an 8-byte boundary. To prevent
62138 ** this assert() from failing, when building with SQLITE_DEBUG defined
62139 ** using gcc, force nullMem to be 8-byte aligned using the magical
62140 ** __attribute__((aligned(8))) macro. */
62141 static const Mem nullMem
62142 #if defined(SQLITE_DEBUG) && defined(__GNUC__)
62143 __attribute__((aligned(8)))
62144 #endif
62145 = {0, "", (double)0, {0}, 0, MEM_Null, SQLITE_NULL, 0,
62146 #ifdef SQLITE_DEBUG
62147 0, 0, /* pScopyFrom, pFiller */
62148 #endif
62149 0, 0 };
62151 if( pVm && ALWAYS(pVm->db) ){
62152 sqlite3_mutex_enter(pVm->db->mutex);
62153 sqlite3Error(pVm->db, SQLITE_RANGE, 0);
62155 pOut = (Mem*)&nullMem;
62157 return pOut;
62161 ** This function is called after invoking an sqlite3_value_XXX function on a
62162 ** column value (i.e. a value returned by evaluating an SQL expression in the
62163 ** select list of a SELECT statement) that may cause a malloc() failure. If
62164 ** malloc() has failed, the threads mallocFailed flag is cleared and the result
62165 ** code of statement pStmt set to SQLITE_NOMEM.
62167 ** Specifically, this is called from within:
62169 ** sqlite3_column_int()
62170 ** sqlite3_column_int64()
62171 ** sqlite3_column_text()
62172 ** sqlite3_column_text16()
62173 ** sqlite3_column_real()
62174 ** sqlite3_column_bytes()
62175 ** sqlite3_column_bytes16()
62176 ** sqiite3_column_blob()
62178 static void columnMallocFailure(sqlite3_stmt *pStmt)
62180 /* If malloc() failed during an encoding conversion within an
62181 ** sqlite3_column_XXX API, then set the return code of the statement to
62182 ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
62183 ** and _finalize() will return NOMEM.
62185 Vdbe *p = (Vdbe *)pStmt;
62186 if( p ){
62187 p->rc = sqlite3ApiExit(p->db, p->rc);
62188 sqlite3_mutex_leave(p->db->mutex);
62192 /**************************** sqlite3_column_ *******************************
62193 ** The following routines are used to access elements of the current row
62194 ** in the result set.
62196 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
62197 const void *val;
62198 val = sqlite3_value_blob( columnMem(pStmt,i) );
62199 /* Even though there is no encoding conversion, value_blob() might
62200 ** need to call malloc() to expand the result of a zeroblob()
62201 ** expression.
62203 columnMallocFailure(pStmt);
62204 return val;
62206 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
62207 int val = sqlite3_value_bytes( columnMem(pStmt,i) );
62208 columnMallocFailure(pStmt);
62209 return val;
62211 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
62212 int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
62213 columnMallocFailure(pStmt);
62214 return val;
62216 SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
62217 double val = sqlite3_value_double( columnMem(pStmt,i) );
62218 columnMallocFailure(pStmt);
62219 return val;
62221 SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
62222 int val = sqlite3_value_int( columnMem(pStmt,i) );
62223 columnMallocFailure(pStmt);
62224 return val;
62226 SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
62227 sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
62228 columnMallocFailure(pStmt);
62229 return val;
62231 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
62232 const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
62233 columnMallocFailure(pStmt);
62234 return val;
62236 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
62237 Mem *pOut = columnMem(pStmt, i);
62238 if( pOut->flags&MEM_Static ){
62239 pOut->flags &= ~MEM_Static;
62240 pOut->flags |= MEM_Ephem;
62242 columnMallocFailure(pStmt);
62243 return (sqlite3_value *)pOut;
62245 #ifndef SQLITE_OMIT_UTF16
62246 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
62247 const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
62248 columnMallocFailure(pStmt);
62249 return val;
62251 #endif /* SQLITE_OMIT_UTF16 */
62252 SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
62253 int iType = sqlite3_value_type( columnMem(pStmt,i) );
62254 columnMallocFailure(pStmt);
62255 return iType;
62258 /* The following function is experimental and subject to change or
62259 ** removal */
62260 /*int sqlite3_column_numeric_type(sqlite3_stmt *pStmt, int i){
62261 ** return sqlite3_value_numeric_type( columnMem(pStmt,i) );
62266 ** Convert the N-th element of pStmt->pColName[] into a string using
62267 ** xFunc() then return that string. If N is out of range, return 0.
62269 ** There are up to 5 names for each column. useType determines which
62270 ** name is returned. Here are the names:
62272 ** 0 The column name as it should be displayed for output
62273 ** 1 The datatype name for the column
62274 ** 2 The name of the database that the column derives from
62275 ** 3 The name of the table that the column derives from
62276 ** 4 The name of the table column that the result column derives from
62278 ** If the result is not a simple column reference (if it is an expression
62279 ** or a constant) then useTypes 2, 3, and 4 return NULL.
62281 static const void *columnName(
62282 sqlite3_stmt *pStmt,
62283 int N,
62284 const void *(*xFunc)(Mem*),
62285 int useType
62287 const void *ret = 0;
62288 Vdbe *p = (Vdbe *)pStmt;
62289 int n;
62290 sqlite3 *db = p->db;
62292 assert( db!=0 );
62293 n = sqlite3_column_count(pStmt);
62294 if( N<n && N>=0 ){
62295 N += useType*n;
62296 sqlite3_mutex_enter(db->mutex);
62297 assert( db->mallocFailed==0 );
62298 ret = xFunc(&p->aColName[N]);
62299 /* A malloc may have failed inside of the xFunc() call. If this
62300 ** is the case, clear the mallocFailed flag and return NULL.
62302 if( db->mallocFailed ){
62303 db->mallocFailed = 0;
62304 ret = 0;
62306 sqlite3_mutex_leave(db->mutex);
62308 return ret;
62312 ** Return the name of the Nth column of the result set returned by SQL
62313 ** statement pStmt.
62315 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
62316 return columnName(
62317 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
62319 #ifndef SQLITE_OMIT_UTF16
62320 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
62321 return columnName(
62322 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
62324 #endif
62327 ** Constraint: If you have ENABLE_COLUMN_METADATA then you must
62328 ** not define OMIT_DECLTYPE.
62330 #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
62331 # error "Must not define both SQLITE_OMIT_DECLTYPE \
62332 and SQLITE_ENABLE_COLUMN_METADATA"
62333 #endif
62335 #ifndef SQLITE_OMIT_DECLTYPE
62337 ** Return the column declaration type (if applicable) of the 'i'th column
62338 ** of the result set of SQL statement pStmt.
62340 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
62341 return columnName(
62342 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
62344 #ifndef SQLITE_OMIT_UTF16
62345 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
62346 return columnName(
62347 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
62349 #endif /* SQLITE_OMIT_UTF16 */
62350 #endif /* SQLITE_OMIT_DECLTYPE */
62352 #ifdef SQLITE_ENABLE_COLUMN_METADATA
62354 ** Return the name of the database from which a result column derives.
62355 ** NULL is returned if the result column is an expression or constant or
62356 ** anything else which is not an unabiguous reference to a database column.
62358 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
62359 return columnName(
62360 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
62362 #ifndef SQLITE_OMIT_UTF16
62363 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
62364 return columnName(
62365 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
62367 #endif /* SQLITE_OMIT_UTF16 */
62370 ** Return the name of the table from which a result column derives.
62371 ** NULL is returned if the result column is an expression or constant or
62372 ** anything else which is not an unabiguous reference to a database column.
62374 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
62375 return columnName(
62376 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
62378 #ifndef SQLITE_OMIT_UTF16
62379 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
62380 return columnName(
62381 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
62383 #endif /* SQLITE_OMIT_UTF16 */
62386 ** Return the name of the table column from which a result column derives.
62387 ** NULL is returned if the result column is an expression or constant or
62388 ** anything else which is not an unabiguous reference to a database column.
62390 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
62391 return columnName(
62392 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
62394 #ifndef SQLITE_OMIT_UTF16
62395 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
62396 return columnName(
62397 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
62399 #endif /* SQLITE_OMIT_UTF16 */
62400 #endif /* SQLITE_ENABLE_COLUMN_METADATA */
62403 /******************************* sqlite3_bind_ ***************************
62405 ** Routines used to attach values to wildcards in a compiled SQL statement.
62408 ** Unbind the value bound to variable i in virtual machine p. This is the
62409 ** the same as binding a NULL value to the column. If the "i" parameter is
62410 ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
62412 ** A successful evaluation of this routine acquires the mutex on p.
62413 ** the mutex is released if any kind of error occurs.
62415 ** The error code stored in database p->db is overwritten with the return
62416 ** value in any case.
62418 static int vdbeUnbind(Vdbe *p, int i){
62419 Mem *pVar;
62420 if( vdbeSafetyNotNull(p) ){
62421 return SQLITE_MISUSE_BKPT;
62423 sqlite3_mutex_enter(p->db->mutex);
62424 if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
62425 sqlite3Error(p->db, SQLITE_MISUSE, 0);
62426 sqlite3_mutex_leave(p->db->mutex);
62427 sqlite3_log(SQLITE_MISUSE,
62428 "bind on a busy prepared statement: [%s]", p->zSql);
62429 return SQLITE_MISUSE_BKPT;
62431 if( i<1 || i>p->nVar ){
62432 sqlite3Error(p->db, SQLITE_RANGE, 0);
62433 sqlite3_mutex_leave(p->db->mutex);
62434 return SQLITE_RANGE;
62436 i--;
62437 pVar = &p->aVar[i];
62438 sqlite3VdbeMemRelease(pVar);
62439 pVar->flags = MEM_Null;
62440 sqlite3Error(p->db, SQLITE_OK, 0);
62442 /* If the bit corresponding to this variable in Vdbe.expmask is set, then
62443 ** binding a new value to this variable invalidates the current query plan.
62445 ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
62446 ** parameter in the WHERE clause might influence the choice of query plan
62447 ** for a statement, then the statement will be automatically recompiled,
62448 ** as if there had been a schema change, on the first sqlite3_step() call
62449 ** following any change to the bindings of that parameter.
62451 if( p->isPrepareV2 &&
62452 ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
62454 p->expired = 1;
62456 return SQLITE_OK;
62460 ** Bind a text or BLOB value.
62462 static int bindText(
62463 sqlite3_stmt *pStmt, /* The statement to bind against */
62464 int i, /* Index of the parameter to bind */
62465 const void *zData, /* Pointer to the data to be bound */
62466 int nData, /* Number of bytes of data to be bound */
62467 void (*xDel)(void*), /* Destructor for the data */
62468 u8 encoding /* Encoding for the data */
62470 Vdbe *p = (Vdbe *)pStmt;
62471 Mem *pVar;
62472 int rc;
62474 rc = vdbeUnbind(p, i);
62475 if( rc==SQLITE_OK ){
62476 if( zData!=0 ){
62477 pVar = &p->aVar[i-1];
62478 rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
62479 if( rc==SQLITE_OK && encoding!=0 ){
62480 rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
62482 sqlite3Error(p->db, rc, 0);
62483 rc = sqlite3ApiExit(p->db, rc);
62485 sqlite3_mutex_leave(p->db->mutex);
62486 }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
62487 xDel((void*)zData);
62489 return rc;
62494 ** Bind a blob value to an SQL statement variable.
62496 SQLITE_API int sqlite3_bind_blob(
62497 sqlite3_stmt *pStmt,
62498 int i,
62499 const void *zData,
62500 int nData,
62501 void (*xDel)(void*)
62503 return bindText(pStmt, i, zData, nData, xDel, 0);
62505 SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
62506 int rc;
62507 Vdbe *p = (Vdbe *)pStmt;
62508 rc = vdbeUnbind(p, i);
62509 if( rc==SQLITE_OK ){
62510 sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
62511 sqlite3_mutex_leave(p->db->mutex);
62513 return rc;
62515 SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
62516 return sqlite3_bind_int64(p, i, (i64)iValue);
62518 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
62519 int rc;
62520 Vdbe *p = (Vdbe *)pStmt;
62521 rc = vdbeUnbind(p, i);
62522 if( rc==SQLITE_OK ){
62523 sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
62524 sqlite3_mutex_leave(p->db->mutex);
62526 return rc;
62528 SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
62529 int rc;
62530 Vdbe *p = (Vdbe*)pStmt;
62531 rc = vdbeUnbind(p, i);
62532 if( rc==SQLITE_OK ){
62533 sqlite3_mutex_leave(p->db->mutex);
62535 return rc;
62537 SQLITE_API int sqlite3_bind_text(
62538 sqlite3_stmt *pStmt,
62539 int i,
62540 const char *zData,
62541 int nData,
62542 void (*xDel)(void*)
62544 return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
62546 #ifndef SQLITE_OMIT_UTF16
62547 SQLITE_API int sqlite3_bind_text16(
62548 sqlite3_stmt *pStmt,
62549 int i,
62550 const void *zData,
62551 int nData,
62552 void (*xDel)(void*)
62554 return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
62556 #endif /* SQLITE_OMIT_UTF16 */
62557 SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
62558 int rc;
62559 switch( pValue->type ){
62560 case SQLITE_INTEGER: {
62561 rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
62562 break;
62564 case SQLITE_FLOAT: {
62565 rc = sqlite3_bind_double(pStmt, i, pValue->r);
62566 break;
62568 case SQLITE_BLOB: {
62569 if( pValue->flags & MEM_Zero ){
62570 rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
62571 }else{
62572 rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
62574 break;
62576 case SQLITE_TEXT: {
62577 rc = bindText(pStmt,i, pValue->z, pValue->n, SQLITE_TRANSIENT,
62578 pValue->enc);
62579 break;
62581 default: {
62582 rc = sqlite3_bind_null(pStmt, i);
62583 break;
62586 return rc;
62588 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
62589 int rc;
62590 Vdbe *p = (Vdbe *)pStmt;
62591 rc = vdbeUnbind(p, i);
62592 if( rc==SQLITE_OK ){
62593 sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
62594 sqlite3_mutex_leave(p->db->mutex);
62596 return rc;
62600 ** Return the number of wildcards that can be potentially bound to.
62601 ** This routine is added to support DBD::SQLite.
62603 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
62604 Vdbe *p = (Vdbe*)pStmt;
62605 return p ? p->nVar : 0;
62609 ** Return the name of a wildcard parameter. Return NULL if the index
62610 ** is out of range or if the wildcard is unnamed.
62612 ** The result is always UTF-8.
62614 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
62615 Vdbe *p = (Vdbe*)pStmt;
62616 if( p==0 || i<1 || i>p->nzVar ){
62617 return 0;
62619 return p->azVar[i-1];
62623 ** Given a wildcard parameter name, return the index of the variable
62624 ** with that name. If there is no variable with the given name,
62625 ** return 0.
62627 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
62628 int i;
62629 if( p==0 ){
62630 return 0;
62632 if( zName ){
62633 for(i=0; i<p->nzVar; i++){
62634 const char *z = p->azVar[i];
62635 if( z && memcmp(z,zName,nName)==0 && z[nName]==0 ){
62636 return i+1;
62640 return 0;
62642 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
62643 return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
62647 ** Transfer all bindings from the first statement over to the second.
62649 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
62650 Vdbe *pFrom = (Vdbe*)pFromStmt;
62651 Vdbe *pTo = (Vdbe*)pToStmt;
62652 int i;
62653 assert( pTo->db==pFrom->db );
62654 assert( pTo->nVar==pFrom->nVar );
62655 sqlite3_mutex_enter(pTo->db->mutex);
62656 for(i=0; i<pFrom->nVar; i++){
62657 sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
62659 sqlite3_mutex_leave(pTo->db->mutex);
62660 return SQLITE_OK;
62663 #ifndef SQLITE_OMIT_DEPRECATED
62665 ** Deprecated external interface. Internal/core SQLite code
62666 ** should call sqlite3TransferBindings.
62668 ** Is is misuse to call this routine with statements from different
62669 ** database connections. But as this is a deprecated interface, we
62670 ** will not bother to check for that condition.
62672 ** If the two statements contain a different number of bindings, then
62673 ** an SQLITE_ERROR is returned. Nothing else can go wrong, so otherwise
62674 ** SQLITE_OK is returned.
62676 SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
62677 Vdbe *pFrom = (Vdbe*)pFromStmt;
62678 Vdbe *pTo = (Vdbe*)pToStmt;
62679 if( pFrom->nVar!=pTo->nVar ){
62680 return SQLITE_ERROR;
62682 if( pTo->isPrepareV2 && pTo->expmask ){
62683 pTo->expired = 1;
62685 if( pFrom->isPrepareV2 && pFrom->expmask ){
62686 pFrom->expired = 1;
62688 return sqlite3TransferBindings(pFromStmt, pToStmt);
62690 #endif
62693 ** Return the sqlite3* database handle to which the prepared statement given
62694 ** in the argument belongs. This is the same database handle that was
62695 ** the first argument to the sqlite3_prepare() that was used to create
62696 ** the statement in the first place.
62698 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
62699 return pStmt ? ((Vdbe*)pStmt)->db : 0;
62703 ** Return true if the prepared statement is guaranteed to not modify the
62704 ** database.
62706 SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
62707 return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
62711 ** Return a pointer to the next prepared statement after pStmt associated
62712 ** with database connection pDb. If pStmt is NULL, return the first
62713 ** prepared statement for the database connection. Return NULL if there
62714 ** are no more.
62716 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
62717 sqlite3_stmt *pNext;
62718 sqlite3_mutex_enter(pDb->mutex);
62719 if( pStmt==0 ){
62720 pNext = (sqlite3_stmt*)pDb->pVdbe;
62721 }else{
62722 pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
62724 sqlite3_mutex_leave(pDb->mutex);
62725 return pNext;
62729 ** Return the value of a status counter for a prepared statement
62731 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
62732 Vdbe *pVdbe = (Vdbe*)pStmt;
62733 int v = pVdbe->aCounter[op-1];
62734 if( resetFlag ) pVdbe->aCounter[op-1] = 0;
62735 return v;
62738 /************** End of vdbeapi.c *********************************************/
62739 /************** Begin file vdbetrace.c ***************************************/
62741 ** 2009 November 25
62743 ** The author disclaims copyright to this source code. In place of
62744 ** a legal notice, here is a blessing:
62746 ** May you do good and not evil.
62747 ** May you find forgiveness for yourself and forgive others.
62748 ** May you share freely, never taking more than you give.
62750 *************************************************************************
62752 ** This file contains code used to insert the values of host parameters
62753 ** (aka "wildcards") into the SQL text output by sqlite3_trace().
62756 #ifndef SQLITE_OMIT_TRACE
62759 ** zSql is a zero-terminated string of UTF-8 SQL text. Return the number of
62760 ** bytes in this text up to but excluding the first character in
62761 ** a host parameter. If the text contains no host parameters, return
62762 ** the total number of bytes in the text.
62764 static int findNextHostParameter(const char *zSql, int *pnToken){
62765 int tokenType;
62766 int nTotal = 0;
62767 int n;
62769 *pnToken = 0;
62770 while( zSql[0] ){
62771 n = sqlite3GetToken((u8*)zSql, &tokenType);
62772 assert( n>0 && tokenType!=TK_ILLEGAL );
62773 if( tokenType==TK_VARIABLE ){
62774 *pnToken = n;
62775 break;
62777 nTotal += n;
62778 zSql += n;
62780 return nTotal;
62784 ** This function returns a pointer to a nul-terminated string in memory
62785 ** obtained from sqlite3DbMalloc(). If sqlite3.vdbeExecCnt is 1, then the
62786 ** string contains a copy of zRawSql but with host parameters expanded to
62787 ** their current bindings. Or, if sqlite3.vdbeExecCnt is greater than 1,
62788 ** then the returned string holds a copy of zRawSql with "-- " prepended
62789 ** to each line of text.
62791 ** The calling function is responsible for making sure the memory returned
62792 ** is eventually freed.
62794 ** ALGORITHM: Scan the input string looking for host parameters in any of
62795 ** these forms: ?, ?N, $A, @A, :A. Take care to avoid text within
62796 ** string literals, quoted identifier names, and comments. For text forms,
62797 ** the host parameter index is found by scanning the perpared
62798 ** statement for the corresponding OP_Variable opcode. Once the host
62799 ** parameter index is known, locate the value in p->aVar[]. Then render
62800 ** the value as a literal in place of the host parameter name.
62802 SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
62803 Vdbe *p, /* The prepared statement being evaluated */
62804 const char *zRawSql /* Raw text of the SQL statement */
62806 sqlite3 *db; /* The database connection */
62807 int idx = 0; /* Index of a host parameter */
62808 int nextIndex = 1; /* Index of next ? host parameter */
62809 int n; /* Length of a token prefix */
62810 int nToken; /* Length of the parameter token */
62811 int i; /* Loop counter */
62812 Mem *pVar; /* Value of a host parameter */
62813 StrAccum out; /* Accumulate the output here */
62814 char zBase[100]; /* Initial working space */
62816 db = p->db;
62817 sqlite3StrAccumInit(&out, zBase, sizeof(zBase),
62818 db->aLimit[SQLITE_LIMIT_LENGTH]);
62819 out.db = db;
62820 if( db->vdbeExecCnt>1 ){
62821 while( *zRawSql ){
62822 const char *zStart = zRawSql;
62823 while( *(zRawSql++)!='\n' && *zRawSql );
62824 sqlite3StrAccumAppend(&out, "-- ", 3);
62825 sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
62827 }else{
62828 while( zRawSql[0] ){
62829 n = findNextHostParameter(zRawSql, &nToken);
62830 assert( n>0 );
62831 sqlite3StrAccumAppend(&out, zRawSql, n);
62832 zRawSql += n;
62833 assert( zRawSql[0] || nToken==0 );
62834 if( nToken==0 ) break;
62835 if( zRawSql[0]=='?' ){
62836 if( nToken>1 ){
62837 assert( sqlite3Isdigit(zRawSql[1]) );
62838 sqlite3GetInt32(&zRawSql[1], &idx);
62839 }else{
62840 idx = nextIndex;
62842 }else{
62843 assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' );
62844 testcase( zRawSql[0]==':' );
62845 testcase( zRawSql[0]=='$' );
62846 testcase( zRawSql[0]=='@' );
62847 idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
62848 assert( idx>0 );
62850 zRawSql += nToken;
62851 nextIndex = idx + 1;
62852 assert( idx>0 && idx<=p->nVar );
62853 pVar = &p->aVar[idx-1];
62854 if( pVar->flags & MEM_Null ){
62855 sqlite3StrAccumAppend(&out, "NULL", 4);
62856 }else if( pVar->flags & MEM_Int ){
62857 sqlite3XPrintf(&out, "%lld", pVar->u.i);
62858 }else if( pVar->flags & MEM_Real ){
62859 sqlite3XPrintf(&out, "%!.15g", pVar->r);
62860 }else if( pVar->flags & MEM_Str ){
62861 #ifndef SQLITE_OMIT_UTF16
62862 u8 enc = ENC(db);
62863 if( enc!=SQLITE_UTF8 ){
62864 Mem utf8;
62865 memset(&utf8, 0, sizeof(utf8));
62866 utf8.db = db;
62867 sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
62868 sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
62869 sqlite3XPrintf(&out, "'%.*q'", utf8.n, utf8.z);
62870 sqlite3VdbeMemRelease(&utf8);
62871 }else
62872 #endif
62874 sqlite3XPrintf(&out, "'%.*q'", pVar->n, pVar->z);
62876 }else if( pVar->flags & MEM_Zero ){
62877 sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
62878 }else{
62879 assert( pVar->flags & MEM_Blob );
62880 sqlite3StrAccumAppend(&out, "x'", 2);
62881 for(i=0; i<pVar->n; i++){
62882 sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
62884 sqlite3StrAccumAppend(&out, "'", 1);
62888 return sqlite3StrAccumFinish(&out);
62891 #endif /* #ifndef SQLITE_OMIT_TRACE */
62893 /************** End of vdbetrace.c *******************************************/
62894 /************** Begin file vdbe.c ********************************************/
62896 ** 2001 September 15
62898 ** The author disclaims copyright to this source code. In place of
62899 ** a legal notice, here is a blessing:
62901 ** May you do good and not evil.
62902 ** May you find forgiveness for yourself and forgive others.
62903 ** May you share freely, never taking more than you give.
62905 *************************************************************************
62906 ** The code in this file implements execution method of the
62907 ** Virtual Database Engine (VDBE). A separate file ("vdbeaux.c")
62908 ** handles housekeeping details such as creating and deleting
62909 ** VDBE instances. This file is solely interested in executing
62910 ** the VDBE program.
62912 ** In the external interface, an "sqlite3_stmt*" is an opaque pointer
62913 ** to a VDBE.
62915 ** The SQL parser generates a program which is then executed by
62916 ** the VDBE to do the work of the SQL statement. VDBE programs are
62917 ** similar in form to assembly language. The program consists of
62918 ** a linear sequence of operations. Each operation has an opcode
62919 ** and 5 operands. Operands P1, P2, and P3 are integers. Operand P4
62920 ** is a null-terminated string. Operand P5 is an unsigned character.
62921 ** Few opcodes use all 5 operands.
62923 ** Computation results are stored on a set of registers numbered beginning
62924 ** with 1 and going up to Vdbe.nMem. Each register can store
62925 ** either an integer, a null-terminated string, a floating point
62926 ** number, or the SQL "NULL" value. An implicit conversion from one
62927 ** type to the other occurs as necessary.
62929 ** Most of the code in this file is taken up by the sqlite3VdbeExec()
62930 ** function which does the work of interpreting a VDBE program.
62931 ** But other routines are also provided to help in building up
62932 ** a program instruction by instruction.
62934 ** Various scripts scan this source file in order to generate HTML
62935 ** documentation, headers files, or other derived files. The formatting
62936 ** of the code in this file is, therefore, important. See other comments
62937 ** in this file for details. If in doubt, do not deviate from existing
62938 ** commenting and indentation practices when changing or adding code.
62942 ** Invoke this macro on memory cells just prior to changing the
62943 ** value of the cell. This macro verifies that shallow copies are
62944 ** not misused.
62946 #ifdef SQLITE_DEBUG
62947 # define memAboutToChange(P,M) sqlite3VdbeMemPrepareToChange(P,M)
62948 #else
62949 # define memAboutToChange(P,M)
62950 #endif
62953 ** The following global variable is incremented every time a cursor
62954 ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes. The test
62955 ** procedures use this information to make sure that indices are
62956 ** working correctly. This variable has no function other than to
62957 ** help verify the correct operation of the library.
62959 #ifdef SQLITE_TEST
62960 SQLITE_API int sqlite3_search_count = 0;
62961 #endif
62964 ** When this global variable is positive, it gets decremented once before
62965 ** each instruction in the VDBE. When reaches zero, the u1.isInterrupted
62966 ** field of the sqlite3 structure is set in order to simulate and interrupt.
62968 ** This facility is used for testing purposes only. It does not function
62969 ** in an ordinary build.
62971 #ifdef SQLITE_TEST
62972 SQLITE_API int sqlite3_interrupt_count = 0;
62973 #endif
62976 ** The next global variable is incremented each type the OP_Sort opcode
62977 ** is executed. The test procedures use this information to make sure that
62978 ** sorting is occurring or not occurring at appropriate times. This variable
62979 ** has no function other than to help verify the correct operation of the
62980 ** library.
62982 #ifdef SQLITE_TEST
62983 SQLITE_API int sqlite3_sort_count = 0;
62984 #endif
62987 ** The next global variable records the size of the largest MEM_Blob
62988 ** or MEM_Str that has been used by a VDBE opcode. The test procedures
62989 ** use this information to make sure that the zero-blob functionality
62990 ** is working correctly. This variable has no function other than to
62991 ** help verify the correct operation of the library.
62993 #ifdef SQLITE_TEST
62994 SQLITE_API int sqlite3_max_blobsize = 0;
62995 static void updateMaxBlobsize(Mem *p){
62996 if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
62997 sqlite3_max_blobsize = p->n;
63000 #endif
63003 ** The next global variable is incremented each type the OP_Found opcode
63004 ** is executed. This is used to test whether or not the foreign key
63005 ** operation implemented using OP_FkIsZero is working. This variable
63006 ** has no function other than to help verify the correct operation of the
63007 ** library.
63009 #ifdef SQLITE_TEST
63010 SQLITE_API int sqlite3_found_count = 0;
63011 #endif
63014 ** Test a register to see if it exceeds the current maximum blob size.
63015 ** If it does, record the new maximum blob size.
63017 #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
63018 # define UPDATE_MAX_BLOBSIZE(P) updateMaxBlobsize(P)
63019 #else
63020 # define UPDATE_MAX_BLOBSIZE(P)
63021 #endif
63024 ** Convert the given register into a string if it isn't one
63025 ** already. Return non-zero if a malloc() fails.
63027 #define Stringify(P, enc) \
63028 if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
63029 { goto no_mem; }
63032 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
63033 ** a pointer to a dynamically allocated string where some other entity
63034 ** is responsible for deallocating that string. Because the register
63035 ** does not control the string, it might be deleted without the register
63036 ** knowing it.
63038 ** This routine converts an ephemeral string into a dynamically allocated
63039 ** string that the register itself controls. In other words, it
63040 ** converts an MEM_Ephem string into an MEM_Dyn string.
63042 #define Deephemeralize(P) \
63043 if( ((P)->flags&MEM_Ephem)!=0 \
63044 && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
63047 ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
63048 ** P if required.
63050 #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
63052 /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
63053 #ifdef SQLITE_OMIT_MERGE_SORT
63054 # define isSorter(x) 0
63055 #else
63056 # define isSorter(x) ((x)->pSorter!=0)
63057 #endif
63060 ** Argument pMem points at a register that will be passed to a
63061 ** user-defined function or returned to the user as the result of a query.
63062 ** This routine sets the pMem->type variable used by the sqlite3_value_*()
63063 ** routines.
63065 SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem){
63066 int flags = pMem->flags;
63067 if( flags & MEM_Null ){
63068 pMem->type = SQLITE_NULL;
63070 else if( flags & MEM_Int ){
63071 pMem->type = SQLITE_INTEGER;
63073 else if( flags & MEM_Real ){
63074 pMem->type = SQLITE_FLOAT;
63076 else if( flags & MEM_Str ){
63077 pMem->type = SQLITE_TEXT;
63078 }else{
63079 pMem->type = SQLITE_BLOB;
63084 ** Allocate VdbeCursor number iCur. Return a pointer to it. Return NULL
63085 ** if we run out of memory.
63087 static VdbeCursor *allocateCursor(
63088 Vdbe *p, /* The virtual machine */
63089 int iCur, /* Index of the new VdbeCursor */
63090 int nField, /* Number of fields in the table or index */
63091 int iDb, /* When database the cursor belongs to, or -1 */
63092 int isBtreeCursor /* True for B-Tree. False for pseudo-table or vtab */
63094 /* Find the memory cell that will be used to store the blob of memory
63095 ** required for this VdbeCursor structure. It is convenient to use a
63096 ** vdbe memory cell to manage the memory allocation required for a
63097 ** VdbeCursor structure for the following reasons:
63099 ** * Sometimes cursor numbers are used for a couple of different
63100 ** purposes in a vdbe program. The different uses might require
63101 ** different sized allocations. Memory cells provide growable
63102 ** allocations.
63104 ** * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
63105 ** be freed lazily via the sqlite3_release_memory() API. This
63106 ** minimizes the number of malloc calls made by the system.
63108 ** Memory cells for cursors are allocated at the top of the address
63109 ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
63110 ** cursor 1 is managed by memory cell (p->nMem-1), etc.
63112 Mem *pMem = &p->aMem[p->nMem-iCur];
63114 int nByte;
63115 VdbeCursor *pCx = 0;
63116 nByte =
63117 ROUND8(sizeof(VdbeCursor)) +
63118 (isBtreeCursor?sqlite3BtreeCursorSize():0) +
63119 2*nField*sizeof(u32);
63121 assert( iCur<p->nCursor );
63122 if( p->apCsr[iCur] ){
63123 sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
63124 p->apCsr[iCur] = 0;
63126 if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
63127 p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
63128 memset(pCx, 0, sizeof(VdbeCursor));
63129 pCx->iDb = iDb;
63130 pCx->nField = nField;
63131 if( nField ){
63132 pCx->aType = (u32 *)&pMem->z[ROUND8(sizeof(VdbeCursor))];
63134 if( isBtreeCursor ){
63135 pCx->pCursor = (BtCursor*)
63136 &pMem->z[ROUND8(sizeof(VdbeCursor))+2*nField*sizeof(u32)];
63137 sqlite3BtreeCursorZero(pCx->pCursor);
63140 return pCx;
63144 ** Try to convert a value into a numeric representation if we can
63145 ** do so without loss of information. In other words, if the string
63146 ** looks like a number, convert it into a number. If it does not
63147 ** look like a number, leave it alone.
63149 static void applyNumericAffinity(Mem *pRec){
63150 if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
63151 double rValue;
63152 i64 iValue;
63153 u8 enc = pRec->enc;
63154 if( (pRec->flags&MEM_Str)==0 ) return;
63155 if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
63156 if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
63157 pRec->u.i = iValue;
63158 pRec->flags |= MEM_Int;
63159 }else{
63160 pRec->r = rValue;
63161 pRec->flags |= MEM_Real;
63167 ** Processing is determine by the affinity parameter:
63169 ** SQLITE_AFF_INTEGER:
63170 ** SQLITE_AFF_REAL:
63171 ** SQLITE_AFF_NUMERIC:
63172 ** Try to convert pRec to an integer representation or a
63173 ** floating-point representation if an integer representation
63174 ** is not possible. Note that the integer representation is
63175 ** always preferred, even if the affinity is REAL, because
63176 ** an integer representation is more space efficient on disk.
63178 ** SQLITE_AFF_TEXT:
63179 ** Convert pRec to a text representation.
63181 ** SQLITE_AFF_NONE:
63182 ** No-op. pRec is unchanged.
63184 static void applyAffinity(
63185 Mem *pRec, /* The value to apply affinity to */
63186 char affinity, /* The affinity to be applied */
63187 u8 enc /* Use this text encoding */
63189 if( affinity==SQLITE_AFF_TEXT ){
63190 /* Only attempt the conversion to TEXT if there is an integer or real
63191 ** representation (blob and NULL do not get converted) but no string
63192 ** representation.
63194 if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
63195 sqlite3VdbeMemStringify(pRec, enc);
63197 pRec->flags &= ~(MEM_Real|MEM_Int);
63198 }else if( affinity!=SQLITE_AFF_NONE ){
63199 assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
63200 || affinity==SQLITE_AFF_NUMERIC );
63201 applyNumericAffinity(pRec);
63202 if( pRec->flags & MEM_Real ){
63203 sqlite3VdbeIntegerAffinity(pRec);
63209 ** Try to convert the type of a function argument or a result column
63210 ** into a numeric representation. Use either INTEGER or REAL whichever
63211 ** is appropriate. But only do the conversion if it is possible without
63212 ** loss of information and return the revised type of the argument.
63214 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
63215 Mem *pMem = (Mem*)pVal;
63216 if( pMem->type==SQLITE_TEXT ){
63217 applyNumericAffinity(pMem);
63218 sqlite3VdbeMemStoreType(pMem);
63220 return pMem->type;
63224 ** Exported version of applyAffinity(). This one works on sqlite3_value*,
63225 ** not the internal Mem* type.
63227 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
63228 sqlite3_value *pVal,
63229 u8 affinity,
63230 u8 enc
63232 applyAffinity((Mem *)pVal, affinity, enc);
63235 #ifdef SQLITE_DEBUG
63237 ** Write a nice string representation of the contents of cell pMem
63238 ** into buffer zBuf, length nBuf.
63240 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
63241 char *zCsr = zBuf;
63242 int f = pMem->flags;
63244 static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
63246 if( f&MEM_Blob ){
63247 int i;
63248 char c;
63249 if( f & MEM_Dyn ){
63250 c = 'z';
63251 assert( (f & (MEM_Static|MEM_Ephem))==0 );
63252 }else if( f & MEM_Static ){
63253 c = 't';
63254 assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
63255 }else if( f & MEM_Ephem ){
63256 c = 'e';
63257 assert( (f & (MEM_Static|MEM_Dyn))==0 );
63258 }else{
63259 c = 's';
63262 sqlite3_snprintf(100, zCsr, "%c", c);
63263 zCsr += sqlite3Strlen30(zCsr);
63264 sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
63265 zCsr += sqlite3Strlen30(zCsr);
63266 for(i=0; i<16 && i<pMem->n; i++){
63267 sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
63268 zCsr += sqlite3Strlen30(zCsr);
63270 for(i=0; i<16 && i<pMem->n; i++){
63271 char z = pMem->z[i];
63272 if( z<32 || z>126 ) *zCsr++ = '.';
63273 else *zCsr++ = z;
63276 sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
63277 zCsr += sqlite3Strlen30(zCsr);
63278 if( f & MEM_Zero ){
63279 sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
63280 zCsr += sqlite3Strlen30(zCsr);
63282 *zCsr = '\0';
63283 }else if( f & MEM_Str ){
63284 int j, k;
63285 zBuf[0] = ' ';
63286 if( f & MEM_Dyn ){
63287 zBuf[1] = 'z';
63288 assert( (f & (MEM_Static|MEM_Ephem))==0 );
63289 }else if( f & MEM_Static ){
63290 zBuf[1] = 't';
63291 assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
63292 }else if( f & MEM_Ephem ){
63293 zBuf[1] = 'e';
63294 assert( (f & (MEM_Static|MEM_Dyn))==0 );
63295 }else{
63296 zBuf[1] = 's';
63298 k = 2;
63299 sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
63300 k += sqlite3Strlen30(&zBuf[k]);
63301 zBuf[k++] = '[';
63302 for(j=0; j<15 && j<pMem->n; j++){
63303 u8 c = pMem->z[j];
63304 if( c>=0x20 && c<0x7f ){
63305 zBuf[k++] = c;
63306 }else{
63307 zBuf[k++] = '.';
63310 zBuf[k++] = ']';
63311 sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
63312 k += sqlite3Strlen30(&zBuf[k]);
63313 zBuf[k++] = 0;
63316 #endif
63318 #ifdef SQLITE_DEBUG
63320 ** Print the value of a register for tracing purposes:
63322 static void memTracePrint(FILE *out, Mem *p){
63323 if( p->flags & MEM_Null ){
63324 fprintf(out, " NULL");
63325 }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
63326 fprintf(out, " si:%lld", p->u.i);
63327 }else if( p->flags & MEM_Int ){
63328 fprintf(out, " i:%lld", p->u.i);
63329 #ifndef SQLITE_OMIT_FLOATING_POINT
63330 }else if( p->flags & MEM_Real ){
63331 fprintf(out, " r:%g", p->r);
63332 #endif
63333 }else if( p->flags & MEM_RowSet ){
63334 fprintf(out, " (rowset)");
63335 }else{
63336 char zBuf[200];
63337 sqlite3VdbeMemPrettyPrint(p, zBuf);
63338 fprintf(out, " ");
63339 fprintf(out, "%s", zBuf);
63342 static void registerTrace(FILE *out, int iReg, Mem *p){
63343 fprintf(out, "REG[%d] = ", iReg);
63344 memTracePrint(out, p);
63345 fprintf(out, "\n");
63347 #endif
63349 #ifdef SQLITE_DEBUG
63350 # define REGISTER_TRACE(R,M) if(p->trace)registerTrace(p->trace,R,M)
63351 #else
63352 # define REGISTER_TRACE(R,M)
63353 #endif
63356 #ifdef VDBE_PROFILE
63359 ** hwtime.h contains inline assembler code for implementing
63360 ** high-performance timing routines.
63362 /************** Include hwtime.h in the middle of vdbe.c *********************/
63363 /************** Begin file hwtime.h ******************************************/
63365 ** 2008 May 27
63367 ** The author disclaims copyright to this source code. In place of
63368 ** a legal notice, here is a blessing:
63370 ** May you do good and not evil.
63371 ** May you find forgiveness for yourself and forgive others.
63372 ** May you share freely, never taking more than you give.
63374 ******************************************************************************
63376 ** This file contains inline asm code for retrieving "high-performance"
63377 ** counters for x86 class CPUs.
63379 #ifndef _HWTIME_H_
63380 #define _HWTIME_H_
63383 ** The following routine only works on pentium-class (or newer) processors.
63384 ** It uses the RDTSC opcode to read the cycle count value out of the
63385 ** processor and returns that value. This can be used for high-res
63386 ** profiling.
63388 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
63389 (defined(i386) || defined(__i386__) || defined(_M_IX86))
63391 #if defined(__GNUC__)
63393 __inline__ sqlite_uint64 sqlite3Hwtime(void){
63394 unsigned int lo, hi;
63395 __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
63396 return (sqlite_uint64)hi << 32 | lo;
63399 #elif defined(_MSC_VER)
63401 __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
63402 __asm {
63403 rdtsc
63404 ret ; return value at EDX:EAX
63408 #endif
63410 #elif (defined(__GNUC__) && defined(__x86_64__))
63412 __inline__ sqlite_uint64 sqlite3Hwtime(void){
63413 unsigned long val;
63414 __asm__ __volatile__ ("rdtsc" : "=A" (val));
63415 return val;
63418 #elif (defined(__GNUC__) && defined(__ppc__))
63420 __inline__ sqlite_uint64 sqlite3Hwtime(void){
63421 unsigned long long retval;
63422 unsigned long junk;
63423 __asm__ __volatile__ ("\n\
63424 1: mftbu %1\n\
63425 mftb %L0\n\
63426 mftbu %0\n\
63427 cmpw %0,%1\n\
63428 bne 1b"
63429 : "=r" (retval), "=r" (junk));
63430 return retval;
63433 #else
63435 #error Need implementation of sqlite3Hwtime() for your platform.
63438 ** To compile without implementing sqlite3Hwtime() for your platform,
63439 ** you can remove the above #error and use the following
63440 ** stub function. You will lose timing support for many
63441 ** of the debugging and testing utilities, but it should at
63442 ** least compile and run.
63444 SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
63446 #endif
63448 #endif /* !defined(_HWTIME_H_) */
63450 /************** End of hwtime.h **********************************************/
63451 /************** Continuing where we left off in vdbe.c ***********************/
63453 #endif
63456 ** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
63457 ** sqlite3_interrupt() routine has been called. If it has been, then
63458 ** processing of the VDBE program is interrupted.
63460 ** This macro added to every instruction that does a jump in order to
63461 ** implement a loop. This test used to be on every single instruction,
63462 ** but that meant we more testing that we needed. By only testing the
63463 ** flag on jump instructions, we get a (small) speed improvement.
63465 #define CHECK_FOR_INTERRUPT \
63466 if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
63469 #ifndef NDEBUG
63471 ** This function is only called from within an assert() expression. It
63472 ** checks that the sqlite3.nTransaction variable is correctly set to
63473 ** the number of non-transaction savepoints currently in the
63474 ** linked list starting at sqlite3.pSavepoint.
63476 ** Usage:
63478 ** assert( checkSavepointCount(db) );
63480 static int checkSavepointCount(sqlite3 *db){
63481 int n = 0;
63482 Savepoint *p;
63483 for(p=db->pSavepoint; p; p=p->pNext) n++;
63484 assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
63485 return 1;
63487 #endif
63490 ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
63491 ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
63492 ** in memory obtained from sqlite3DbMalloc).
63494 static void importVtabErrMsg(Vdbe *p, sqlite3_vtab *pVtab){
63495 sqlite3 *db = p->db;
63496 sqlite3DbFree(db, p->zErrMsg);
63497 p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
63498 sqlite3_free(pVtab->zErrMsg);
63499 pVtab->zErrMsg = 0;
63504 ** Execute as much of a VDBE program as we can then return.
63506 ** sqlite3VdbeMakeReady() must be called before this routine in order to
63507 ** close the program with a final OP_Halt and to set up the callbacks
63508 ** and the error message pointer.
63510 ** Whenever a row or result data is available, this routine will either
63511 ** invoke the result callback (if there is one) or return with
63512 ** SQLITE_ROW.
63514 ** If an attempt is made to open a locked database, then this routine
63515 ** will either invoke the busy callback (if there is one) or it will
63516 ** return SQLITE_BUSY.
63518 ** If an error occurs, an error message is written to memory obtained
63519 ** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
63520 ** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
63522 ** If the callback ever returns non-zero, then the program exits
63523 ** immediately. There will be no error message but the p->rc field is
63524 ** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
63526 ** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
63527 ** routine to return SQLITE_ERROR.
63529 ** Other fatal errors return SQLITE_ERROR.
63531 ** After this routine has finished, sqlite3VdbeFinalize() should be
63532 ** used to clean up the mess that was left behind.
63534 SQLITE_PRIVATE int sqlite3VdbeExec(
63535 Vdbe *p /* The VDBE */
63537 int pc=0; /* The program counter */
63538 Op *aOp = p->aOp; /* Copy of p->aOp */
63539 Op *pOp; /* Current operation */
63540 int rc = SQLITE_OK; /* Value to return */
63541 sqlite3 *db = p->db; /* The database */
63542 u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
63543 u8 encoding = ENC(db); /* The database encoding */
63544 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
63545 int checkProgress; /* True if progress callbacks are enabled */
63546 int nProgressOps = 0; /* Opcodes executed since progress callback. */
63547 #endif
63548 Mem *aMem = p->aMem; /* Copy of p->aMem */
63549 Mem *pIn1 = 0; /* 1st input operand */
63550 Mem *pIn2 = 0; /* 2nd input operand */
63551 Mem *pIn3 = 0; /* 3rd input operand */
63552 Mem *pOut = 0; /* Output operand */
63553 int iCompare = 0; /* Result of last OP_Compare operation */
63554 int *aPermute = 0; /* Permutation of columns for OP_Compare */
63555 i64 lastRowid = db->lastRowid; /* Saved value of the last insert ROWID */
63556 #ifdef VDBE_PROFILE
63557 u64 start; /* CPU clock count at start of opcode */
63558 int origPc; /* Program counter at start of opcode */
63559 #endif
63560 /********************************************************************
63561 ** Automatically generated code
63563 ** The following union is automatically generated by the
63564 ** vdbe-compress.tcl script. The purpose of this union is to
63565 ** reduce the amount of stack space required by this function.
63566 ** See comments in the vdbe-compress.tcl script for details.
63568 union vdbeExecUnion {
63569 struct OP_Yield_stack_vars {
63570 int pcDest;
63571 } aa;
63572 struct OP_Variable_stack_vars {
63573 Mem *pVar; /* Value being transferred */
63574 } ab;
63575 struct OP_Move_stack_vars {
63576 char *zMalloc; /* Holding variable for allocated memory */
63577 int n; /* Number of registers left to copy */
63578 int p1; /* Register to copy from */
63579 int p2; /* Register to copy to */
63580 } ac;
63581 struct OP_ResultRow_stack_vars {
63582 Mem *pMem;
63583 int i;
63584 } ad;
63585 struct OP_Concat_stack_vars {
63586 i64 nByte;
63587 } ae;
63588 struct OP_Remainder_stack_vars {
63589 int flags; /* Combined MEM_* flags from both inputs */
63590 i64 iA; /* Integer value of left operand */
63591 i64 iB; /* Integer value of right operand */
63592 double rA; /* Real value of left operand */
63593 double rB; /* Real value of right operand */
63594 } af;
63595 struct OP_Function_stack_vars {
63596 int i;
63597 Mem *pArg;
63598 sqlite3_context ctx;
63599 sqlite3_value **apVal;
63600 int n;
63601 } ag;
63602 struct OP_ShiftRight_stack_vars {
63603 i64 iA;
63604 u64 uA;
63605 i64 iB;
63606 u8 op;
63607 } ah;
63608 struct OP_Ge_stack_vars {
63609 int res; /* Result of the comparison of pIn1 against pIn3 */
63610 char affinity; /* Affinity to use for comparison */
63611 u16 flags1; /* Copy of initial value of pIn1->flags */
63612 u16 flags3; /* Copy of initial value of pIn3->flags */
63613 } ai;
63614 struct OP_Compare_stack_vars {
63615 int n;
63616 int i;
63617 int p1;
63618 int p2;
63619 const KeyInfo *pKeyInfo;
63620 int idx;
63621 CollSeq *pColl; /* Collating sequence to use on this term */
63622 int bRev; /* True for DESCENDING sort order */
63623 } aj;
63624 struct OP_Or_stack_vars {
63625 int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
63626 int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
63627 } ak;
63628 struct OP_IfNot_stack_vars {
63629 int c;
63630 } al;
63631 struct OP_Column_stack_vars {
63632 u32 payloadSize; /* Number of bytes in the record */
63633 i64 payloadSize64; /* Number of bytes in the record */
63634 int p1; /* P1 value of the opcode */
63635 int p2; /* column number to retrieve */
63636 VdbeCursor *pC; /* The VDBE cursor */
63637 char *zRec; /* Pointer to complete record-data */
63638 BtCursor *pCrsr; /* The BTree cursor */
63639 u32 *aType; /* aType[i] holds the numeric type of the i-th column */
63640 u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
63641 int nField; /* number of fields in the record */
63642 int len; /* The length of the serialized data for the column */
63643 int i; /* Loop counter */
63644 char *zData; /* Part of the record being decoded */
63645 Mem *pDest; /* Where to write the extracted value */
63646 Mem sMem; /* For storing the record being decoded */
63647 u8 *zIdx; /* Index into header */
63648 u8 *zEndHdr; /* Pointer to first byte after the header */
63649 u32 offset; /* Offset into the data */
63650 u32 szField; /* Number of bytes in the content of a field */
63651 int szHdr; /* Size of the header size field at start of record */
63652 int avail; /* Number of bytes of available data */
63653 u32 t; /* A type code from the record header */
63654 Mem *pReg; /* PseudoTable input register */
63655 } am;
63656 struct OP_Affinity_stack_vars {
63657 const char *zAffinity; /* The affinity to be applied */
63658 char cAff; /* A single character of affinity */
63659 } an;
63660 struct OP_MakeRecord_stack_vars {
63661 u8 *zNewRecord; /* A buffer to hold the data for the new record */
63662 Mem *pRec; /* The new record */
63663 u64 nData; /* Number of bytes of data space */
63664 int nHdr; /* Number of bytes of header space */
63665 i64 nByte; /* Data space required for this record */
63666 int nZero; /* Number of zero bytes at the end of the record */
63667 int nVarint; /* Number of bytes in a varint */
63668 u32 serial_type; /* Type field */
63669 Mem *pData0; /* First field to be combined into the record */
63670 Mem *pLast; /* Last field of the record */
63671 int nField; /* Number of fields in the record */
63672 char *zAffinity; /* The affinity string for the record */
63673 int file_format; /* File format to use for encoding */
63674 int i; /* Space used in zNewRecord[] */
63675 int len; /* Length of a field */
63676 } ao;
63677 struct OP_Count_stack_vars {
63678 i64 nEntry;
63679 BtCursor *pCrsr;
63680 } ap;
63681 struct OP_Savepoint_stack_vars {
63682 int p1; /* Value of P1 operand */
63683 char *zName; /* Name of savepoint */
63684 int nName;
63685 Savepoint *pNew;
63686 Savepoint *pSavepoint;
63687 Savepoint *pTmp;
63688 int iSavepoint;
63689 int ii;
63690 } aq;
63691 struct OP_AutoCommit_stack_vars {
63692 int desiredAutoCommit;
63693 int iRollback;
63694 int turnOnAC;
63695 } ar;
63696 struct OP_Transaction_stack_vars {
63697 Btree *pBt;
63698 } as;
63699 struct OP_ReadCookie_stack_vars {
63700 int iMeta;
63701 int iDb;
63702 int iCookie;
63703 } at;
63704 struct OP_SetCookie_stack_vars {
63705 Db *pDb;
63706 } au;
63707 struct OP_VerifyCookie_stack_vars {
63708 int iMeta;
63709 int iGen;
63710 Btree *pBt;
63711 } av;
63712 struct OP_OpenWrite_stack_vars {
63713 int nField;
63714 KeyInfo *pKeyInfo;
63715 int p2;
63716 int iDb;
63717 int wrFlag;
63718 Btree *pX;
63719 VdbeCursor *pCur;
63720 Db *pDb;
63721 } aw;
63722 struct OP_OpenEphemeral_stack_vars {
63723 VdbeCursor *pCx;
63724 } ax;
63725 struct OP_SorterOpen_stack_vars {
63726 VdbeCursor *pCx;
63727 } ay;
63728 struct OP_OpenPseudo_stack_vars {
63729 VdbeCursor *pCx;
63730 } az;
63731 struct OP_SeekGt_stack_vars {
63732 int res;
63733 int oc;
63734 VdbeCursor *pC;
63735 UnpackedRecord r;
63736 int nField;
63737 i64 iKey; /* The rowid we are to seek to */
63738 } ba;
63739 struct OP_Seek_stack_vars {
63740 VdbeCursor *pC;
63741 } bb;
63742 struct OP_Found_stack_vars {
63743 int alreadyExists;
63744 VdbeCursor *pC;
63745 int res;
63746 char *pFree;
63747 UnpackedRecord *pIdxKey;
63748 UnpackedRecord r;
63749 char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
63750 } bc;
63751 struct OP_IsUnique_stack_vars {
63752 u16 ii;
63753 VdbeCursor *pCx;
63754 BtCursor *pCrsr;
63755 u16 nField;
63756 Mem *aMx;
63757 UnpackedRecord r; /* B-Tree index search key */
63758 i64 R; /* Rowid stored in register P3 */
63759 } bd;
63760 struct OP_NotExists_stack_vars {
63761 VdbeCursor *pC;
63762 BtCursor *pCrsr;
63763 int res;
63764 u64 iKey;
63765 } be;
63766 struct OP_NewRowid_stack_vars {
63767 i64 v; /* The new rowid */
63768 VdbeCursor *pC; /* Cursor of table to get the new rowid */
63769 int res; /* Result of an sqlite3BtreeLast() */
63770 int cnt; /* Counter to limit the number of searches */
63771 Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */
63772 VdbeFrame *pFrame; /* Root frame of VDBE */
63773 } bf;
63774 struct OP_InsertInt_stack_vars {
63775 Mem *pData; /* MEM cell holding data for the record to be inserted */
63776 Mem *pKey; /* MEM cell holding key for the record */
63777 i64 iKey; /* The integer ROWID or key for the record to be inserted */
63778 VdbeCursor *pC; /* Cursor to table into which insert is written */
63779 int nZero; /* Number of zero-bytes to append */
63780 int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
63781 const char *zDb; /* database name - used by the update hook */
63782 const char *zTbl; /* Table name - used by the opdate hook */
63783 int op; /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
63784 } bg;
63785 struct OP_Delete_stack_vars {
63786 i64 iKey;
63787 VdbeCursor *pC;
63788 } bh;
63789 struct OP_SorterCompare_stack_vars {
63790 VdbeCursor *pC;
63791 int res;
63792 } bi;
63793 struct OP_SorterData_stack_vars {
63794 VdbeCursor *pC;
63795 } bj;
63796 struct OP_RowData_stack_vars {
63797 VdbeCursor *pC;
63798 BtCursor *pCrsr;
63799 u32 n;
63800 i64 n64;
63801 } bk;
63802 struct OP_Rowid_stack_vars {
63803 VdbeCursor *pC;
63804 i64 v;
63805 sqlite3_vtab *pVtab;
63806 const sqlite3_module *pModule;
63807 } bl;
63808 struct OP_NullRow_stack_vars {
63809 VdbeCursor *pC;
63810 } bm;
63811 struct OP_Last_stack_vars {
63812 VdbeCursor *pC;
63813 BtCursor *pCrsr;
63814 int res;
63815 } bn;
63816 struct OP_Rewind_stack_vars {
63817 VdbeCursor *pC;
63818 BtCursor *pCrsr;
63819 int res;
63820 } bo;
63821 struct OP_Next_stack_vars {
63822 VdbeCursor *pC;
63823 int res;
63824 } bp;
63825 struct OP_IdxInsert_stack_vars {
63826 VdbeCursor *pC;
63827 BtCursor *pCrsr;
63828 int nKey;
63829 const char *zKey;
63830 } bq;
63831 struct OP_IdxDelete_stack_vars {
63832 VdbeCursor *pC;
63833 BtCursor *pCrsr;
63834 int res;
63835 UnpackedRecord r;
63836 } br;
63837 struct OP_IdxRowid_stack_vars {
63838 BtCursor *pCrsr;
63839 VdbeCursor *pC;
63840 i64 rowid;
63841 } bs;
63842 struct OP_IdxGE_stack_vars {
63843 VdbeCursor *pC;
63844 int res;
63845 UnpackedRecord r;
63846 } bt;
63847 struct OP_Destroy_stack_vars {
63848 int iMoved;
63849 int iCnt;
63850 Vdbe *pVdbe;
63851 int iDb;
63852 } bu;
63853 struct OP_Clear_stack_vars {
63854 int nChange;
63855 } bv;
63856 struct OP_CreateTable_stack_vars {
63857 int pgno;
63858 int flags;
63859 Db *pDb;
63860 } bw;
63861 struct OP_ParseSchema_stack_vars {
63862 int iDb;
63863 const char *zMaster;
63864 char *zSql;
63865 InitData initData;
63866 } bx;
63867 struct OP_IntegrityCk_stack_vars {
63868 int nRoot; /* Number of tables to check. (Number of root pages.) */
63869 int *aRoot; /* Array of rootpage numbers for tables to be checked */
63870 int j; /* Loop counter */
63871 int nErr; /* Number of errors reported */
63872 char *z; /* Text of the error report */
63873 Mem *pnErr; /* Register keeping track of errors remaining */
63874 } by;
63875 struct OP_RowSetRead_stack_vars {
63876 i64 val;
63877 } bz;
63878 struct OP_RowSetTest_stack_vars {
63879 int iSet;
63880 int exists;
63881 } ca;
63882 struct OP_Program_stack_vars {
63883 int nMem; /* Number of memory registers for sub-program */
63884 int nByte; /* Bytes of runtime space required for sub-program */
63885 Mem *pRt; /* Register to allocate runtime space */
63886 Mem *pMem; /* Used to iterate through memory cells */
63887 Mem *pEnd; /* Last memory cell in new array */
63888 VdbeFrame *pFrame; /* New vdbe frame to execute in */
63889 SubProgram *pProgram; /* Sub-program to execute */
63890 void *t; /* Token identifying trigger */
63891 } cb;
63892 struct OP_Param_stack_vars {
63893 VdbeFrame *pFrame;
63894 Mem *pIn;
63895 } cc;
63896 struct OP_MemMax_stack_vars {
63897 Mem *pIn1;
63898 VdbeFrame *pFrame;
63899 } cd;
63900 struct OP_AggStep_stack_vars {
63901 int n;
63902 int i;
63903 Mem *pMem;
63904 Mem *pRec;
63905 sqlite3_context ctx;
63906 sqlite3_value **apVal;
63907 } ce;
63908 struct OP_AggFinal_stack_vars {
63909 Mem *pMem;
63910 } cf;
63911 struct OP_Checkpoint_stack_vars {
63912 int i; /* Loop counter */
63913 int aRes[3]; /* Results */
63914 Mem *pMem; /* Write results here */
63915 } cg;
63916 struct OP_JournalMode_stack_vars {
63917 Btree *pBt; /* Btree to change journal mode of */
63918 Pager *pPager; /* Pager associated with pBt */
63919 int eNew; /* New journal mode */
63920 int eOld; /* The old journal mode */
63921 const char *zFilename; /* Name of database file for pPager */
63922 } ch;
63923 struct OP_IncrVacuum_stack_vars {
63924 Btree *pBt;
63925 } ci;
63926 struct OP_VBegin_stack_vars {
63927 VTable *pVTab;
63928 } cj;
63929 struct OP_VOpen_stack_vars {
63930 VdbeCursor *pCur;
63931 sqlite3_vtab_cursor *pVtabCursor;
63932 sqlite3_vtab *pVtab;
63933 sqlite3_module *pModule;
63934 } ck;
63935 struct OP_VFilter_stack_vars {
63936 int nArg;
63937 int iQuery;
63938 const sqlite3_module *pModule;
63939 Mem *pQuery;
63940 Mem *pArgc;
63941 sqlite3_vtab_cursor *pVtabCursor;
63942 sqlite3_vtab *pVtab;
63943 VdbeCursor *pCur;
63944 int res;
63945 int i;
63946 Mem **apArg;
63947 } cl;
63948 struct OP_VColumn_stack_vars {
63949 sqlite3_vtab *pVtab;
63950 const sqlite3_module *pModule;
63951 Mem *pDest;
63952 sqlite3_context sContext;
63953 } cm;
63954 struct OP_VNext_stack_vars {
63955 sqlite3_vtab *pVtab;
63956 const sqlite3_module *pModule;
63957 int res;
63958 VdbeCursor *pCur;
63959 } cn;
63960 struct OP_VRename_stack_vars {
63961 sqlite3_vtab *pVtab;
63962 Mem *pName;
63963 } co;
63964 struct OP_VUpdate_stack_vars {
63965 sqlite3_vtab *pVtab;
63966 sqlite3_module *pModule;
63967 int nArg;
63968 int i;
63969 sqlite_int64 rowid;
63970 Mem **apArg;
63971 Mem *pX;
63972 } cp;
63973 struct OP_Trace_stack_vars {
63974 char *zTrace;
63975 char *z;
63976 } cq;
63977 } u;
63978 /* End automatically generated code
63979 ********************************************************************/
63981 assert( p->magic==VDBE_MAGIC_RUN ); /* sqlite3_step() verifies this */
63982 sqlite3VdbeEnter(p);
63983 if( p->rc==SQLITE_NOMEM ){
63984 /* This happens if a malloc() inside a call to sqlite3_column_text() or
63985 ** sqlite3_column_text16() failed. */
63986 goto no_mem;
63988 assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
63989 p->rc = SQLITE_OK;
63990 assert( p->explain==0 );
63991 p->pResultSet = 0;
63992 db->busyHandler.nBusy = 0;
63993 CHECK_FOR_INTERRUPT;
63994 sqlite3VdbeIOTraceSql(p);
63995 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
63996 checkProgress = db->xProgress!=0;
63997 #endif
63998 #ifdef SQLITE_DEBUG
63999 sqlite3BeginBenignMalloc();
64000 if( p->pc==0 && (p->db->flags & SQLITE_VdbeListing)!=0 ){
64001 int i;
64002 printf("VDBE Program Listing:\n");
64003 sqlite3VdbePrintSql(p);
64004 for(i=0; i<p->nOp; i++){
64005 sqlite3VdbePrintOp(stdout, i, &aOp[i]);
64008 sqlite3EndBenignMalloc();
64009 #endif
64010 for(pc=p->pc; rc==SQLITE_OK; pc++){
64011 assert( pc>=0 && pc<p->nOp );
64012 if( db->mallocFailed ) goto no_mem;
64013 #ifdef VDBE_PROFILE
64014 origPc = pc;
64015 start = sqlite3Hwtime();
64016 #endif
64017 pOp = &aOp[pc];
64019 /* Only allow tracing if SQLITE_DEBUG is defined.
64021 #ifdef SQLITE_DEBUG
64022 if( p->trace ){
64023 if( pc==0 ){
64024 printf("VDBE Execution Trace:\n");
64025 sqlite3VdbePrintSql(p);
64027 sqlite3VdbePrintOp(p->trace, pc, pOp);
64029 #endif
64032 /* Check to see if we need to simulate an interrupt. This only happens
64033 ** if we have a special test build.
64035 #ifdef SQLITE_TEST
64036 if( sqlite3_interrupt_count>0 ){
64037 sqlite3_interrupt_count--;
64038 if( sqlite3_interrupt_count==0 ){
64039 sqlite3_interrupt(db);
64042 #endif
64044 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
64045 /* Call the progress callback if it is configured and the required number
64046 ** of VDBE ops have been executed (either since this invocation of
64047 ** sqlite3VdbeExec() or since last time the progress callback was called).
64048 ** If the progress callback returns non-zero, exit the virtual machine with
64049 ** a return code SQLITE_ABORT.
64051 if( checkProgress ){
64052 if( db->nProgressOps==nProgressOps ){
64053 int prc;
64054 prc = db->xProgress(db->pProgressArg);
64055 if( prc!=0 ){
64056 rc = SQLITE_INTERRUPT;
64057 goto vdbe_error_halt;
64059 nProgressOps = 0;
64061 nProgressOps++;
64063 #endif
64065 /* On any opcode with the "out2-prerelase" tag, free any
64066 ** external allocations out of mem[p2] and set mem[p2] to be
64067 ** an undefined integer. Opcodes will either fill in the integer
64068 ** value or convert mem[p2] to a different type.
64070 assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
64071 if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
64072 assert( pOp->p2>0 );
64073 assert( pOp->p2<=p->nMem );
64074 pOut = &aMem[pOp->p2];
64075 memAboutToChange(p, pOut);
64076 MemReleaseExt(pOut);
64077 pOut->flags = MEM_Int;
64080 /* Sanity checking on other operands */
64081 #ifdef SQLITE_DEBUG
64082 if( (pOp->opflags & OPFLG_IN1)!=0 ){
64083 assert( pOp->p1>0 );
64084 assert( pOp->p1<=p->nMem );
64085 assert( memIsValid(&aMem[pOp->p1]) );
64086 REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
64088 if( (pOp->opflags & OPFLG_IN2)!=0 ){
64089 assert( pOp->p2>0 );
64090 assert( pOp->p2<=p->nMem );
64091 assert( memIsValid(&aMem[pOp->p2]) );
64092 REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
64094 if( (pOp->opflags & OPFLG_IN3)!=0 ){
64095 assert( pOp->p3>0 );
64096 assert( pOp->p3<=p->nMem );
64097 assert( memIsValid(&aMem[pOp->p3]) );
64098 REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
64100 if( (pOp->opflags & OPFLG_OUT2)!=0 ){
64101 assert( pOp->p2>0 );
64102 assert( pOp->p2<=p->nMem );
64103 memAboutToChange(p, &aMem[pOp->p2]);
64105 if( (pOp->opflags & OPFLG_OUT3)!=0 ){
64106 assert( pOp->p3>0 );
64107 assert( pOp->p3<=p->nMem );
64108 memAboutToChange(p, &aMem[pOp->p3]);
64110 #endif
64112 switch( pOp->opcode ){
64114 /*****************************************************************************
64115 ** What follows is a massive switch statement where each case implements a
64116 ** separate instruction in the virtual machine. If we follow the usual
64117 ** indentation conventions, each case should be indented by 6 spaces. But
64118 ** that is a lot of wasted space on the left margin. So the code within
64119 ** the switch statement will break with convention and be flush-left. Another
64120 ** big comment (similar to this one) will mark the point in the code where
64121 ** we transition back to normal indentation.
64123 ** The formatting of each case is important. The makefile for SQLite
64124 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
64125 ** file looking for lines that begin with "case OP_". The opcodes.h files
64126 ** will be filled with #defines that give unique integer values to each
64127 ** opcode and the opcodes.c file is filled with an array of strings where
64128 ** each string is the symbolic name for the corresponding opcode. If the
64129 ** case statement is followed by a comment of the form "/# same as ... #/"
64130 ** that comment is used to determine the particular value of the opcode.
64132 ** Other keywords in the comment that follows each case are used to
64133 ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
64134 ** Keywords include: in1, in2, in3, out2_prerelease, out2, out3. See
64135 ** the mkopcodeh.awk script for additional information.
64137 ** Documentation about VDBE opcodes is generated by scanning this file
64138 ** for lines of that contain "Opcode:". That line and all subsequent
64139 ** comment lines are used in the generation of the opcode.html documentation
64140 ** file.
64142 ** SUMMARY:
64144 ** Formatting is important to scripts that scan this file.
64145 ** Do not deviate from the formatting style currently in use.
64147 *****************************************************************************/
64149 /* Opcode: Goto * P2 * * *
64151 ** An unconditional jump to address P2.
64152 ** The next instruction executed will be
64153 ** the one at index P2 from the beginning of
64154 ** the program.
64156 case OP_Goto: { /* jump */
64157 CHECK_FOR_INTERRUPT;
64158 pc = pOp->p2 - 1;
64159 break;
64162 /* Opcode: Gosub P1 P2 * * *
64164 ** Write the current address onto register P1
64165 ** and then jump to address P2.
64167 case OP_Gosub: { /* jump, in1 */
64168 pIn1 = &aMem[pOp->p1];
64169 assert( (pIn1->flags & MEM_Dyn)==0 );
64170 memAboutToChange(p, pIn1);
64171 pIn1->flags = MEM_Int;
64172 pIn1->u.i = pc;
64173 REGISTER_TRACE(pOp->p1, pIn1);
64174 pc = pOp->p2 - 1;
64175 break;
64178 /* Opcode: Return P1 * * * *
64180 ** Jump to the next instruction after the address in register P1.
64182 case OP_Return: { /* in1 */
64183 pIn1 = &aMem[pOp->p1];
64184 assert( pIn1->flags & MEM_Int );
64185 pc = (int)pIn1->u.i;
64186 break;
64189 /* Opcode: Yield P1 * * * *
64191 ** Swap the program counter with the value in register P1.
64193 case OP_Yield: { /* in1 */
64194 #if 0 /* local variables moved into u.aa */
64195 int pcDest;
64196 #endif /* local variables moved into u.aa */
64197 pIn1 = &aMem[pOp->p1];
64198 assert( (pIn1->flags & MEM_Dyn)==0 );
64199 pIn1->flags = MEM_Int;
64200 u.aa.pcDest = (int)pIn1->u.i;
64201 pIn1->u.i = pc;
64202 REGISTER_TRACE(pOp->p1, pIn1);
64203 pc = u.aa.pcDest;
64204 break;
64207 /* Opcode: HaltIfNull P1 P2 P3 P4 *
64209 ** Check the value in register P3. If it is NULL then Halt using
64210 ** parameter P1, P2, and P4 as if this were a Halt instruction. If the
64211 ** value in register P3 is not NULL, then this routine is a no-op.
64213 case OP_HaltIfNull: { /* in3 */
64214 pIn3 = &aMem[pOp->p3];
64215 if( (pIn3->flags & MEM_Null)==0 ) break;
64216 /* Fall through into OP_Halt */
64219 /* Opcode: Halt P1 P2 * P4 *
64221 ** Exit immediately. All open cursors, etc are closed
64222 ** automatically.
64224 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
64225 ** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0).
64226 ** For errors, it can be some other value. If P1!=0 then P2 will determine
64227 ** whether or not to rollback the current transaction. Do not rollback
64228 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort,
64229 ** then back out all changes that have occurred during this execution of the
64230 ** VDBE, but do not rollback the transaction.
64232 ** If P4 is not null then it is an error message string.
64234 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
64235 ** every program. So a jump past the last instruction of the program
64236 ** is the same as executing Halt.
64238 case OP_Halt: {
64239 if( pOp->p1==SQLITE_OK && p->pFrame ){
64240 /* Halt the sub-program. Return control to the parent frame. */
64241 VdbeFrame *pFrame = p->pFrame;
64242 p->pFrame = pFrame->pParent;
64243 p->nFrame--;
64244 sqlite3VdbeSetChanges(db, p->nChange);
64245 pc = sqlite3VdbeFrameRestore(pFrame);
64246 lastRowid = db->lastRowid;
64247 if( pOp->p2==OE_Ignore ){
64248 /* Instruction pc is the OP_Program that invoked the sub-program
64249 ** currently being halted. If the p2 instruction of this OP_Halt
64250 ** instruction is set to OE_Ignore, then the sub-program is throwing
64251 ** an IGNORE exception. In this case jump to the address specified
64252 ** as the p2 of the calling OP_Program. */
64253 pc = p->aOp[pc].p2-1;
64255 aOp = p->aOp;
64256 aMem = p->aMem;
64257 break;
64260 p->rc = pOp->p1;
64261 p->errorAction = (u8)pOp->p2;
64262 p->pc = pc;
64263 if( pOp->p4.z ){
64264 assert( p->rc!=SQLITE_OK );
64265 sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
64266 testcase( sqlite3GlobalConfig.xLog!=0 );
64267 sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pc, p->zSql, pOp->p4.z);
64268 }else if( p->rc ){
64269 testcase( sqlite3GlobalConfig.xLog!=0 );
64270 sqlite3_log(pOp->p1, "constraint failed at %d in [%s]", pc, p->zSql);
64272 rc = sqlite3VdbeHalt(p);
64273 assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
64274 if( rc==SQLITE_BUSY ){
64275 p->rc = rc = SQLITE_BUSY;
64276 }else{
64277 assert( rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT );
64278 assert( rc==SQLITE_OK || db->nDeferredCons>0 );
64279 rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
64281 goto vdbe_return;
64284 /* Opcode: Integer P1 P2 * * *
64286 ** The 32-bit integer value P1 is written into register P2.
64288 case OP_Integer: { /* out2-prerelease */
64289 pOut->u.i = pOp->p1;
64290 break;
64293 /* Opcode: Int64 * P2 * P4 *
64295 ** P4 is a pointer to a 64-bit integer value.
64296 ** Write that value into register P2.
64298 case OP_Int64: { /* out2-prerelease */
64299 assert( pOp->p4.pI64!=0 );
64300 pOut->u.i = *pOp->p4.pI64;
64301 break;
64304 #ifndef SQLITE_OMIT_FLOATING_POINT
64305 /* Opcode: Real * P2 * P4 *
64307 ** P4 is a pointer to a 64-bit floating point value.
64308 ** Write that value into register P2.
64310 case OP_Real: { /* same as TK_FLOAT, out2-prerelease */
64311 pOut->flags = MEM_Real;
64312 assert( !sqlite3IsNaN(*pOp->p4.pReal) );
64313 pOut->r = *pOp->p4.pReal;
64314 break;
64316 #endif
64318 /* Opcode: String8 * P2 * P4 *
64320 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
64321 ** into an OP_String before it is executed for the first time.
64323 case OP_String8: { /* same as TK_STRING, out2-prerelease */
64324 assert( pOp->p4.z!=0 );
64325 pOp->opcode = OP_String;
64326 pOp->p1 = sqlite3Strlen30(pOp->p4.z);
64328 #ifndef SQLITE_OMIT_UTF16
64329 if( encoding!=SQLITE_UTF8 ){
64330 rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
64331 if( rc==SQLITE_TOOBIG ) goto too_big;
64332 if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
64333 assert( pOut->zMalloc==pOut->z );
64334 assert( pOut->flags & MEM_Dyn );
64335 pOut->zMalloc = 0;
64336 pOut->flags |= MEM_Static;
64337 pOut->flags &= ~MEM_Dyn;
64338 if( pOp->p4type==P4_DYNAMIC ){
64339 sqlite3DbFree(db, pOp->p4.z);
64341 pOp->p4type = P4_DYNAMIC;
64342 pOp->p4.z = pOut->z;
64343 pOp->p1 = pOut->n;
64345 #endif
64346 if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
64347 goto too_big;
64349 /* Fall through to the next case, OP_String */
64352 /* Opcode: String P1 P2 * P4 *
64354 ** The string value P4 of length P1 (bytes) is stored in register P2.
64356 case OP_String: { /* out2-prerelease */
64357 assert( pOp->p4.z!=0 );
64358 pOut->flags = MEM_Str|MEM_Static|MEM_Term;
64359 pOut->z = pOp->p4.z;
64360 pOut->n = pOp->p1;
64361 pOut->enc = encoding;
64362 UPDATE_MAX_BLOBSIZE(pOut);
64363 break;
64366 /* Opcode: Null * P2 * * *
64368 ** Write a NULL into register P2.
64370 case OP_Null: { /* out2-prerelease */
64371 pOut->flags = MEM_Null;
64372 break;
64376 /* Opcode: Blob P1 P2 * P4
64378 ** P4 points to a blob of data P1 bytes long. Store this
64379 ** blob in register P2.
64381 case OP_Blob: { /* out2-prerelease */
64382 assert( pOp->p1 <= SQLITE_MAX_LENGTH );
64383 sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
64384 pOut->enc = encoding;
64385 UPDATE_MAX_BLOBSIZE(pOut);
64386 break;
64389 /* Opcode: Variable P1 P2 * P4 *
64391 ** Transfer the values of bound parameter P1 into register P2
64393 ** If the parameter is named, then its name appears in P4 and P3==1.
64394 ** The P4 value is used by sqlite3_bind_parameter_name().
64396 case OP_Variable: { /* out2-prerelease */
64397 #if 0 /* local variables moved into u.ab */
64398 Mem *pVar; /* Value being transferred */
64399 #endif /* local variables moved into u.ab */
64401 assert( pOp->p1>0 && pOp->p1<=p->nVar );
64402 assert( pOp->p4.z==0 || pOp->p4.z==p->azVar[pOp->p1-1] );
64403 u.ab.pVar = &p->aVar[pOp->p1 - 1];
64404 if( sqlite3VdbeMemTooBig(u.ab.pVar) ){
64405 goto too_big;
64407 sqlite3VdbeMemShallowCopy(pOut, u.ab.pVar, MEM_Static);
64408 UPDATE_MAX_BLOBSIZE(pOut);
64409 break;
64412 /* Opcode: Move P1 P2 P3 * *
64414 ** Move the values in register P1..P1+P3-1 over into
64415 ** registers P2..P2+P3-1. Registers P1..P1+P1-1 are
64416 ** left holding a NULL. It is an error for register ranges
64417 ** P1..P1+P3-1 and P2..P2+P3-1 to overlap.
64419 case OP_Move: {
64420 #if 0 /* local variables moved into u.ac */
64421 char *zMalloc; /* Holding variable for allocated memory */
64422 int n; /* Number of registers left to copy */
64423 int p1; /* Register to copy from */
64424 int p2; /* Register to copy to */
64425 #endif /* local variables moved into u.ac */
64427 u.ac.n = pOp->p3;
64428 u.ac.p1 = pOp->p1;
64429 u.ac.p2 = pOp->p2;
64430 assert( u.ac.n>0 && u.ac.p1>0 && u.ac.p2>0 );
64431 assert( u.ac.p1+u.ac.n<=u.ac.p2 || u.ac.p2+u.ac.n<=u.ac.p1 );
64433 pIn1 = &aMem[u.ac.p1];
64434 pOut = &aMem[u.ac.p2];
64435 while( u.ac.n-- ){
64436 assert( pOut<=&aMem[p->nMem] );
64437 assert( pIn1<=&aMem[p->nMem] );
64438 assert( memIsValid(pIn1) );
64439 memAboutToChange(p, pOut);
64440 u.ac.zMalloc = pOut->zMalloc;
64441 pOut->zMalloc = 0;
64442 sqlite3VdbeMemMove(pOut, pIn1);
64443 #ifdef SQLITE_DEBUG
64444 if( pOut->pScopyFrom>=&aMem[u.ac.p1] && pOut->pScopyFrom<&aMem[u.ac.p1+pOp->p3] ){
64445 pOut->pScopyFrom += u.ac.p1 - pOp->p2;
64447 #endif
64448 pIn1->zMalloc = u.ac.zMalloc;
64449 REGISTER_TRACE(u.ac.p2++, pOut);
64450 pIn1++;
64451 pOut++;
64453 break;
64456 /* Opcode: Copy P1 P2 * * *
64458 ** Make a copy of register P1 into register P2.
64460 ** This instruction makes a deep copy of the value. A duplicate
64461 ** is made of any string or blob constant. See also OP_SCopy.
64463 case OP_Copy: { /* in1, out2 */
64464 pIn1 = &aMem[pOp->p1];
64465 pOut = &aMem[pOp->p2];
64466 assert( pOut!=pIn1 );
64467 sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
64468 Deephemeralize(pOut);
64469 REGISTER_TRACE(pOp->p2, pOut);
64470 break;
64473 /* Opcode: SCopy P1 P2 * * *
64475 ** Make a shallow copy of register P1 into register P2.
64477 ** This instruction makes a shallow copy of the value. If the value
64478 ** is a string or blob, then the copy is only a pointer to the
64479 ** original and hence if the original changes so will the copy.
64480 ** Worse, if the original is deallocated, the copy becomes invalid.
64481 ** Thus the program must guarantee that the original will not change
64482 ** during the lifetime of the copy. Use OP_Copy to make a complete
64483 ** copy.
64485 case OP_SCopy: { /* in1, out2 */
64486 pIn1 = &aMem[pOp->p1];
64487 pOut = &aMem[pOp->p2];
64488 assert( pOut!=pIn1 );
64489 sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
64490 #ifdef SQLITE_DEBUG
64491 if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
64492 #endif
64493 REGISTER_TRACE(pOp->p2, pOut);
64494 break;
64497 /* Opcode: ResultRow P1 P2 * * *
64499 ** The registers P1 through P1+P2-1 contain a single row of
64500 ** results. This opcode causes the sqlite3_step() call to terminate
64501 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
64502 ** structure to provide access to the top P1 values as the result
64503 ** row.
64505 case OP_ResultRow: {
64506 #if 0 /* local variables moved into u.ad */
64507 Mem *pMem;
64508 int i;
64509 #endif /* local variables moved into u.ad */
64510 assert( p->nResColumn==pOp->p2 );
64511 assert( pOp->p1>0 );
64512 assert( pOp->p1+pOp->p2<=p->nMem+1 );
64514 /* If this statement has violated immediate foreign key constraints, do
64515 ** not return the number of rows modified. And do not RELEASE the statement
64516 ** transaction. It needs to be rolled back. */
64517 if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
64518 assert( db->flags&SQLITE_CountRows );
64519 assert( p->usesStmtJournal );
64520 break;
64523 /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
64524 ** DML statements invoke this opcode to return the number of rows
64525 ** modified to the user. This is the only way that a VM that
64526 ** opens a statement transaction may invoke this opcode.
64528 ** In case this is such a statement, close any statement transaction
64529 ** opened by this VM before returning control to the user. This is to
64530 ** ensure that statement-transactions are always nested, not overlapping.
64531 ** If the open statement-transaction is not closed here, then the user
64532 ** may step another VM that opens its own statement transaction. This
64533 ** may lead to overlapping statement transactions.
64535 ** The statement transaction is never a top-level transaction. Hence
64536 ** the RELEASE call below can never fail.
64538 assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
64539 rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
64540 if( NEVER(rc!=SQLITE_OK) ){
64541 break;
64544 /* Invalidate all ephemeral cursor row caches */
64545 p->cacheCtr = (p->cacheCtr + 2)|1;
64547 /* Make sure the results of the current row are \000 terminated
64548 ** and have an assigned type. The results are de-ephemeralized as
64549 ** as side effect.
64551 u.ad.pMem = p->pResultSet = &aMem[pOp->p1];
64552 for(u.ad.i=0; u.ad.i<pOp->p2; u.ad.i++){
64553 assert( memIsValid(&u.ad.pMem[u.ad.i]) );
64554 Deephemeralize(&u.ad.pMem[u.ad.i]);
64555 assert( (u.ad.pMem[u.ad.i].flags & MEM_Ephem)==0
64556 || (u.ad.pMem[u.ad.i].flags & (MEM_Str|MEM_Blob))==0 );
64557 sqlite3VdbeMemNulTerminate(&u.ad.pMem[u.ad.i]);
64558 sqlite3VdbeMemStoreType(&u.ad.pMem[u.ad.i]);
64559 REGISTER_TRACE(pOp->p1+u.ad.i, &u.ad.pMem[u.ad.i]);
64561 if( db->mallocFailed ) goto no_mem;
64563 /* Return SQLITE_ROW
64565 p->pc = pc + 1;
64566 rc = SQLITE_ROW;
64567 goto vdbe_return;
64570 /* Opcode: Concat P1 P2 P3 * *
64572 ** Add the text in register P1 onto the end of the text in
64573 ** register P2 and store the result in register P3.
64574 ** If either the P1 or P2 text are NULL then store NULL in P3.
64576 ** P3 = P2 || P1
64578 ** It is illegal for P1 and P3 to be the same register. Sometimes,
64579 ** if P3 is the same register as P2, the implementation is able
64580 ** to avoid a memcpy().
64582 case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */
64583 #if 0 /* local variables moved into u.ae */
64584 i64 nByte;
64585 #endif /* local variables moved into u.ae */
64587 pIn1 = &aMem[pOp->p1];
64588 pIn2 = &aMem[pOp->p2];
64589 pOut = &aMem[pOp->p3];
64590 assert( pIn1!=pOut );
64591 if( (pIn1->flags | pIn2->flags) & MEM_Null ){
64592 sqlite3VdbeMemSetNull(pOut);
64593 break;
64595 if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
64596 Stringify(pIn1, encoding);
64597 Stringify(pIn2, encoding);
64598 u.ae.nByte = pIn1->n + pIn2->n;
64599 if( u.ae.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
64600 goto too_big;
64602 MemSetTypeFlag(pOut, MEM_Str);
64603 if( sqlite3VdbeMemGrow(pOut, (int)u.ae.nByte+2, pOut==pIn2) ){
64604 goto no_mem;
64606 if( pOut!=pIn2 ){
64607 memcpy(pOut->z, pIn2->z, pIn2->n);
64609 memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
64610 pOut->z[u.ae.nByte] = 0;
64611 pOut->z[u.ae.nByte+1] = 0;
64612 pOut->flags |= MEM_Term;
64613 pOut->n = (int)u.ae.nByte;
64614 pOut->enc = encoding;
64615 UPDATE_MAX_BLOBSIZE(pOut);
64616 break;
64619 /* Opcode: Add P1 P2 P3 * *
64621 ** Add the value in register P1 to the value in register P2
64622 ** and store the result in register P3.
64623 ** If either input is NULL, the result is NULL.
64625 /* Opcode: Multiply P1 P2 P3 * *
64628 ** Multiply the value in register P1 by the value in register P2
64629 ** and store the result in register P3.
64630 ** If either input is NULL, the result is NULL.
64632 /* Opcode: Subtract P1 P2 P3 * *
64634 ** Subtract the value in register P1 from the value in register P2
64635 ** and store the result in register P3.
64636 ** If either input is NULL, the result is NULL.
64638 /* Opcode: Divide P1 P2 P3 * *
64640 ** Divide the value in register P1 by the value in register P2
64641 ** and store the result in register P3 (P3=P2/P1). If the value in
64642 ** register P1 is zero, then the result is NULL. If either input is
64643 ** NULL, the result is NULL.
64645 /* Opcode: Remainder P1 P2 P3 * *
64647 ** Compute the remainder after integer division of the value in
64648 ** register P1 by the value in register P2 and store the result in P3.
64649 ** If the value in register P2 is zero the result is NULL.
64650 ** If either operand is NULL, the result is NULL.
64652 case OP_Add: /* same as TK_PLUS, in1, in2, out3 */
64653 case OP_Subtract: /* same as TK_MINUS, in1, in2, out3 */
64654 case OP_Multiply: /* same as TK_STAR, in1, in2, out3 */
64655 case OP_Divide: /* same as TK_SLASH, in1, in2, out3 */
64656 case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */
64657 #if 0 /* local variables moved into u.af */
64658 int flags; /* Combined MEM_* flags from both inputs */
64659 i64 iA; /* Integer value of left operand */
64660 i64 iB; /* Integer value of right operand */
64661 double rA; /* Real value of left operand */
64662 double rB; /* Real value of right operand */
64663 #endif /* local variables moved into u.af */
64665 pIn1 = &aMem[pOp->p1];
64666 applyNumericAffinity(pIn1);
64667 pIn2 = &aMem[pOp->p2];
64668 applyNumericAffinity(pIn2);
64669 pOut = &aMem[pOp->p3];
64670 u.af.flags = pIn1->flags | pIn2->flags;
64671 if( (u.af.flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
64672 if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){
64673 u.af.iA = pIn1->u.i;
64674 u.af.iB = pIn2->u.i;
64675 switch( pOp->opcode ){
64676 case OP_Add: if( sqlite3AddInt64(&u.af.iB,u.af.iA) ) goto fp_math; break;
64677 case OP_Subtract: if( sqlite3SubInt64(&u.af.iB,u.af.iA) ) goto fp_math; break;
64678 case OP_Multiply: if( sqlite3MulInt64(&u.af.iB,u.af.iA) ) goto fp_math; break;
64679 case OP_Divide: {
64680 if( u.af.iA==0 ) goto arithmetic_result_is_null;
64681 if( u.af.iA==-1 && u.af.iB==SMALLEST_INT64 ) goto fp_math;
64682 u.af.iB /= u.af.iA;
64683 break;
64685 default: {
64686 if( u.af.iA==0 ) goto arithmetic_result_is_null;
64687 if( u.af.iA==-1 ) u.af.iA = 1;
64688 u.af.iB %= u.af.iA;
64689 break;
64692 pOut->u.i = u.af.iB;
64693 MemSetTypeFlag(pOut, MEM_Int);
64694 }else{
64695 fp_math:
64696 u.af.rA = sqlite3VdbeRealValue(pIn1);
64697 u.af.rB = sqlite3VdbeRealValue(pIn2);
64698 switch( pOp->opcode ){
64699 case OP_Add: u.af.rB += u.af.rA; break;
64700 case OP_Subtract: u.af.rB -= u.af.rA; break;
64701 case OP_Multiply: u.af.rB *= u.af.rA; break;
64702 case OP_Divide: {
64703 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
64704 if( u.af.rA==(double)0 ) goto arithmetic_result_is_null;
64705 u.af.rB /= u.af.rA;
64706 break;
64708 default: {
64709 u.af.iA = (i64)u.af.rA;
64710 u.af.iB = (i64)u.af.rB;
64711 if( u.af.iA==0 ) goto arithmetic_result_is_null;
64712 if( u.af.iA==-1 ) u.af.iA = 1;
64713 u.af.rB = (double)(u.af.iB % u.af.iA);
64714 break;
64717 #ifdef SQLITE_OMIT_FLOATING_POINT
64718 pOut->u.i = u.af.rB;
64719 MemSetTypeFlag(pOut, MEM_Int);
64720 #else
64721 if( sqlite3IsNaN(u.af.rB) ){
64722 goto arithmetic_result_is_null;
64724 pOut->r = u.af.rB;
64725 MemSetTypeFlag(pOut, MEM_Real);
64726 if( (u.af.flags & MEM_Real)==0 ){
64727 sqlite3VdbeIntegerAffinity(pOut);
64729 #endif
64731 break;
64733 arithmetic_result_is_null:
64734 sqlite3VdbeMemSetNull(pOut);
64735 break;
64738 /* Opcode: CollSeq * * P4
64740 ** P4 is a pointer to a CollSeq struct. If the next call to a user function
64741 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
64742 ** be returned. This is used by the built-in min(), max() and nullif()
64743 ** functions.
64745 ** The interface used by the implementation of the aforementioned functions
64746 ** to retrieve the collation sequence set by this opcode is not available
64747 ** publicly, only to user functions defined in func.c.
64749 case OP_CollSeq: {
64750 assert( pOp->p4type==P4_COLLSEQ );
64751 break;
64754 /* Opcode: Function P1 P2 P3 P4 P5
64756 ** Invoke a user function (P4 is a pointer to a Function structure that
64757 ** defines the function) with P5 arguments taken from register P2 and
64758 ** successors. The result of the function is stored in register P3.
64759 ** Register P3 must not be one of the function inputs.
64761 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
64762 ** function was determined to be constant at compile time. If the first
64763 ** argument was constant then bit 0 of P1 is set. This is used to determine
64764 ** whether meta data associated with a user function argument using the
64765 ** sqlite3_set_auxdata() API may be safely retained until the next
64766 ** invocation of this opcode.
64768 ** See also: AggStep and AggFinal
64770 case OP_Function: {
64771 #if 0 /* local variables moved into u.ag */
64772 int i;
64773 Mem *pArg;
64774 sqlite3_context ctx;
64775 sqlite3_value **apVal;
64776 int n;
64777 #endif /* local variables moved into u.ag */
64779 u.ag.n = pOp->p5;
64780 u.ag.apVal = p->apArg;
64781 assert( u.ag.apVal || u.ag.n==0 );
64782 assert( pOp->p3>0 && pOp->p3<=p->nMem );
64783 pOut = &aMem[pOp->p3];
64784 memAboutToChange(p, pOut);
64786 assert( u.ag.n==0 || (pOp->p2>0 && pOp->p2+u.ag.n<=p->nMem+1) );
64787 assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+u.ag.n );
64788 u.ag.pArg = &aMem[pOp->p2];
64789 for(u.ag.i=0; u.ag.i<u.ag.n; u.ag.i++, u.ag.pArg++){
64790 assert( memIsValid(u.ag.pArg) );
64791 u.ag.apVal[u.ag.i] = u.ag.pArg;
64792 Deephemeralize(u.ag.pArg);
64793 sqlite3VdbeMemStoreType(u.ag.pArg);
64794 REGISTER_TRACE(pOp->p2+u.ag.i, u.ag.pArg);
64797 assert( pOp->p4type==P4_FUNCDEF || pOp->p4type==P4_VDBEFUNC );
64798 if( pOp->p4type==P4_FUNCDEF ){
64799 u.ag.ctx.pFunc = pOp->p4.pFunc;
64800 u.ag.ctx.pVdbeFunc = 0;
64801 }else{
64802 u.ag.ctx.pVdbeFunc = (VdbeFunc*)pOp->p4.pVdbeFunc;
64803 u.ag.ctx.pFunc = u.ag.ctx.pVdbeFunc->pFunc;
64806 u.ag.ctx.s.flags = MEM_Null;
64807 u.ag.ctx.s.db = db;
64808 u.ag.ctx.s.xDel = 0;
64809 u.ag.ctx.s.zMalloc = 0;
64811 /* The output cell may already have a buffer allocated. Move
64812 ** the pointer to u.ag.ctx.s so in case the user-function can use
64813 ** the already allocated buffer instead of allocating a new one.
64815 sqlite3VdbeMemMove(&u.ag.ctx.s, pOut);
64816 MemSetTypeFlag(&u.ag.ctx.s, MEM_Null);
64818 u.ag.ctx.isError = 0;
64819 if( u.ag.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
64820 assert( pOp>aOp );
64821 assert( pOp[-1].p4type==P4_COLLSEQ );
64822 assert( pOp[-1].opcode==OP_CollSeq );
64823 u.ag.ctx.pColl = pOp[-1].p4.pColl;
64825 db->lastRowid = lastRowid;
64826 (*u.ag.ctx.pFunc->xFunc)(&u.ag.ctx, u.ag.n, u.ag.apVal); /* IMP: R-24505-23230 */
64827 lastRowid = db->lastRowid;
64829 /* If any auxiliary data functions have been called by this user function,
64830 ** immediately call the destructor for any non-static values.
64832 if( u.ag.ctx.pVdbeFunc ){
64833 sqlite3VdbeDeleteAuxData(u.ag.ctx.pVdbeFunc, pOp->p1);
64834 pOp->p4.pVdbeFunc = u.ag.ctx.pVdbeFunc;
64835 pOp->p4type = P4_VDBEFUNC;
64838 if( db->mallocFailed ){
64839 /* Even though a malloc() has failed, the implementation of the
64840 ** user function may have called an sqlite3_result_XXX() function
64841 ** to return a value. The following call releases any resources
64842 ** associated with such a value.
64844 sqlite3VdbeMemRelease(&u.ag.ctx.s);
64845 goto no_mem;
64848 /* If the function returned an error, throw an exception */
64849 if( u.ag.ctx.isError ){
64850 sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.ag.ctx.s));
64851 rc = u.ag.ctx.isError;
64854 /* Copy the result of the function into register P3 */
64855 sqlite3VdbeChangeEncoding(&u.ag.ctx.s, encoding);
64856 sqlite3VdbeMemMove(pOut, &u.ag.ctx.s);
64857 if( sqlite3VdbeMemTooBig(pOut) ){
64858 goto too_big;
64861 #if 0
64862 /* The app-defined function has done something that as caused this
64863 ** statement to expire. (Perhaps the function called sqlite3_exec()
64864 ** with a CREATE TABLE statement.)
64866 if( p->expired ) rc = SQLITE_ABORT;
64867 #endif
64869 REGISTER_TRACE(pOp->p3, pOut);
64870 UPDATE_MAX_BLOBSIZE(pOut);
64871 break;
64874 /* Opcode: BitAnd P1 P2 P3 * *
64876 ** Take the bit-wise AND of the values in register P1 and P2 and
64877 ** store the result in register P3.
64878 ** If either input is NULL, the result is NULL.
64880 /* Opcode: BitOr P1 P2 P3 * *
64882 ** Take the bit-wise OR of the values in register P1 and P2 and
64883 ** store the result in register P3.
64884 ** If either input is NULL, the result is NULL.
64886 /* Opcode: ShiftLeft P1 P2 P3 * *
64888 ** Shift the integer value in register P2 to the left by the
64889 ** number of bits specified by the integer in register P1.
64890 ** Store the result in register P3.
64891 ** If either input is NULL, the result is NULL.
64893 /* Opcode: ShiftRight P1 P2 P3 * *
64895 ** Shift the integer value in register P2 to the right by the
64896 ** number of bits specified by the integer in register P1.
64897 ** Store the result in register P3.
64898 ** If either input is NULL, the result is NULL.
64900 case OP_BitAnd: /* same as TK_BITAND, in1, in2, out3 */
64901 case OP_BitOr: /* same as TK_BITOR, in1, in2, out3 */
64902 case OP_ShiftLeft: /* same as TK_LSHIFT, in1, in2, out3 */
64903 case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */
64904 #if 0 /* local variables moved into u.ah */
64905 i64 iA;
64906 u64 uA;
64907 i64 iB;
64908 u8 op;
64909 #endif /* local variables moved into u.ah */
64911 pIn1 = &aMem[pOp->p1];
64912 pIn2 = &aMem[pOp->p2];
64913 pOut = &aMem[pOp->p3];
64914 if( (pIn1->flags | pIn2->flags) & MEM_Null ){
64915 sqlite3VdbeMemSetNull(pOut);
64916 break;
64918 u.ah.iA = sqlite3VdbeIntValue(pIn2);
64919 u.ah.iB = sqlite3VdbeIntValue(pIn1);
64920 u.ah.op = pOp->opcode;
64921 if( u.ah.op==OP_BitAnd ){
64922 u.ah.iA &= u.ah.iB;
64923 }else if( u.ah.op==OP_BitOr ){
64924 u.ah.iA |= u.ah.iB;
64925 }else if( u.ah.iB!=0 ){
64926 assert( u.ah.op==OP_ShiftRight || u.ah.op==OP_ShiftLeft );
64928 /* If shifting by a negative amount, shift in the other direction */
64929 if( u.ah.iB<0 ){
64930 assert( OP_ShiftRight==OP_ShiftLeft+1 );
64931 u.ah.op = 2*OP_ShiftLeft + 1 - u.ah.op;
64932 u.ah.iB = u.ah.iB>(-64) ? -u.ah.iB : 64;
64935 if( u.ah.iB>=64 ){
64936 u.ah.iA = (u.ah.iA>=0 || u.ah.op==OP_ShiftLeft) ? 0 : -1;
64937 }else{
64938 memcpy(&u.ah.uA, &u.ah.iA, sizeof(u.ah.uA));
64939 if( u.ah.op==OP_ShiftLeft ){
64940 u.ah.uA <<= u.ah.iB;
64941 }else{
64942 u.ah.uA >>= u.ah.iB;
64943 /* Sign-extend on a right shift of a negative number */
64944 if( u.ah.iA<0 ) u.ah.uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-u.ah.iB);
64946 memcpy(&u.ah.iA, &u.ah.uA, sizeof(u.ah.iA));
64949 pOut->u.i = u.ah.iA;
64950 MemSetTypeFlag(pOut, MEM_Int);
64951 break;
64954 /* Opcode: AddImm P1 P2 * * *
64956 ** Add the constant P2 to the value in register P1.
64957 ** The result is always an integer.
64959 ** To force any register to be an integer, just add 0.
64961 case OP_AddImm: { /* in1 */
64962 pIn1 = &aMem[pOp->p1];
64963 memAboutToChange(p, pIn1);
64964 sqlite3VdbeMemIntegerify(pIn1);
64965 pIn1->u.i += pOp->p2;
64966 break;
64969 /* Opcode: MustBeInt P1 P2 * * *
64971 ** Force the value in register P1 to be an integer. If the value
64972 ** in P1 is not an integer and cannot be converted into an integer
64973 ** without data loss, then jump immediately to P2, or if P2==0
64974 ** raise an SQLITE_MISMATCH exception.
64976 case OP_MustBeInt: { /* jump, in1 */
64977 pIn1 = &aMem[pOp->p1];
64978 applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
64979 if( (pIn1->flags & MEM_Int)==0 ){
64980 if( pOp->p2==0 ){
64981 rc = SQLITE_MISMATCH;
64982 goto abort_due_to_error;
64983 }else{
64984 pc = pOp->p2 - 1;
64986 }else{
64987 MemSetTypeFlag(pIn1, MEM_Int);
64989 break;
64992 #ifndef SQLITE_OMIT_FLOATING_POINT
64993 /* Opcode: RealAffinity P1 * * * *
64995 ** If register P1 holds an integer convert it to a real value.
64997 ** This opcode is used when extracting information from a column that
64998 ** has REAL affinity. Such column values may still be stored as
64999 ** integers, for space efficiency, but after extraction we want them
65000 ** to have only a real value.
65002 case OP_RealAffinity: { /* in1 */
65003 pIn1 = &aMem[pOp->p1];
65004 if( pIn1->flags & MEM_Int ){
65005 sqlite3VdbeMemRealify(pIn1);
65007 break;
65009 #endif
65011 #ifndef SQLITE_OMIT_CAST
65012 /* Opcode: ToText P1 * * * *
65014 ** Force the value in register P1 to be text.
65015 ** If the value is numeric, convert it to a string using the
65016 ** equivalent of printf(). Blob values are unchanged and
65017 ** are afterwards simply interpreted as text.
65019 ** A NULL value is not changed by this routine. It remains NULL.
65021 case OP_ToText: { /* same as TK_TO_TEXT, in1 */
65022 pIn1 = &aMem[pOp->p1];
65023 memAboutToChange(p, pIn1);
65024 if( pIn1->flags & MEM_Null ) break;
65025 assert( MEM_Str==(MEM_Blob>>3) );
65026 pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
65027 applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
65028 rc = ExpandBlob(pIn1);
65029 assert( pIn1->flags & MEM_Str || db->mallocFailed );
65030 pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
65031 UPDATE_MAX_BLOBSIZE(pIn1);
65032 break;
65035 /* Opcode: ToBlob P1 * * * *
65037 ** Force the value in register P1 to be a BLOB.
65038 ** If the value is numeric, convert it to a string first.
65039 ** Strings are simply reinterpreted as blobs with no change
65040 ** to the underlying data.
65042 ** A NULL value is not changed by this routine. It remains NULL.
65044 case OP_ToBlob: { /* same as TK_TO_BLOB, in1 */
65045 pIn1 = &aMem[pOp->p1];
65046 if( pIn1->flags & MEM_Null ) break;
65047 if( (pIn1->flags & MEM_Blob)==0 ){
65048 applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
65049 assert( pIn1->flags & MEM_Str || db->mallocFailed );
65050 MemSetTypeFlag(pIn1, MEM_Blob);
65051 }else{
65052 pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob);
65054 UPDATE_MAX_BLOBSIZE(pIn1);
65055 break;
65058 /* Opcode: ToNumeric P1 * * * *
65060 ** Force the value in register P1 to be numeric (either an
65061 ** integer or a floating-point number.)
65062 ** If the value is text or blob, try to convert it to an using the
65063 ** equivalent of atoi() or atof() and store 0 if no such conversion
65064 ** is possible.
65066 ** A NULL value is not changed by this routine. It remains NULL.
65068 case OP_ToNumeric: { /* same as TK_TO_NUMERIC, in1 */
65069 pIn1 = &aMem[pOp->p1];
65070 sqlite3VdbeMemNumerify(pIn1);
65071 break;
65073 #endif /* SQLITE_OMIT_CAST */
65075 /* Opcode: ToInt P1 * * * *
65077 ** Force the value in register P1 to be an integer. If
65078 ** The value is currently a real number, drop its fractional part.
65079 ** If the value is text or blob, try to convert it to an integer using the
65080 ** equivalent of atoi() and store 0 if no such conversion is possible.
65082 ** A NULL value is not changed by this routine. It remains NULL.
65084 case OP_ToInt: { /* same as TK_TO_INT, in1 */
65085 pIn1 = &aMem[pOp->p1];
65086 if( (pIn1->flags & MEM_Null)==0 ){
65087 sqlite3VdbeMemIntegerify(pIn1);
65089 break;
65092 #if !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT)
65093 /* Opcode: ToReal P1 * * * *
65095 ** Force the value in register P1 to be a floating point number.
65096 ** If The value is currently an integer, convert it.
65097 ** If the value is text or blob, try to convert it to an integer using the
65098 ** equivalent of atoi() and store 0.0 if no such conversion is possible.
65100 ** A NULL value is not changed by this routine. It remains NULL.
65102 case OP_ToReal: { /* same as TK_TO_REAL, in1 */
65103 pIn1 = &aMem[pOp->p1];
65104 memAboutToChange(p, pIn1);
65105 if( (pIn1->flags & MEM_Null)==0 ){
65106 sqlite3VdbeMemRealify(pIn1);
65108 break;
65110 #endif /* !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT) */
65112 /* Opcode: Lt P1 P2 P3 P4 P5
65114 ** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then
65115 ** jump to address P2.
65117 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
65118 ** reg(P3) is NULL then take the jump. If the SQLITE_JUMPIFNULL
65119 ** bit is clear then fall through if either operand is NULL.
65121 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
65122 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
65123 ** to coerce both inputs according to this affinity before the
65124 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
65125 ** affinity is used. Note that the affinity conversions are stored
65126 ** back into the input registers P1 and P3. So this opcode can cause
65127 ** persistent changes to registers P1 and P3.
65129 ** Once any conversions have taken place, and neither value is NULL,
65130 ** the values are compared. If both values are blobs then memcmp() is
65131 ** used to determine the results of the comparison. If both values
65132 ** are text, then the appropriate collating function specified in
65133 ** P4 is used to do the comparison. If P4 is not specified then
65134 ** memcmp() is used to compare text string. If both values are
65135 ** numeric, then a numeric comparison is used. If the two values
65136 ** are of different types, then numbers are considered less than
65137 ** strings and strings are considered less than blobs.
65139 ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump. Instead,
65140 ** store a boolean result (either 0, or 1, or NULL) in register P2.
65142 /* Opcode: Ne P1 P2 P3 P4 P5
65144 ** This works just like the Lt opcode except that the jump is taken if
65145 ** the operands in registers P1 and P3 are not equal. See the Lt opcode for
65146 ** additional information.
65148 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
65149 ** true or false and is never NULL. If both operands are NULL then the result
65150 ** of comparison is false. If either operand is NULL then the result is true.
65151 ** If neither operand is NULL the result is the same as it would be if
65152 ** the SQLITE_NULLEQ flag were omitted from P5.
65154 /* Opcode: Eq P1 P2 P3 P4 P5
65156 ** This works just like the Lt opcode except that the jump is taken if
65157 ** the operands in registers P1 and P3 are equal.
65158 ** See the Lt opcode for additional information.
65160 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
65161 ** true or false and is never NULL. If both operands are NULL then the result
65162 ** of comparison is true. If either operand is NULL then the result is false.
65163 ** If neither operand is NULL the result is the same as it would be if
65164 ** the SQLITE_NULLEQ flag were omitted from P5.
65166 /* Opcode: Le P1 P2 P3 P4 P5
65168 ** This works just like the Lt opcode except that the jump is taken if
65169 ** the content of register P3 is less than or equal to the content of
65170 ** register P1. See the Lt opcode for additional information.
65172 /* Opcode: Gt P1 P2 P3 P4 P5
65174 ** This works just like the Lt opcode except that the jump is taken if
65175 ** the content of register P3 is greater than the content of
65176 ** register P1. See the Lt opcode for additional information.
65178 /* Opcode: Ge P1 P2 P3 P4 P5
65180 ** This works just like the Lt opcode except that the jump is taken if
65181 ** the content of register P3 is greater than or equal to the content of
65182 ** register P1. See the Lt opcode for additional information.
65184 case OP_Eq: /* same as TK_EQ, jump, in1, in3 */
65185 case OP_Ne: /* same as TK_NE, jump, in1, in3 */
65186 case OP_Lt: /* same as TK_LT, jump, in1, in3 */
65187 case OP_Le: /* same as TK_LE, jump, in1, in3 */
65188 case OP_Gt: /* same as TK_GT, jump, in1, in3 */
65189 case OP_Ge: { /* same as TK_GE, jump, in1, in3 */
65190 #if 0 /* local variables moved into u.ai */
65191 int res; /* Result of the comparison of pIn1 against pIn3 */
65192 char affinity; /* Affinity to use for comparison */
65193 u16 flags1; /* Copy of initial value of pIn1->flags */
65194 u16 flags3; /* Copy of initial value of pIn3->flags */
65195 #endif /* local variables moved into u.ai */
65197 pIn1 = &aMem[pOp->p1];
65198 pIn3 = &aMem[pOp->p3];
65199 u.ai.flags1 = pIn1->flags;
65200 u.ai.flags3 = pIn3->flags;
65201 if( (u.ai.flags1 | u.ai.flags3)&MEM_Null ){
65202 /* One or both operands are NULL */
65203 if( pOp->p5 & SQLITE_NULLEQ ){
65204 /* If SQLITE_NULLEQ is set (which will only happen if the operator is
65205 ** OP_Eq or OP_Ne) then take the jump or not depending on whether
65206 ** or not both operands are null.
65208 assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
65209 u.ai.res = (u.ai.flags1 & u.ai.flags3 & MEM_Null)==0;
65210 }else{
65211 /* SQLITE_NULLEQ is clear and at least one operand is NULL,
65212 ** then the result is always NULL.
65213 ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
65215 if( pOp->p5 & SQLITE_STOREP2 ){
65216 pOut = &aMem[pOp->p2];
65217 MemSetTypeFlag(pOut, MEM_Null);
65218 REGISTER_TRACE(pOp->p2, pOut);
65219 }else if( pOp->p5 & SQLITE_JUMPIFNULL ){
65220 pc = pOp->p2-1;
65222 break;
65224 }else{
65225 /* Neither operand is NULL. Do a comparison. */
65226 u.ai.affinity = pOp->p5 & SQLITE_AFF_MASK;
65227 if( u.ai.affinity ){
65228 applyAffinity(pIn1, u.ai.affinity, encoding);
65229 applyAffinity(pIn3, u.ai.affinity, encoding);
65230 if( db->mallocFailed ) goto no_mem;
65233 assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
65234 ExpandBlob(pIn1);
65235 ExpandBlob(pIn3);
65236 u.ai.res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
65238 switch( pOp->opcode ){
65239 case OP_Eq: u.ai.res = u.ai.res==0; break;
65240 case OP_Ne: u.ai.res = u.ai.res!=0; break;
65241 case OP_Lt: u.ai.res = u.ai.res<0; break;
65242 case OP_Le: u.ai.res = u.ai.res<=0; break;
65243 case OP_Gt: u.ai.res = u.ai.res>0; break;
65244 default: u.ai.res = u.ai.res>=0; break;
65247 if( pOp->p5 & SQLITE_STOREP2 ){
65248 pOut = &aMem[pOp->p2];
65249 memAboutToChange(p, pOut);
65250 MemSetTypeFlag(pOut, MEM_Int);
65251 pOut->u.i = u.ai.res;
65252 REGISTER_TRACE(pOp->p2, pOut);
65253 }else if( u.ai.res ){
65254 pc = pOp->p2-1;
65257 /* Undo any changes made by applyAffinity() to the input registers. */
65258 pIn1->flags = (pIn1->flags&~MEM_TypeMask) | (u.ai.flags1&MEM_TypeMask);
65259 pIn3->flags = (pIn3->flags&~MEM_TypeMask) | (u.ai.flags3&MEM_TypeMask);
65260 break;
65263 /* Opcode: Permutation * * * P4 *
65265 ** Set the permutation used by the OP_Compare operator to be the array
65266 ** of integers in P4.
65268 ** The permutation is only valid until the next OP_Permutation, OP_Compare,
65269 ** OP_Halt, or OP_ResultRow. Typically the OP_Permutation should occur
65270 ** immediately prior to the OP_Compare.
65272 case OP_Permutation: {
65273 assert( pOp->p4type==P4_INTARRAY );
65274 assert( pOp->p4.ai );
65275 aPermute = pOp->p4.ai;
65276 break;
65279 /* Opcode: Compare P1 P2 P3 P4 *
65281 ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
65282 ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of
65283 ** the comparison for use by the next OP_Jump instruct.
65285 ** P4 is a KeyInfo structure that defines collating sequences and sort
65286 ** orders for the comparison. The permutation applies to registers
65287 ** only. The KeyInfo elements are used sequentially.
65289 ** The comparison is a sort comparison, so NULLs compare equal,
65290 ** NULLs are less than numbers, numbers are less than strings,
65291 ** and strings are less than blobs.
65293 case OP_Compare: {
65294 #if 0 /* local variables moved into u.aj */
65295 int n;
65296 int i;
65297 int p1;
65298 int p2;
65299 const KeyInfo *pKeyInfo;
65300 int idx;
65301 CollSeq *pColl; /* Collating sequence to use on this term */
65302 int bRev; /* True for DESCENDING sort order */
65303 #endif /* local variables moved into u.aj */
65305 u.aj.n = pOp->p3;
65306 u.aj.pKeyInfo = pOp->p4.pKeyInfo;
65307 assert( u.aj.n>0 );
65308 assert( u.aj.pKeyInfo!=0 );
65309 u.aj.p1 = pOp->p1;
65310 u.aj.p2 = pOp->p2;
65311 #if SQLITE_DEBUG
65312 if( aPermute ){
65313 int k, mx = 0;
65314 for(k=0; k<u.aj.n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
65315 assert( u.aj.p1>0 && u.aj.p1+mx<=p->nMem+1 );
65316 assert( u.aj.p2>0 && u.aj.p2+mx<=p->nMem+1 );
65317 }else{
65318 assert( u.aj.p1>0 && u.aj.p1+u.aj.n<=p->nMem+1 );
65319 assert( u.aj.p2>0 && u.aj.p2+u.aj.n<=p->nMem+1 );
65321 #endif /* SQLITE_DEBUG */
65322 for(u.aj.i=0; u.aj.i<u.aj.n; u.aj.i++){
65323 u.aj.idx = aPermute ? aPermute[u.aj.i] : u.aj.i;
65324 assert( memIsValid(&aMem[u.aj.p1+u.aj.idx]) );
65325 assert( memIsValid(&aMem[u.aj.p2+u.aj.idx]) );
65326 REGISTER_TRACE(u.aj.p1+u.aj.idx, &aMem[u.aj.p1+u.aj.idx]);
65327 REGISTER_TRACE(u.aj.p2+u.aj.idx, &aMem[u.aj.p2+u.aj.idx]);
65328 assert( u.aj.i<u.aj.pKeyInfo->nField );
65329 u.aj.pColl = u.aj.pKeyInfo->aColl[u.aj.i];
65330 u.aj.bRev = u.aj.pKeyInfo->aSortOrder[u.aj.i];
65331 iCompare = sqlite3MemCompare(&aMem[u.aj.p1+u.aj.idx], &aMem[u.aj.p2+u.aj.idx], u.aj.pColl);
65332 if( iCompare ){
65333 if( u.aj.bRev ) iCompare = -iCompare;
65334 break;
65337 aPermute = 0;
65338 break;
65341 /* Opcode: Jump P1 P2 P3 * *
65343 ** Jump to the instruction at address P1, P2, or P3 depending on whether
65344 ** in the most recent OP_Compare instruction the P1 vector was less than
65345 ** equal to, or greater than the P2 vector, respectively.
65347 case OP_Jump: { /* jump */
65348 if( iCompare<0 ){
65349 pc = pOp->p1 - 1;
65350 }else if( iCompare==0 ){
65351 pc = pOp->p2 - 1;
65352 }else{
65353 pc = pOp->p3 - 1;
65355 break;
65358 /* Opcode: And P1 P2 P3 * *
65360 ** Take the logical AND of the values in registers P1 and P2 and
65361 ** write the result into register P3.
65363 ** If either P1 or P2 is 0 (false) then the result is 0 even if
65364 ** the other input is NULL. A NULL and true or two NULLs give
65365 ** a NULL output.
65367 /* Opcode: Or P1 P2 P3 * *
65369 ** Take the logical OR of the values in register P1 and P2 and
65370 ** store the answer in register P3.
65372 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
65373 ** even if the other input is NULL. A NULL and false or two NULLs
65374 ** give a NULL output.
65376 case OP_And: /* same as TK_AND, in1, in2, out3 */
65377 case OP_Or: { /* same as TK_OR, in1, in2, out3 */
65378 #if 0 /* local variables moved into u.ak */
65379 int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
65380 int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
65381 #endif /* local variables moved into u.ak */
65383 pIn1 = &aMem[pOp->p1];
65384 if( pIn1->flags & MEM_Null ){
65385 u.ak.v1 = 2;
65386 }else{
65387 u.ak.v1 = sqlite3VdbeIntValue(pIn1)!=0;
65389 pIn2 = &aMem[pOp->p2];
65390 if( pIn2->flags & MEM_Null ){
65391 u.ak.v2 = 2;
65392 }else{
65393 u.ak.v2 = sqlite3VdbeIntValue(pIn2)!=0;
65395 if( pOp->opcode==OP_And ){
65396 static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
65397 u.ak.v1 = and_logic[u.ak.v1*3+u.ak.v2];
65398 }else{
65399 static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
65400 u.ak.v1 = or_logic[u.ak.v1*3+u.ak.v2];
65402 pOut = &aMem[pOp->p3];
65403 if( u.ak.v1==2 ){
65404 MemSetTypeFlag(pOut, MEM_Null);
65405 }else{
65406 pOut->u.i = u.ak.v1;
65407 MemSetTypeFlag(pOut, MEM_Int);
65409 break;
65412 /* Opcode: Not P1 P2 * * *
65414 ** Interpret the value in register P1 as a boolean value. Store the
65415 ** boolean complement in register P2. If the value in register P1 is
65416 ** NULL, then a NULL is stored in P2.
65418 case OP_Not: { /* same as TK_NOT, in1, out2 */
65419 pIn1 = &aMem[pOp->p1];
65420 pOut = &aMem[pOp->p2];
65421 if( pIn1->flags & MEM_Null ){
65422 sqlite3VdbeMemSetNull(pOut);
65423 }else{
65424 sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeIntValue(pIn1));
65426 break;
65429 /* Opcode: BitNot P1 P2 * * *
65431 ** Interpret the content of register P1 as an integer. Store the
65432 ** ones-complement of the P1 value into register P2. If P1 holds
65433 ** a NULL then store a NULL in P2.
65435 case OP_BitNot: { /* same as TK_BITNOT, in1, out2 */
65436 pIn1 = &aMem[pOp->p1];
65437 pOut = &aMem[pOp->p2];
65438 if( pIn1->flags & MEM_Null ){
65439 sqlite3VdbeMemSetNull(pOut);
65440 }else{
65441 sqlite3VdbeMemSetInt64(pOut, ~sqlite3VdbeIntValue(pIn1));
65443 break;
65446 /* Opcode: Once P1 P2 * * *
65448 ** Jump to P2 if the value in register P1 is a not null or zero. If
65449 ** the value is NULL or zero, fall through and change the P1 register
65450 ** to an integer 1.
65452 ** When P1 is not used otherwise in a program, this opcode falls through
65453 ** once and jumps on all subsequent invocations. It is the equivalent
65454 ** of "OP_If P1 P2", followed by "OP_Integer 1 P1".
65456 /* Opcode: If P1 P2 P3 * *
65458 ** Jump to P2 if the value in register P1 is true. The value
65459 ** is considered true if it is numeric and non-zero. If the value
65460 ** in P1 is NULL then take the jump if P3 is true.
65462 /* Opcode: IfNot P1 P2 P3 * *
65464 ** Jump to P2 if the value in register P1 is False. The value
65465 ** is considered true if it has a numeric value of zero. If the value
65466 ** in P1 is NULL then take the jump if P3 is true.
65468 case OP_Once: /* jump, in1 */
65469 case OP_If: /* jump, in1 */
65470 case OP_IfNot: { /* jump, in1 */
65471 #if 0 /* local variables moved into u.al */
65472 int c;
65473 #endif /* local variables moved into u.al */
65474 pIn1 = &aMem[pOp->p1];
65475 if( pIn1->flags & MEM_Null ){
65476 u.al.c = pOp->p3;
65477 }else{
65478 #ifdef SQLITE_OMIT_FLOATING_POINT
65479 u.al.c = sqlite3VdbeIntValue(pIn1)!=0;
65480 #else
65481 u.al.c = sqlite3VdbeRealValue(pIn1)!=0.0;
65482 #endif
65483 if( pOp->opcode==OP_IfNot ) u.al.c = !u.al.c;
65485 if( u.al.c ){
65486 pc = pOp->p2-1;
65487 }else if( pOp->opcode==OP_Once ){
65488 assert( (pIn1->flags & (MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame))==0 );
65489 memAboutToChange(p, pIn1);
65490 pIn1->flags = MEM_Int;
65491 pIn1->u.i = 1;
65492 REGISTER_TRACE(pOp->p1, pIn1);
65494 break;
65497 /* Opcode: IsNull P1 P2 * * *
65499 ** Jump to P2 if the value in register P1 is NULL.
65501 case OP_IsNull: { /* same as TK_ISNULL, jump, in1 */
65502 pIn1 = &aMem[pOp->p1];
65503 if( (pIn1->flags & MEM_Null)!=0 ){
65504 pc = pOp->p2 - 1;
65506 break;
65509 /* Opcode: NotNull P1 P2 * * *
65511 ** Jump to P2 if the value in register P1 is not NULL.
65513 case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */
65514 pIn1 = &aMem[pOp->p1];
65515 if( (pIn1->flags & MEM_Null)==0 ){
65516 pc = pOp->p2 - 1;
65518 break;
65521 /* Opcode: Column P1 P2 P3 P4 P5
65523 ** Interpret the data that cursor P1 points to as a structure built using
65524 ** the MakeRecord instruction. (See the MakeRecord opcode for additional
65525 ** information about the format of the data.) Extract the P2-th column
65526 ** from this record. If there are less that (P2+1)
65527 ** values in the record, extract a NULL.
65529 ** The value extracted is stored in register P3.
65531 ** If the column contains fewer than P2 fields, then extract a NULL. Or,
65532 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
65533 ** the result.
65535 ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
65536 ** then the cache of the cursor is reset prior to extracting the column.
65537 ** The first OP_Column against a pseudo-table after the value of the content
65538 ** register has changed should have this bit set.
65540 case OP_Column: {
65541 #if 0 /* local variables moved into u.am */
65542 u32 payloadSize; /* Number of bytes in the record */
65543 i64 payloadSize64; /* Number of bytes in the record */
65544 int p1; /* P1 value of the opcode */
65545 int p2; /* column number to retrieve */
65546 VdbeCursor *pC; /* The VDBE cursor */
65547 char *zRec; /* Pointer to complete record-data */
65548 BtCursor *pCrsr; /* The BTree cursor */
65549 u32 *aType; /* aType[i] holds the numeric type of the i-th column */
65550 u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
65551 int nField; /* number of fields in the record */
65552 int len; /* The length of the serialized data for the column */
65553 int i; /* Loop counter */
65554 char *zData; /* Part of the record being decoded */
65555 Mem *pDest; /* Where to write the extracted value */
65556 Mem sMem; /* For storing the record being decoded */
65557 u8 *zIdx; /* Index into header */
65558 u8 *zEndHdr; /* Pointer to first byte after the header */
65559 u32 offset; /* Offset into the data */
65560 u32 szField; /* Number of bytes in the content of a field */
65561 int szHdr; /* Size of the header size field at start of record */
65562 int avail; /* Number of bytes of available data */
65563 u32 t; /* A type code from the record header */
65564 Mem *pReg; /* PseudoTable input register */
65565 #endif /* local variables moved into u.am */
65568 u.am.p1 = pOp->p1;
65569 u.am.p2 = pOp->p2;
65570 u.am.pC = 0;
65571 memset(&u.am.sMem, 0, sizeof(u.am.sMem));
65572 assert( u.am.p1<p->nCursor );
65573 assert( pOp->p3>0 && pOp->p3<=p->nMem );
65574 u.am.pDest = &aMem[pOp->p3];
65575 memAboutToChange(p, u.am.pDest);
65576 u.am.zRec = 0;
65578 /* This block sets the variable u.am.payloadSize to be the total number of
65579 ** bytes in the record.
65581 ** u.am.zRec is set to be the complete text of the record if it is available.
65582 ** The complete record text is always available for pseudo-tables
65583 ** If the record is stored in a cursor, the complete record text
65584 ** might be available in the u.am.pC->aRow cache. Or it might not be.
65585 ** If the data is unavailable, u.am.zRec is set to NULL.
65587 ** We also compute the number of columns in the record. For cursors,
65588 ** the number of columns is stored in the VdbeCursor.nField element.
65590 u.am.pC = p->apCsr[u.am.p1];
65591 assert( u.am.pC!=0 );
65592 #ifndef SQLITE_OMIT_VIRTUALTABLE
65593 assert( u.am.pC->pVtabCursor==0 );
65594 #endif
65595 u.am.pCrsr = u.am.pC->pCursor;
65596 if( u.am.pCrsr!=0 ){
65597 /* The record is stored in a B-Tree */
65598 rc = sqlite3VdbeCursorMoveto(u.am.pC);
65599 if( rc ) goto abort_due_to_error;
65600 if( u.am.pC->nullRow ){
65601 u.am.payloadSize = 0;
65602 }else if( u.am.pC->cacheStatus==p->cacheCtr ){
65603 u.am.payloadSize = u.am.pC->payloadSize;
65604 u.am.zRec = (char*)u.am.pC->aRow;
65605 }else if( u.am.pC->isIndex ){
65606 assert( sqlite3BtreeCursorIsValid(u.am.pCrsr) );
65607 VVA_ONLY(rc =) sqlite3BtreeKeySize(u.am.pCrsr, &u.am.payloadSize64);
65608 assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */
65609 /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
65610 ** payload size, so it is impossible for u.am.payloadSize64 to be
65611 ** larger than 32 bits. */
65612 assert( (u.am.payloadSize64 & SQLITE_MAX_U32)==(u64)u.am.payloadSize64 );
65613 u.am.payloadSize = (u32)u.am.payloadSize64;
65614 }else{
65615 assert( sqlite3BtreeCursorIsValid(u.am.pCrsr) );
65616 VVA_ONLY(rc =) sqlite3BtreeDataSize(u.am.pCrsr, &u.am.payloadSize);
65617 assert( rc==SQLITE_OK ); /* DataSize() cannot fail */
65619 }else if( ALWAYS(u.am.pC->pseudoTableReg>0) ){
65620 u.am.pReg = &aMem[u.am.pC->pseudoTableReg];
65621 assert( u.am.pReg->flags & MEM_Blob );
65622 assert( memIsValid(u.am.pReg) );
65623 u.am.payloadSize = u.am.pReg->n;
65624 u.am.zRec = u.am.pReg->z;
65625 u.am.pC->cacheStatus = (pOp->p5&OPFLAG_CLEARCACHE) ? CACHE_STALE : p->cacheCtr;
65626 assert( u.am.payloadSize==0 || u.am.zRec!=0 );
65627 }else{
65628 /* Consider the row to be NULL */
65629 u.am.payloadSize = 0;
65632 /* If u.am.payloadSize is 0, then just store a NULL. This can happen because of
65633 ** nullRow or because of a corrupt database. */
65634 if( u.am.payloadSize==0 ){
65635 MemSetTypeFlag(u.am.pDest, MEM_Null);
65636 goto op_column_out;
65638 assert( db->aLimit[SQLITE_LIMIT_LENGTH]>=0 );
65639 if( u.am.payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
65640 goto too_big;
65643 u.am.nField = u.am.pC->nField;
65644 assert( u.am.p2<u.am.nField );
65646 /* Read and parse the table header. Store the results of the parse
65647 ** into the record header cache fields of the cursor.
65649 u.am.aType = u.am.pC->aType;
65650 if( u.am.pC->cacheStatus==p->cacheCtr ){
65651 u.am.aOffset = u.am.pC->aOffset;
65652 }else{
65653 assert(u.am.aType);
65654 u.am.avail = 0;
65655 u.am.pC->aOffset = u.am.aOffset = &u.am.aType[u.am.nField];
65656 u.am.pC->payloadSize = u.am.payloadSize;
65657 u.am.pC->cacheStatus = p->cacheCtr;
65659 /* Figure out how many bytes are in the header */
65660 if( u.am.zRec ){
65661 u.am.zData = u.am.zRec;
65662 }else{
65663 if( u.am.pC->isIndex ){
65664 u.am.zData = (char*)sqlite3BtreeKeyFetch(u.am.pCrsr, &u.am.avail);
65665 }else{
65666 u.am.zData = (char*)sqlite3BtreeDataFetch(u.am.pCrsr, &u.am.avail);
65668 /* If KeyFetch()/DataFetch() managed to get the entire payload,
65669 ** save the payload in the u.am.pC->aRow cache. That will save us from
65670 ** having to make additional calls to fetch the content portion of
65671 ** the record.
65673 assert( u.am.avail>=0 );
65674 if( u.am.payloadSize <= (u32)u.am.avail ){
65675 u.am.zRec = u.am.zData;
65676 u.am.pC->aRow = (u8*)u.am.zData;
65677 }else{
65678 u.am.pC->aRow = 0;
65681 /* The following assert is true in all cases accept when
65682 ** the database file has been corrupted externally.
65683 ** assert( u.am.zRec!=0 || u.am.avail>=u.am.payloadSize || u.am.avail>=9 ); */
65684 u.am.szHdr = getVarint32((u8*)u.am.zData, u.am.offset);
65686 /* Make sure a corrupt database has not given us an oversize header.
65687 ** Do this now to avoid an oversize memory allocation.
65689 ** Type entries can be between 1 and 5 bytes each. But 4 and 5 byte
65690 ** types use so much data space that there can only be 4096 and 32 of
65691 ** them, respectively. So the maximum header length results from a
65692 ** 3-byte type for each of the maximum of 32768 columns plus three
65693 ** extra bytes for the header length itself. 32768*3 + 3 = 98307.
65695 if( u.am.offset > 98307 ){
65696 rc = SQLITE_CORRUPT_BKPT;
65697 goto op_column_out;
65700 /* Compute in u.am.len the number of bytes of data we need to read in order
65701 ** to get u.am.nField type values. u.am.offset is an upper bound on this. But
65702 ** u.am.nField might be significantly less than the true number of columns
65703 ** in the table, and in that case, 5*u.am.nField+3 might be smaller than u.am.offset.
65704 ** We want to minimize u.am.len in order to limit the size of the memory
65705 ** allocation, especially if a corrupt database file has caused u.am.offset
65706 ** to be oversized. Offset is limited to 98307 above. But 98307 might
65707 ** still exceed Robson memory allocation limits on some configurations.
65708 ** On systems that cannot tolerate large memory allocations, u.am.nField*5+3
65709 ** will likely be much smaller since u.am.nField will likely be less than
65710 ** 20 or so. This insures that Robson memory allocation limits are
65711 ** not exceeded even for corrupt database files.
65713 u.am.len = u.am.nField*5 + 3;
65714 if( u.am.len > (int)u.am.offset ) u.am.len = (int)u.am.offset;
65716 /* The KeyFetch() or DataFetch() above are fast and will get the entire
65717 ** record header in most cases. But they will fail to get the complete
65718 ** record header if the record header does not fit on a single page
65719 ** in the B-Tree. When that happens, use sqlite3VdbeMemFromBtree() to
65720 ** acquire the complete header text.
65722 if( !u.am.zRec && u.am.avail<u.am.len ){
65723 u.am.sMem.flags = 0;
65724 u.am.sMem.db = 0;
65725 rc = sqlite3VdbeMemFromBtree(u.am.pCrsr, 0, u.am.len, u.am.pC->isIndex, &u.am.sMem);
65726 if( rc!=SQLITE_OK ){
65727 goto op_column_out;
65729 u.am.zData = u.am.sMem.z;
65731 u.am.zEndHdr = (u8 *)&u.am.zData[u.am.len];
65732 u.am.zIdx = (u8 *)&u.am.zData[u.am.szHdr];
65734 /* Scan the header and use it to fill in the u.am.aType[] and u.am.aOffset[]
65735 ** arrays. u.am.aType[u.am.i] will contain the type integer for the u.am.i-th
65736 ** column and u.am.aOffset[u.am.i] will contain the u.am.offset from the beginning
65737 ** of the record to the start of the data for the u.am.i-th column
65739 for(u.am.i=0; u.am.i<u.am.nField; u.am.i++){
65740 if( u.am.zIdx<u.am.zEndHdr ){
65741 u.am.aOffset[u.am.i] = u.am.offset;
65742 if( u.am.zIdx[0]<0x80 ){
65743 u.am.t = u.am.zIdx[0];
65744 u.am.zIdx++;
65745 }else{
65746 u.am.zIdx += sqlite3GetVarint32(u.am.zIdx, &u.am.t);
65748 u.am.aType[u.am.i] = u.am.t;
65749 u.am.szField = sqlite3VdbeSerialTypeLen(u.am.t);
65750 u.am.offset += u.am.szField;
65751 if( u.am.offset<u.am.szField ){ /* True if u.am.offset overflows */
65752 u.am.zIdx = &u.am.zEndHdr[1]; /* Forces SQLITE_CORRUPT return below */
65753 break;
65755 }else{
65756 /* If u.am.i is less that u.am.nField, then there are less fields in this
65757 ** record than SetNumColumns indicated there are columns in the
65758 ** table. Set the u.am.offset for any extra columns not present in
65759 ** the record to 0. This tells code below to store a NULL
65760 ** instead of deserializing a value from the record.
65762 u.am.aOffset[u.am.i] = 0;
65765 sqlite3VdbeMemRelease(&u.am.sMem);
65766 u.am.sMem.flags = MEM_Null;
65768 /* If we have read more header data than was contained in the header,
65769 ** or if the end of the last field appears to be past the end of the
65770 ** record, or if the end of the last field appears to be before the end
65771 ** of the record (when all fields present), then we must be dealing
65772 ** with a corrupt database.
65774 if( (u.am.zIdx > u.am.zEndHdr) || (u.am.offset > u.am.payloadSize)
65775 || (u.am.zIdx==u.am.zEndHdr && u.am.offset!=u.am.payloadSize) ){
65776 rc = SQLITE_CORRUPT_BKPT;
65777 goto op_column_out;
65781 /* Get the column information. If u.am.aOffset[u.am.p2] is non-zero, then
65782 ** deserialize the value from the record. If u.am.aOffset[u.am.p2] is zero,
65783 ** then there are not enough fields in the record to satisfy the
65784 ** request. In this case, set the value NULL or to P4 if P4 is
65785 ** a pointer to a Mem object.
65787 if( u.am.aOffset[u.am.p2] ){
65788 assert( rc==SQLITE_OK );
65789 if( u.am.zRec ){
65790 MemReleaseExt(u.am.pDest);
65791 sqlite3VdbeSerialGet((u8 *)&u.am.zRec[u.am.aOffset[u.am.p2]], u.am.aType[u.am.p2], u.am.pDest);
65792 }else{
65793 u.am.len = sqlite3VdbeSerialTypeLen(u.am.aType[u.am.p2]);
65794 sqlite3VdbeMemMove(&u.am.sMem, u.am.pDest);
65795 rc = sqlite3VdbeMemFromBtree(u.am.pCrsr, u.am.aOffset[u.am.p2], u.am.len, u.am.pC->isIndex, &u.am.sMem);
65796 if( rc!=SQLITE_OK ){
65797 goto op_column_out;
65799 u.am.zData = u.am.sMem.z;
65800 sqlite3VdbeSerialGet((u8*)u.am.zData, u.am.aType[u.am.p2], u.am.pDest);
65802 u.am.pDest->enc = encoding;
65803 }else{
65804 if( pOp->p4type==P4_MEM ){
65805 sqlite3VdbeMemShallowCopy(u.am.pDest, pOp->p4.pMem, MEM_Static);
65806 }else{
65807 MemSetTypeFlag(u.am.pDest, MEM_Null);
65811 /* If we dynamically allocated space to hold the data (in the
65812 ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
65813 ** dynamically allocated space over to the u.am.pDest structure.
65814 ** This prevents a memory copy.
65816 if( u.am.sMem.zMalloc ){
65817 assert( u.am.sMem.z==u.am.sMem.zMalloc );
65818 assert( !(u.am.pDest->flags & MEM_Dyn) );
65819 assert( !(u.am.pDest->flags & (MEM_Blob|MEM_Str)) || u.am.pDest->z==u.am.sMem.z );
65820 u.am.pDest->flags &= ~(MEM_Ephem|MEM_Static);
65821 u.am.pDest->flags |= MEM_Term;
65822 u.am.pDest->z = u.am.sMem.z;
65823 u.am.pDest->zMalloc = u.am.sMem.zMalloc;
65826 rc = sqlite3VdbeMemMakeWriteable(u.am.pDest);
65828 op_column_out:
65829 UPDATE_MAX_BLOBSIZE(u.am.pDest);
65830 REGISTER_TRACE(pOp->p3, u.am.pDest);
65831 break;
65834 /* Opcode: Affinity P1 P2 * P4 *
65836 ** Apply affinities to a range of P2 registers starting with P1.
65838 ** P4 is a string that is P2 characters long. The nth character of the
65839 ** string indicates the column affinity that should be used for the nth
65840 ** memory cell in the range.
65842 case OP_Affinity: {
65843 #if 0 /* local variables moved into u.an */
65844 const char *zAffinity; /* The affinity to be applied */
65845 char cAff; /* A single character of affinity */
65846 #endif /* local variables moved into u.an */
65848 u.an.zAffinity = pOp->p4.z;
65849 assert( u.an.zAffinity!=0 );
65850 assert( u.an.zAffinity[pOp->p2]==0 );
65851 pIn1 = &aMem[pOp->p1];
65852 while( (u.an.cAff = *(u.an.zAffinity++))!=0 ){
65853 assert( pIn1 <= &p->aMem[p->nMem] );
65854 assert( memIsValid(pIn1) );
65855 ExpandBlob(pIn1);
65856 applyAffinity(pIn1, u.an.cAff, encoding);
65857 pIn1++;
65859 break;
65862 /* Opcode: MakeRecord P1 P2 P3 P4 *
65864 ** Convert P2 registers beginning with P1 into the [record format]
65865 ** use as a data record in a database table or as a key
65866 ** in an index. The OP_Column opcode can decode the record later.
65868 ** P4 may be a string that is P2 characters long. The nth character of the
65869 ** string indicates the column affinity that should be used for the nth
65870 ** field of the index key.
65872 ** The mapping from character to affinity is given by the SQLITE_AFF_
65873 ** macros defined in sqliteInt.h.
65875 ** If P4 is NULL then all index fields have the affinity NONE.
65877 case OP_MakeRecord: {
65878 #if 0 /* local variables moved into u.ao */
65879 u8 *zNewRecord; /* A buffer to hold the data for the new record */
65880 Mem *pRec; /* The new record */
65881 u64 nData; /* Number of bytes of data space */
65882 int nHdr; /* Number of bytes of header space */
65883 i64 nByte; /* Data space required for this record */
65884 int nZero; /* Number of zero bytes at the end of the record */
65885 int nVarint; /* Number of bytes in a varint */
65886 u32 serial_type; /* Type field */
65887 Mem *pData0; /* First field to be combined into the record */
65888 Mem *pLast; /* Last field of the record */
65889 int nField; /* Number of fields in the record */
65890 char *zAffinity; /* The affinity string for the record */
65891 int file_format; /* File format to use for encoding */
65892 int i; /* Space used in zNewRecord[] */
65893 int len; /* Length of a field */
65894 #endif /* local variables moved into u.ao */
65896 /* Assuming the record contains N fields, the record format looks
65897 ** like this:
65899 ** ------------------------------------------------------------------------
65900 ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
65901 ** ------------------------------------------------------------------------
65903 ** Data(0) is taken from register P1. Data(1) comes from register P1+1
65904 ** and so froth.
65906 ** Each type field is a varint representing the serial type of the
65907 ** corresponding data element (see sqlite3VdbeSerialType()). The
65908 ** hdr-size field is also a varint which is the offset from the beginning
65909 ** of the record to data0.
65911 u.ao.nData = 0; /* Number of bytes of data space */
65912 u.ao.nHdr = 0; /* Number of bytes of header space */
65913 u.ao.nZero = 0; /* Number of zero bytes at the end of the record */
65914 u.ao.nField = pOp->p1;
65915 u.ao.zAffinity = pOp->p4.z;
65916 assert( u.ao.nField>0 && pOp->p2>0 && pOp->p2+u.ao.nField<=p->nMem+1 );
65917 u.ao.pData0 = &aMem[u.ao.nField];
65918 u.ao.nField = pOp->p2;
65919 u.ao.pLast = &u.ao.pData0[u.ao.nField-1];
65920 u.ao.file_format = p->minWriteFileFormat;
65922 /* Identify the output register */
65923 assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
65924 pOut = &aMem[pOp->p3];
65925 memAboutToChange(p, pOut);
65927 /* Loop through the elements that will make up the record to figure
65928 ** out how much space is required for the new record.
65930 for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){
65931 assert( memIsValid(u.ao.pRec) );
65932 if( u.ao.zAffinity ){
65933 applyAffinity(u.ao.pRec, u.ao.zAffinity[u.ao.pRec-u.ao.pData0], encoding);
65935 if( u.ao.pRec->flags&MEM_Zero && u.ao.pRec->n>0 ){
65936 sqlite3VdbeMemExpandBlob(u.ao.pRec);
65938 u.ao.serial_type = sqlite3VdbeSerialType(u.ao.pRec, u.ao.file_format);
65939 u.ao.len = sqlite3VdbeSerialTypeLen(u.ao.serial_type);
65940 u.ao.nData += u.ao.len;
65941 u.ao.nHdr += sqlite3VarintLen(u.ao.serial_type);
65942 if( u.ao.pRec->flags & MEM_Zero ){
65943 /* Only pure zero-filled BLOBs can be input to this Opcode.
65944 ** We do not allow blobs with a prefix and a zero-filled tail. */
65945 u.ao.nZero += u.ao.pRec->u.nZero;
65946 }else if( u.ao.len ){
65947 u.ao.nZero = 0;
65951 /* Add the initial header varint and total the size */
65952 u.ao.nHdr += u.ao.nVarint = sqlite3VarintLen(u.ao.nHdr);
65953 if( u.ao.nVarint<sqlite3VarintLen(u.ao.nHdr) ){
65954 u.ao.nHdr++;
65956 u.ao.nByte = u.ao.nHdr+u.ao.nData-u.ao.nZero;
65957 if( u.ao.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
65958 goto too_big;
65961 /* Make sure the output register has a buffer large enough to store
65962 ** the new record. The output register (pOp->p3) is not allowed to
65963 ** be one of the input registers (because the following call to
65964 ** sqlite3VdbeMemGrow() could clobber the value before it is used).
65966 if( sqlite3VdbeMemGrow(pOut, (int)u.ao.nByte, 0) ){
65967 goto no_mem;
65969 u.ao.zNewRecord = (u8 *)pOut->z;
65971 /* Write the record */
65972 u.ao.i = putVarint32(u.ao.zNewRecord, u.ao.nHdr);
65973 for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){
65974 u.ao.serial_type = sqlite3VdbeSerialType(u.ao.pRec, u.ao.file_format);
65975 u.ao.i += putVarint32(&u.ao.zNewRecord[u.ao.i], u.ao.serial_type); /* serial type */
65977 for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){ /* serial data */
65978 u.ao.i += sqlite3VdbeSerialPut(&u.ao.zNewRecord[u.ao.i], (int)(u.ao.nByte-u.ao.i), u.ao.pRec,u.ao.file_format);
65980 assert( u.ao.i==u.ao.nByte );
65982 assert( pOp->p3>0 && pOp->p3<=p->nMem );
65983 pOut->n = (int)u.ao.nByte;
65984 pOut->flags = MEM_Blob | MEM_Dyn;
65985 pOut->xDel = 0;
65986 if( u.ao.nZero ){
65987 pOut->u.nZero = u.ao.nZero;
65988 pOut->flags |= MEM_Zero;
65990 pOut->enc = SQLITE_UTF8; /* In case the blob is ever converted to text */
65991 REGISTER_TRACE(pOp->p3, pOut);
65992 UPDATE_MAX_BLOBSIZE(pOut);
65993 break;
65996 /* Opcode: Count P1 P2 * * *
65998 ** Store the number of entries (an integer value) in the table or index
65999 ** opened by cursor P1 in register P2
66001 #ifndef SQLITE_OMIT_BTREECOUNT
66002 case OP_Count: { /* out2-prerelease */
66003 #if 0 /* local variables moved into u.ap */
66004 i64 nEntry;
66005 BtCursor *pCrsr;
66006 #endif /* local variables moved into u.ap */
66008 u.ap.pCrsr = p->apCsr[pOp->p1]->pCursor;
66009 if( ALWAYS(u.ap.pCrsr) ){
66010 rc = sqlite3BtreeCount(u.ap.pCrsr, &u.ap.nEntry);
66011 }else{
66012 u.ap.nEntry = 0;
66014 pOut->u.i = u.ap.nEntry;
66015 break;
66017 #endif
66019 /* Opcode: Savepoint P1 * * P4 *
66021 ** Open, release or rollback the savepoint named by parameter P4, depending
66022 ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
66023 ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
66025 case OP_Savepoint: {
66026 #if 0 /* local variables moved into u.aq */
66027 int p1; /* Value of P1 operand */
66028 char *zName; /* Name of savepoint */
66029 int nName;
66030 Savepoint *pNew;
66031 Savepoint *pSavepoint;
66032 Savepoint *pTmp;
66033 int iSavepoint;
66034 int ii;
66035 #endif /* local variables moved into u.aq */
66037 u.aq.p1 = pOp->p1;
66038 u.aq.zName = pOp->p4.z;
66040 /* Assert that the u.aq.p1 parameter is valid. Also that if there is no open
66041 ** transaction, then there cannot be any savepoints.
66043 assert( db->pSavepoint==0 || db->autoCommit==0 );
66044 assert( u.aq.p1==SAVEPOINT_BEGIN||u.aq.p1==SAVEPOINT_RELEASE||u.aq.p1==SAVEPOINT_ROLLBACK );
66045 assert( db->pSavepoint || db->isTransactionSavepoint==0 );
66046 assert( checkSavepointCount(db) );
66048 if( u.aq.p1==SAVEPOINT_BEGIN ){
66049 if( db->writeVdbeCnt>0 ){
66050 /* A new savepoint cannot be created if there are active write
66051 ** statements (i.e. open read/write incremental blob handles).
66053 sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
66054 "SQL statements in progress");
66055 rc = SQLITE_BUSY;
66056 }else{
66057 u.aq.nName = sqlite3Strlen30(u.aq.zName);
66059 #ifndef SQLITE_OMIT_VIRTUALTABLE
66060 /* This call is Ok even if this savepoint is actually a transaction
66061 ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
66062 ** If this is a transaction savepoint being opened, it is guaranteed
66063 ** that the db->aVTrans[] array is empty. */
66064 assert( db->autoCommit==0 || db->nVTrans==0 );
66065 rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
66066 db->nStatement+db->nSavepoint);
66067 if( rc!=SQLITE_OK ) goto abort_due_to_error;
66068 #endif
66070 /* Create a new savepoint structure. */
66071 u.aq.pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+u.aq.nName+1);
66072 if( u.aq.pNew ){
66073 u.aq.pNew->zName = (char *)&u.aq.pNew[1];
66074 memcpy(u.aq.pNew->zName, u.aq.zName, u.aq.nName+1);
66076 /* If there is no open transaction, then mark this as a special
66077 ** "transaction savepoint". */
66078 if( db->autoCommit ){
66079 db->autoCommit = 0;
66080 db->isTransactionSavepoint = 1;
66081 }else{
66082 db->nSavepoint++;
66085 /* Link the new savepoint into the database handle's list. */
66086 u.aq.pNew->pNext = db->pSavepoint;
66087 db->pSavepoint = u.aq.pNew;
66088 u.aq.pNew->nDeferredCons = db->nDeferredCons;
66091 }else{
66092 u.aq.iSavepoint = 0;
66094 /* Find the named savepoint. If there is no such savepoint, then an
66095 ** an error is returned to the user. */
66096 for(
66097 u.aq.pSavepoint = db->pSavepoint;
66098 u.aq.pSavepoint && sqlite3StrICmp(u.aq.pSavepoint->zName, u.aq.zName);
66099 u.aq.pSavepoint = u.aq.pSavepoint->pNext
66101 u.aq.iSavepoint++;
66103 if( !u.aq.pSavepoint ){
66104 sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", u.aq.zName);
66105 rc = SQLITE_ERROR;
66106 }else if(
66107 db->writeVdbeCnt>0 || (u.aq.p1==SAVEPOINT_ROLLBACK && db->activeVdbeCnt>1)
66109 /* It is not possible to release (commit) a savepoint if there are
66110 ** active write statements. It is not possible to rollback a savepoint
66111 ** if there are any active statements at all.
66113 sqlite3SetString(&p->zErrMsg, db,
66114 "cannot %s savepoint - SQL statements in progress",
66115 (u.aq.p1==SAVEPOINT_ROLLBACK ? "rollback": "release")
66117 rc = SQLITE_BUSY;
66118 }else{
66120 /* Determine whether or not this is a transaction savepoint. If so,
66121 ** and this is a RELEASE command, then the current transaction
66122 ** is committed.
66124 int isTransaction = u.aq.pSavepoint->pNext==0 && db->isTransactionSavepoint;
66125 if( isTransaction && u.aq.p1==SAVEPOINT_RELEASE ){
66126 if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
66127 goto vdbe_return;
66129 db->autoCommit = 1;
66130 if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
66131 p->pc = pc;
66132 db->autoCommit = 0;
66133 p->rc = rc = SQLITE_BUSY;
66134 goto vdbe_return;
66136 db->isTransactionSavepoint = 0;
66137 rc = p->rc;
66138 }else{
66139 u.aq.iSavepoint = db->nSavepoint - u.aq.iSavepoint - 1;
66140 for(u.aq.ii=0; u.aq.ii<db->nDb; u.aq.ii++){
66141 rc = sqlite3BtreeSavepoint(db->aDb[u.aq.ii].pBt, u.aq.p1, u.aq.iSavepoint);
66142 if( rc!=SQLITE_OK ){
66143 goto abort_due_to_error;
66146 if( u.aq.p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){
66147 sqlite3ExpirePreparedStatements(db);
66148 sqlite3ResetInternalSchema(db, -1);
66149 db->flags = (db->flags | SQLITE_InternChanges);
66153 /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
66154 ** savepoints nested inside of the savepoint being operated on. */
66155 while( db->pSavepoint!=u.aq.pSavepoint ){
66156 u.aq.pTmp = db->pSavepoint;
66157 db->pSavepoint = u.aq.pTmp->pNext;
66158 sqlite3DbFree(db, u.aq.pTmp);
66159 db->nSavepoint--;
66162 /* If it is a RELEASE, then destroy the savepoint being operated on
66163 ** too. If it is a ROLLBACK TO, then set the number of deferred
66164 ** constraint violations present in the database to the value stored
66165 ** when the savepoint was created. */
66166 if( u.aq.p1==SAVEPOINT_RELEASE ){
66167 assert( u.aq.pSavepoint==db->pSavepoint );
66168 db->pSavepoint = u.aq.pSavepoint->pNext;
66169 sqlite3DbFree(db, u.aq.pSavepoint);
66170 if( !isTransaction ){
66171 db->nSavepoint--;
66173 }else{
66174 db->nDeferredCons = u.aq.pSavepoint->nDeferredCons;
66177 if( !isTransaction ){
66178 rc = sqlite3VtabSavepoint(db, u.aq.p1, u.aq.iSavepoint);
66179 if( rc!=SQLITE_OK ) goto abort_due_to_error;
66184 break;
66187 /* Opcode: AutoCommit P1 P2 * * *
66189 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
66190 ** back any currently active btree transactions. If there are any active
66191 ** VMs (apart from this one), then a ROLLBACK fails. A COMMIT fails if
66192 ** there are active writing VMs or active VMs that use shared cache.
66194 ** This instruction causes the VM to halt.
66196 case OP_AutoCommit: {
66197 #if 0 /* local variables moved into u.ar */
66198 int desiredAutoCommit;
66199 int iRollback;
66200 int turnOnAC;
66201 #endif /* local variables moved into u.ar */
66203 u.ar.desiredAutoCommit = pOp->p1;
66204 u.ar.iRollback = pOp->p2;
66205 u.ar.turnOnAC = u.ar.desiredAutoCommit && !db->autoCommit;
66206 assert( u.ar.desiredAutoCommit==1 || u.ar.desiredAutoCommit==0 );
66207 assert( u.ar.desiredAutoCommit==1 || u.ar.iRollback==0 );
66208 assert( db->activeVdbeCnt>0 ); /* At least this one VM is active */
66210 if( u.ar.turnOnAC && u.ar.iRollback && db->activeVdbeCnt>1 ){
66211 /* If this instruction implements a ROLLBACK and other VMs are
66212 ** still running, and a transaction is active, return an error indicating
66213 ** that the other VMs must complete first.
66215 sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
66216 "SQL statements in progress");
66217 rc = SQLITE_BUSY;
66218 }else if( u.ar.turnOnAC && !u.ar.iRollback && db->writeVdbeCnt>0 ){
66219 /* If this instruction implements a COMMIT and other VMs are writing
66220 ** return an error indicating that the other VMs must complete first.
66222 sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
66223 "SQL statements in progress");
66224 rc = SQLITE_BUSY;
66225 }else if( u.ar.desiredAutoCommit!=db->autoCommit ){
66226 if( u.ar.iRollback ){
66227 assert( u.ar.desiredAutoCommit==1 );
66228 sqlite3RollbackAll(db);
66229 db->autoCommit = 1;
66230 }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
66231 goto vdbe_return;
66232 }else{
66233 db->autoCommit = (u8)u.ar.desiredAutoCommit;
66234 if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
66235 p->pc = pc;
66236 db->autoCommit = (u8)(1-u.ar.desiredAutoCommit);
66237 p->rc = rc = SQLITE_BUSY;
66238 goto vdbe_return;
66241 assert( db->nStatement==0 );
66242 sqlite3CloseSavepoints(db);
66243 if( p->rc==SQLITE_OK ){
66244 rc = SQLITE_DONE;
66245 }else{
66246 rc = SQLITE_ERROR;
66248 goto vdbe_return;
66249 }else{
66250 sqlite3SetString(&p->zErrMsg, db,
66251 (!u.ar.desiredAutoCommit)?"cannot start a transaction within a transaction":(
66252 (u.ar.iRollback)?"cannot rollback - no transaction is active":
66253 "cannot commit - no transaction is active"));
66255 rc = SQLITE_ERROR;
66257 break;
66260 /* Opcode: Transaction P1 P2 * * *
66262 ** Begin a transaction. The transaction ends when a Commit or Rollback
66263 ** opcode is encountered. Depending on the ON CONFLICT setting, the
66264 ** transaction might also be rolled back if an error is encountered.
66266 ** P1 is the index of the database file on which the transaction is
66267 ** started. Index 0 is the main database file and index 1 is the
66268 ** file used for temporary tables. Indices of 2 or more are used for
66269 ** attached databases.
66271 ** If P2 is non-zero, then a write-transaction is started. A RESERVED lock is
66272 ** obtained on the database file when a write-transaction is started. No
66273 ** other process can start another write transaction while this transaction is
66274 ** underway. Starting a write transaction also creates a rollback journal. A
66275 ** write transaction must be started before any changes can be made to the
66276 ** database. If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
66277 ** on the file.
66279 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
66280 ** true (this flag is set if the Vdbe may modify more than one row and may
66281 ** throw an ABORT exception), a statement transaction may also be opened.
66282 ** More specifically, a statement transaction is opened iff the database
66283 ** connection is currently not in autocommit mode, or if there are other
66284 ** active statements. A statement transaction allows the affects of this
66285 ** VDBE to be rolled back after an error without having to roll back the
66286 ** entire transaction. If no error is encountered, the statement transaction
66287 ** will automatically commit when the VDBE halts.
66289 ** If P2 is zero, then a read-lock is obtained on the database file.
66291 case OP_Transaction: {
66292 #if 0 /* local variables moved into u.as */
66293 Btree *pBt;
66294 #endif /* local variables moved into u.as */
66296 assert( pOp->p1>=0 && pOp->p1<db->nDb );
66297 assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
66298 u.as.pBt = db->aDb[pOp->p1].pBt;
66300 if( u.as.pBt ){
66301 rc = sqlite3BtreeBeginTrans(u.as.pBt, pOp->p2);
66302 if( rc==SQLITE_BUSY ){
66303 p->pc = pc;
66304 p->rc = rc = SQLITE_BUSY;
66305 goto vdbe_return;
66307 if( rc!=SQLITE_OK ){
66308 goto abort_due_to_error;
66311 if( pOp->p2 && p->usesStmtJournal
66312 && (db->autoCommit==0 || db->activeVdbeCnt>1)
66314 assert( sqlite3BtreeIsInTrans(u.as.pBt) );
66315 if( p->iStatement==0 ){
66316 assert( db->nStatement>=0 && db->nSavepoint>=0 );
66317 db->nStatement++;
66318 p->iStatement = db->nSavepoint + db->nStatement;
66321 rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
66322 if( rc==SQLITE_OK ){
66323 rc = sqlite3BtreeBeginStmt(u.as.pBt, p->iStatement);
66326 /* Store the current value of the database handles deferred constraint
66327 ** counter. If the statement transaction needs to be rolled back,
66328 ** the value of this counter needs to be restored too. */
66329 p->nStmtDefCons = db->nDeferredCons;
66332 break;
66335 /* Opcode: ReadCookie P1 P2 P3 * *
66337 ** Read cookie number P3 from database P1 and write it into register P2.
66338 ** P3==1 is the schema version. P3==2 is the database format.
66339 ** P3==3 is the recommended pager cache size, and so forth. P1==0 is
66340 ** the main database file and P1==1 is the database file used to store
66341 ** temporary tables.
66343 ** There must be a read-lock on the database (either a transaction
66344 ** must be started or there must be an open cursor) before
66345 ** executing this instruction.
66347 case OP_ReadCookie: { /* out2-prerelease */
66348 #if 0 /* local variables moved into u.at */
66349 int iMeta;
66350 int iDb;
66351 int iCookie;
66352 #endif /* local variables moved into u.at */
66354 u.at.iDb = pOp->p1;
66355 u.at.iCookie = pOp->p3;
66356 assert( pOp->p3<SQLITE_N_BTREE_META );
66357 assert( u.at.iDb>=0 && u.at.iDb<db->nDb );
66358 assert( db->aDb[u.at.iDb].pBt!=0 );
66359 assert( (p->btreeMask & (((yDbMask)1)<<u.at.iDb))!=0 );
66361 sqlite3BtreeGetMeta(db->aDb[u.at.iDb].pBt, u.at.iCookie, (u32 *)&u.at.iMeta);
66362 pOut->u.i = u.at.iMeta;
66363 break;
66366 /* Opcode: SetCookie P1 P2 P3 * *
66368 ** Write the content of register P3 (interpreted as an integer)
66369 ** into cookie number P2 of database P1. P2==1 is the schema version.
66370 ** P2==2 is the database format. P2==3 is the recommended pager cache
66371 ** size, and so forth. P1==0 is the main database file and P1==1 is the
66372 ** database file used to store temporary tables.
66374 ** A transaction must be started before executing this opcode.
66376 case OP_SetCookie: { /* in3 */
66377 #if 0 /* local variables moved into u.au */
66378 Db *pDb;
66379 #endif /* local variables moved into u.au */
66380 assert( pOp->p2<SQLITE_N_BTREE_META );
66381 assert( pOp->p1>=0 && pOp->p1<db->nDb );
66382 assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
66383 u.au.pDb = &db->aDb[pOp->p1];
66384 assert( u.au.pDb->pBt!=0 );
66385 assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
66386 pIn3 = &aMem[pOp->p3];
66387 sqlite3VdbeMemIntegerify(pIn3);
66388 /* See note about index shifting on OP_ReadCookie */
66389 rc = sqlite3BtreeUpdateMeta(u.au.pDb->pBt, pOp->p2, (int)pIn3->u.i);
66390 if( pOp->p2==BTREE_SCHEMA_VERSION ){
66391 /* When the schema cookie changes, record the new cookie internally */
66392 u.au.pDb->pSchema->schema_cookie = (int)pIn3->u.i;
66393 db->flags |= SQLITE_InternChanges;
66394 }else if( pOp->p2==BTREE_FILE_FORMAT ){
66395 /* Record changes in the file format */
66396 u.au.pDb->pSchema->file_format = (u8)pIn3->u.i;
66398 if( pOp->p1==1 ){
66399 /* Invalidate all prepared statements whenever the TEMP database
66400 ** schema is changed. Ticket #1644 */
66401 sqlite3ExpirePreparedStatements(db);
66402 p->expired = 0;
66404 break;
66407 /* Opcode: VerifyCookie P1 P2 P3 * *
66409 ** Check the value of global database parameter number 0 (the
66410 ** schema version) and make sure it is equal to P2 and that the
66411 ** generation counter on the local schema parse equals P3.
66413 ** P1 is the database number which is 0 for the main database file
66414 ** and 1 for the file holding temporary tables and some higher number
66415 ** for auxiliary databases.
66417 ** The cookie changes its value whenever the database schema changes.
66418 ** This operation is used to detect when that the cookie has changed
66419 ** and that the current process needs to reread the schema.
66421 ** Either a transaction needs to have been started or an OP_Open needs
66422 ** to be executed (to establish a read lock) before this opcode is
66423 ** invoked.
66425 case OP_VerifyCookie: {
66426 #if 0 /* local variables moved into u.av */
66427 int iMeta;
66428 int iGen;
66429 Btree *pBt;
66430 #endif /* local variables moved into u.av */
66432 assert( pOp->p1>=0 && pOp->p1<db->nDb );
66433 assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
66434 assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
66435 u.av.pBt = db->aDb[pOp->p1].pBt;
66436 if( u.av.pBt ){
66437 sqlite3BtreeGetMeta(u.av.pBt, BTREE_SCHEMA_VERSION, (u32 *)&u.av.iMeta);
66438 u.av.iGen = db->aDb[pOp->p1].pSchema->iGeneration;
66439 }else{
66440 u.av.iGen = u.av.iMeta = 0;
66442 if( u.av.iMeta!=pOp->p2 || u.av.iGen!=pOp->p3 ){
66443 sqlite3DbFree(db, p->zErrMsg);
66444 p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
66445 /* If the schema-cookie from the database file matches the cookie
66446 ** stored with the in-memory representation of the schema, do
66447 ** not reload the schema from the database file.
66449 ** If virtual-tables are in use, this is not just an optimization.
66450 ** Often, v-tables store their data in other SQLite tables, which
66451 ** are queried from within xNext() and other v-table methods using
66452 ** prepared queries. If such a query is out-of-date, we do not want to
66453 ** discard the database schema, as the user code implementing the
66454 ** v-table would have to be ready for the sqlite3_vtab structure itself
66455 ** to be invalidated whenever sqlite3_step() is called from within
66456 ** a v-table method.
66458 if( db->aDb[pOp->p1].pSchema->schema_cookie!=u.av.iMeta ){
66459 sqlite3ResetInternalSchema(db, pOp->p1);
66462 p->expired = 1;
66463 rc = SQLITE_SCHEMA;
66465 break;
66468 /* Opcode: OpenRead P1 P2 P3 P4 P5
66470 ** Open a read-only cursor for the database table whose root page is
66471 ** P2 in a database file. The database file is determined by P3.
66472 ** P3==0 means the main database, P3==1 means the database used for
66473 ** temporary tables, and P3>1 means used the corresponding attached
66474 ** database. Give the new cursor an identifier of P1. The P1
66475 ** values need not be contiguous but all P1 values should be small integers.
66476 ** It is an error for P1 to be negative.
66478 ** If P5!=0 then use the content of register P2 as the root page, not
66479 ** the value of P2 itself.
66481 ** There will be a read lock on the database whenever there is an
66482 ** open cursor. If the database was unlocked prior to this instruction
66483 ** then a read lock is acquired as part of this instruction. A read
66484 ** lock allows other processes to read the database but prohibits
66485 ** any other process from modifying the database. The read lock is
66486 ** released when all cursors are closed. If this instruction attempts
66487 ** to get a read lock but fails, the script terminates with an
66488 ** SQLITE_BUSY error code.
66490 ** The P4 value may be either an integer (P4_INT32) or a pointer to
66491 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
66492 ** structure, then said structure defines the content and collating
66493 ** sequence of the index being opened. Otherwise, if P4 is an integer
66494 ** value, it is set to the number of columns in the table.
66496 ** See also OpenWrite.
66498 /* Opcode: OpenWrite P1 P2 P3 P4 P5
66500 ** Open a read/write cursor named P1 on the table or index whose root
66501 ** page is P2. Or if P5!=0 use the content of register P2 to find the
66502 ** root page.
66504 ** The P4 value may be either an integer (P4_INT32) or a pointer to
66505 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
66506 ** structure, then said structure defines the content and collating
66507 ** sequence of the index being opened. Otherwise, if P4 is an integer
66508 ** value, it is set to the number of columns in the table, or to the
66509 ** largest index of any column of the table that is actually used.
66511 ** This instruction works just like OpenRead except that it opens the cursor
66512 ** in read/write mode. For a given table, there can be one or more read-only
66513 ** cursors or a single read/write cursor but not both.
66515 ** See also OpenRead.
66517 case OP_OpenRead:
66518 case OP_OpenWrite: {
66519 #if 0 /* local variables moved into u.aw */
66520 int nField;
66521 KeyInfo *pKeyInfo;
66522 int p2;
66523 int iDb;
66524 int wrFlag;
66525 Btree *pX;
66526 VdbeCursor *pCur;
66527 Db *pDb;
66528 #endif /* local variables moved into u.aw */
66530 if( p->expired ){
66531 rc = SQLITE_ABORT;
66532 break;
66535 u.aw.nField = 0;
66536 u.aw.pKeyInfo = 0;
66537 u.aw.p2 = pOp->p2;
66538 u.aw.iDb = pOp->p3;
66539 assert( u.aw.iDb>=0 && u.aw.iDb<db->nDb );
66540 assert( (p->btreeMask & (((yDbMask)1)<<u.aw.iDb))!=0 );
66541 u.aw.pDb = &db->aDb[u.aw.iDb];
66542 u.aw.pX = u.aw.pDb->pBt;
66543 assert( u.aw.pX!=0 );
66544 if( pOp->opcode==OP_OpenWrite ){
66545 u.aw.wrFlag = 1;
66546 assert( sqlite3SchemaMutexHeld(db, u.aw.iDb, 0) );
66547 if( u.aw.pDb->pSchema->file_format < p->minWriteFileFormat ){
66548 p->minWriteFileFormat = u.aw.pDb->pSchema->file_format;
66550 }else{
66551 u.aw.wrFlag = 0;
66553 if( pOp->p5 ){
66554 assert( u.aw.p2>0 );
66555 assert( u.aw.p2<=p->nMem );
66556 pIn2 = &aMem[u.aw.p2];
66557 assert( memIsValid(pIn2) );
66558 assert( (pIn2->flags & MEM_Int)!=0 );
66559 sqlite3VdbeMemIntegerify(pIn2);
66560 u.aw.p2 = (int)pIn2->u.i;
66561 /* The u.aw.p2 value always comes from a prior OP_CreateTable opcode and
66562 ** that opcode will always set the u.aw.p2 value to 2 or more or else fail.
66563 ** If there were a failure, the prepared statement would have halted
66564 ** before reaching this instruction. */
66565 if( NEVER(u.aw.p2<2) ) {
66566 rc = SQLITE_CORRUPT_BKPT;
66567 goto abort_due_to_error;
66570 if( pOp->p4type==P4_KEYINFO ){
66571 u.aw.pKeyInfo = pOp->p4.pKeyInfo;
66572 u.aw.pKeyInfo->enc = ENC(p->db);
66573 u.aw.nField = u.aw.pKeyInfo->nField+1;
66574 }else if( pOp->p4type==P4_INT32 ){
66575 u.aw.nField = pOp->p4.i;
66577 assert( pOp->p1>=0 );
66578 u.aw.pCur = allocateCursor(p, pOp->p1, u.aw.nField, u.aw.iDb, 1);
66579 if( u.aw.pCur==0 ) goto no_mem;
66580 u.aw.pCur->nullRow = 1;
66581 u.aw.pCur->isOrdered = 1;
66582 rc = sqlite3BtreeCursor(u.aw.pX, u.aw.p2, u.aw.wrFlag, u.aw.pKeyInfo, u.aw.pCur->pCursor);
66583 u.aw.pCur->pKeyInfo = u.aw.pKeyInfo;
66585 /* Since it performs no memory allocation or IO, the only value that
66586 ** sqlite3BtreeCursor() may return is SQLITE_OK. */
66587 assert( rc==SQLITE_OK );
66589 /* Set the VdbeCursor.isTable and isIndex variables. Previous versions of
66590 ** SQLite used to check if the root-page flags were sane at this point
66591 ** and report database corruption if they were not, but this check has
66592 ** since moved into the btree layer. */
66593 u.aw.pCur->isTable = pOp->p4type!=P4_KEYINFO;
66594 u.aw.pCur->isIndex = !u.aw.pCur->isTable;
66595 break;
66598 /* Opcode: OpenEphemeral P1 P2 * P4 P5
66600 ** Open a new cursor P1 to a transient table.
66601 ** The cursor is always opened read/write even if
66602 ** the main database is read-only. The ephemeral
66603 ** table is deleted automatically when the cursor is closed.
66605 ** P2 is the number of columns in the ephemeral table.
66606 ** The cursor points to a BTree table if P4==0 and to a BTree index
66607 ** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure
66608 ** that defines the format of keys in the index.
66610 ** This opcode was once called OpenTemp. But that created
66611 ** confusion because the term "temp table", might refer either
66612 ** to a TEMP table at the SQL level, or to a table opened by
66613 ** this opcode. Then this opcode was call OpenVirtual. But
66614 ** that created confusion with the whole virtual-table idea.
66616 ** The P5 parameter can be a mask of the BTREE_* flags defined
66617 ** in btree.h. These flags control aspects of the operation of
66618 ** the btree. The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
66619 ** added automatically.
66621 /* Opcode: OpenAutoindex P1 P2 * P4 *
66623 ** This opcode works the same as OP_OpenEphemeral. It has a
66624 ** different name to distinguish its use. Tables created using
66625 ** by this opcode will be used for automatically created transient
66626 ** indices in joins.
66628 case OP_OpenAutoindex:
66629 case OP_OpenEphemeral: {
66630 #if 0 /* local variables moved into u.ax */
66631 VdbeCursor *pCx;
66632 #endif /* local variables moved into u.ax */
66633 static const int vfsFlags =
66634 SQLITE_OPEN_READWRITE |
66635 SQLITE_OPEN_CREATE |
66636 SQLITE_OPEN_EXCLUSIVE |
66637 SQLITE_OPEN_DELETEONCLOSE |
66638 SQLITE_OPEN_TRANSIENT_DB;
66640 assert( pOp->p1>=0 );
66641 u.ax.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
66642 if( u.ax.pCx==0 ) goto no_mem;
66643 u.ax.pCx->nullRow = 1;
66644 rc = sqlite3BtreeOpen(db->pVfs, 0, db, &u.ax.pCx->pBt,
66645 BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
66646 if( rc==SQLITE_OK ){
66647 rc = sqlite3BtreeBeginTrans(u.ax.pCx->pBt, 1);
66649 if( rc==SQLITE_OK ){
66650 /* If a transient index is required, create it by calling
66651 ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
66652 ** opening it. If a transient table is required, just use the
66653 ** automatically created table with root-page 1 (an BLOB_INTKEY table).
66655 if( pOp->p4.pKeyInfo ){
66656 int pgno;
66657 assert( pOp->p4type==P4_KEYINFO );
66658 rc = sqlite3BtreeCreateTable(u.ax.pCx->pBt, &pgno, BTREE_BLOBKEY | pOp->p5);
66659 if( rc==SQLITE_OK ){
66660 assert( pgno==MASTER_ROOT+1 );
66661 rc = sqlite3BtreeCursor(u.ax.pCx->pBt, pgno, 1,
66662 (KeyInfo*)pOp->p4.z, u.ax.pCx->pCursor);
66663 u.ax.pCx->pKeyInfo = pOp->p4.pKeyInfo;
66664 u.ax.pCx->pKeyInfo->enc = ENC(p->db);
66666 u.ax.pCx->isTable = 0;
66667 }else{
66668 rc = sqlite3BtreeCursor(u.ax.pCx->pBt, MASTER_ROOT, 1, 0, u.ax.pCx->pCursor);
66669 u.ax.pCx->isTable = 1;
66672 u.ax.pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
66673 u.ax.pCx->isIndex = !u.ax.pCx->isTable;
66674 break;
66677 /* Opcode: OpenSorter P1 P2 * P4 *
66679 ** This opcode works like OP_OpenEphemeral except that it opens
66680 ** a transient index that is specifically designed to sort large
66681 ** tables using an external merge-sort algorithm.
66683 case OP_SorterOpen: {
66684 #if 0 /* local variables moved into u.ay */
66685 VdbeCursor *pCx;
66686 #endif /* local variables moved into u.ay */
66687 #ifndef SQLITE_OMIT_MERGE_SORT
66688 u.ay.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
66689 if( u.ay.pCx==0 ) goto no_mem;
66690 u.ay.pCx->pKeyInfo = pOp->p4.pKeyInfo;
66691 u.ay.pCx->pKeyInfo->enc = ENC(p->db);
66692 u.ay.pCx->isSorter = 1;
66693 rc = sqlite3VdbeSorterInit(db, u.ay.pCx);
66694 #else
66695 pOp->opcode = OP_OpenEphemeral;
66696 pc--;
66697 #endif
66698 break;
66701 /* Opcode: OpenPseudo P1 P2 P3 * *
66703 ** Open a new cursor that points to a fake table that contains a single
66704 ** row of data. The content of that one row in the content of memory
66705 ** register P2. In other words, cursor P1 becomes an alias for the
66706 ** MEM_Blob content contained in register P2.
66708 ** A pseudo-table created by this opcode is used to hold a single
66709 ** row output from the sorter so that the row can be decomposed into
66710 ** individual columns using the OP_Column opcode. The OP_Column opcode
66711 ** is the only cursor opcode that works with a pseudo-table.
66713 ** P3 is the number of fields in the records that will be stored by
66714 ** the pseudo-table.
66716 case OP_OpenPseudo: {
66717 #if 0 /* local variables moved into u.az */
66718 VdbeCursor *pCx;
66719 #endif /* local variables moved into u.az */
66721 assert( pOp->p1>=0 );
66722 u.az.pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
66723 if( u.az.pCx==0 ) goto no_mem;
66724 u.az.pCx->nullRow = 1;
66725 u.az.pCx->pseudoTableReg = pOp->p2;
66726 u.az.pCx->isTable = 1;
66727 u.az.pCx->isIndex = 0;
66728 break;
66731 /* Opcode: Close P1 * * * *
66733 ** Close a cursor previously opened as P1. If P1 is not
66734 ** currently open, this instruction is a no-op.
66736 case OP_Close: {
66737 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66738 sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
66739 p->apCsr[pOp->p1] = 0;
66740 break;
66743 /* Opcode: SeekGe P1 P2 P3 P4 *
66745 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
66746 ** use the value in register P3 as the key. If cursor P1 refers
66747 ** to an SQL index, then P3 is the first in an array of P4 registers
66748 ** that are used as an unpacked index key.
66750 ** Reposition cursor P1 so that it points to the smallest entry that
66751 ** is greater than or equal to the key value. If there are no records
66752 ** greater than or equal to the key and P2 is not zero, then jump to P2.
66754 ** See also: Found, NotFound, Distinct, SeekLt, SeekGt, SeekLe
66756 /* Opcode: SeekGt P1 P2 P3 P4 *
66758 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
66759 ** use the value in register P3 as a key. If cursor P1 refers
66760 ** to an SQL index, then P3 is the first in an array of P4 registers
66761 ** that are used as an unpacked index key.
66763 ** Reposition cursor P1 so that it points to the smallest entry that
66764 ** is greater than the key value. If there are no records greater than
66765 ** the key and P2 is not zero, then jump to P2.
66767 ** See also: Found, NotFound, Distinct, SeekLt, SeekGe, SeekLe
66769 /* Opcode: SeekLt P1 P2 P3 P4 *
66771 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
66772 ** use the value in register P3 as a key. If cursor P1 refers
66773 ** to an SQL index, then P3 is the first in an array of P4 registers
66774 ** that are used as an unpacked index key.
66776 ** Reposition cursor P1 so that it points to the largest entry that
66777 ** is less than the key value. If there are no records less than
66778 ** the key and P2 is not zero, then jump to P2.
66780 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLe
66782 /* Opcode: SeekLe P1 P2 P3 P4 *
66784 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
66785 ** use the value in register P3 as a key. If cursor P1 refers
66786 ** to an SQL index, then P3 is the first in an array of P4 registers
66787 ** that are used as an unpacked index key.
66789 ** Reposition cursor P1 so that it points to the largest entry that
66790 ** is less than or equal to the key value. If there are no records
66791 ** less than or equal to the key and P2 is not zero, then jump to P2.
66793 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLt
66795 case OP_SeekLt: /* jump, in3 */
66796 case OP_SeekLe: /* jump, in3 */
66797 case OP_SeekGe: /* jump, in3 */
66798 case OP_SeekGt: { /* jump, in3 */
66799 #if 0 /* local variables moved into u.ba */
66800 int res;
66801 int oc;
66802 VdbeCursor *pC;
66803 UnpackedRecord r;
66804 int nField;
66805 i64 iKey; /* The rowid we are to seek to */
66806 #endif /* local variables moved into u.ba */
66808 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66809 assert( pOp->p2!=0 );
66810 u.ba.pC = p->apCsr[pOp->p1];
66811 assert( u.ba.pC!=0 );
66812 assert( u.ba.pC->pseudoTableReg==0 );
66813 assert( OP_SeekLe == OP_SeekLt+1 );
66814 assert( OP_SeekGe == OP_SeekLt+2 );
66815 assert( OP_SeekGt == OP_SeekLt+3 );
66816 assert( u.ba.pC->isOrdered );
66817 if( ALWAYS(u.ba.pC->pCursor!=0) ){
66818 u.ba.oc = pOp->opcode;
66819 u.ba.pC->nullRow = 0;
66820 if( u.ba.pC->isTable ){
66821 /* The input value in P3 might be of any type: integer, real, string,
66822 ** blob, or NULL. But it needs to be an integer before we can do
66823 ** the seek, so covert it. */
66824 pIn3 = &aMem[pOp->p3];
66825 applyNumericAffinity(pIn3);
66826 u.ba.iKey = sqlite3VdbeIntValue(pIn3);
66827 u.ba.pC->rowidIsValid = 0;
66829 /* If the P3 value could not be converted into an integer without
66830 ** loss of information, then special processing is required... */
66831 if( (pIn3->flags & MEM_Int)==0 ){
66832 if( (pIn3->flags & MEM_Real)==0 ){
66833 /* If the P3 value cannot be converted into any kind of a number,
66834 ** then the seek is not possible, so jump to P2 */
66835 pc = pOp->p2 - 1;
66836 break;
66838 /* If we reach this point, then the P3 value must be a floating
66839 ** point number. */
66840 assert( (pIn3->flags & MEM_Real)!=0 );
66842 if( u.ba.iKey==SMALLEST_INT64 && (pIn3->r<(double)u.ba.iKey || pIn3->r>0) ){
66843 /* The P3 value is too large in magnitude to be expressed as an
66844 ** integer. */
66845 u.ba.res = 1;
66846 if( pIn3->r<0 ){
66847 if( u.ba.oc>=OP_SeekGe ){ assert( u.ba.oc==OP_SeekGe || u.ba.oc==OP_SeekGt );
66848 rc = sqlite3BtreeFirst(u.ba.pC->pCursor, &u.ba.res);
66849 if( rc!=SQLITE_OK ) goto abort_due_to_error;
66851 }else{
66852 if( u.ba.oc<=OP_SeekLe ){ assert( u.ba.oc==OP_SeekLt || u.ba.oc==OP_SeekLe );
66853 rc = sqlite3BtreeLast(u.ba.pC->pCursor, &u.ba.res);
66854 if( rc!=SQLITE_OK ) goto abort_due_to_error;
66857 if( u.ba.res ){
66858 pc = pOp->p2 - 1;
66860 break;
66861 }else if( u.ba.oc==OP_SeekLt || u.ba.oc==OP_SeekGe ){
66862 /* Use the ceiling() function to convert real->int */
66863 if( pIn3->r > (double)u.ba.iKey ) u.ba.iKey++;
66864 }else{
66865 /* Use the floor() function to convert real->int */
66866 assert( u.ba.oc==OP_SeekLe || u.ba.oc==OP_SeekGt );
66867 if( pIn3->r < (double)u.ba.iKey ) u.ba.iKey--;
66870 rc = sqlite3BtreeMovetoUnpacked(u.ba.pC->pCursor, 0, (u64)u.ba.iKey, 0, &u.ba.res);
66871 if( rc!=SQLITE_OK ){
66872 goto abort_due_to_error;
66874 if( u.ba.res==0 ){
66875 u.ba.pC->rowidIsValid = 1;
66876 u.ba.pC->lastRowid = u.ba.iKey;
66878 }else{
66879 u.ba.nField = pOp->p4.i;
66880 assert( pOp->p4type==P4_INT32 );
66881 assert( u.ba.nField>0 );
66882 u.ba.r.pKeyInfo = u.ba.pC->pKeyInfo;
66883 u.ba.r.nField = (u16)u.ba.nField;
66885 /* The next line of code computes as follows, only faster:
66886 ** if( u.ba.oc==OP_SeekGt || u.ba.oc==OP_SeekLe ){
66887 ** u.ba.r.flags = UNPACKED_INCRKEY;
66888 ** }else{
66889 ** u.ba.r.flags = 0;
66890 ** }
66892 u.ba.r.flags = (u16)(UNPACKED_INCRKEY * (1 & (u.ba.oc - OP_SeekLt)));
66893 assert( u.ba.oc!=OP_SeekGt || u.ba.r.flags==UNPACKED_INCRKEY );
66894 assert( u.ba.oc!=OP_SeekLe || u.ba.r.flags==UNPACKED_INCRKEY );
66895 assert( u.ba.oc!=OP_SeekGe || u.ba.r.flags==0 );
66896 assert( u.ba.oc!=OP_SeekLt || u.ba.r.flags==0 );
66898 u.ba.r.aMem = &aMem[pOp->p3];
66899 #ifdef SQLITE_DEBUG
66900 { int i; for(i=0; i<u.ba.r.nField; i++) assert( memIsValid(&u.ba.r.aMem[i]) ); }
66901 #endif
66902 ExpandBlob(u.ba.r.aMem);
66903 rc = sqlite3BtreeMovetoUnpacked(u.ba.pC->pCursor, &u.ba.r, 0, 0, &u.ba.res);
66904 if( rc!=SQLITE_OK ){
66905 goto abort_due_to_error;
66907 u.ba.pC->rowidIsValid = 0;
66909 u.ba.pC->deferredMoveto = 0;
66910 u.ba.pC->cacheStatus = CACHE_STALE;
66911 #ifdef SQLITE_TEST
66912 sqlite3_search_count++;
66913 #endif
66914 if( u.ba.oc>=OP_SeekGe ){ assert( u.ba.oc==OP_SeekGe || u.ba.oc==OP_SeekGt );
66915 if( u.ba.res<0 || (u.ba.res==0 && u.ba.oc==OP_SeekGt) ){
66916 rc = sqlite3BtreeNext(u.ba.pC->pCursor, &u.ba.res);
66917 if( rc!=SQLITE_OK ) goto abort_due_to_error;
66918 u.ba.pC->rowidIsValid = 0;
66919 }else{
66920 u.ba.res = 0;
66922 }else{
66923 assert( u.ba.oc==OP_SeekLt || u.ba.oc==OP_SeekLe );
66924 if( u.ba.res>0 || (u.ba.res==0 && u.ba.oc==OP_SeekLt) ){
66925 rc = sqlite3BtreePrevious(u.ba.pC->pCursor, &u.ba.res);
66926 if( rc!=SQLITE_OK ) goto abort_due_to_error;
66927 u.ba.pC->rowidIsValid = 0;
66928 }else{
66929 /* u.ba.res might be negative because the table is empty. Check to
66930 ** see if this is the case.
66932 u.ba.res = sqlite3BtreeEof(u.ba.pC->pCursor);
66935 assert( pOp->p2>0 );
66936 if( u.ba.res ){
66937 pc = pOp->p2 - 1;
66939 }else{
66940 /* This happens when attempting to open the sqlite3_master table
66941 ** for read access returns SQLITE_EMPTY. In this case always
66942 ** take the jump (since there are no records in the table).
66944 pc = pOp->p2 - 1;
66946 break;
66949 /* Opcode: Seek P1 P2 * * *
66951 ** P1 is an open table cursor and P2 is a rowid integer. Arrange
66952 ** for P1 to move so that it points to the rowid given by P2.
66954 ** This is actually a deferred seek. Nothing actually happens until
66955 ** the cursor is used to read a record. That way, if no reads
66956 ** occur, no unnecessary I/O happens.
66958 case OP_Seek: { /* in2 */
66959 #if 0 /* local variables moved into u.bb */
66960 VdbeCursor *pC;
66961 #endif /* local variables moved into u.bb */
66963 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66964 u.bb.pC = p->apCsr[pOp->p1];
66965 assert( u.bb.pC!=0 );
66966 if( ALWAYS(u.bb.pC->pCursor!=0) ){
66967 assert( u.bb.pC->isTable );
66968 u.bb.pC->nullRow = 0;
66969 pIn2 = &aMem[pOp->p2];
66970 u.bb.pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
66971 u.bb.pC->rowidIsValid = 0;
66972 u.bb.pC->deferredMoveto = 1;
66974 break;
66978 /* Opcode: Found P1 P2 P3 P4 *
66980 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
66981 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
66982 ** record.
66984 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
66985 ** is a prefix of any entry in P1 then a jump is made to P2 and
66986 ** P1 is left pointing at the matching entry.
66988 /* Opcode: NotFound P1 P2 P3 P4 *
66990 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
66991 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
66992 ** record.
66994 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
66995 ** is not the prefix of any entry in P1 then a jump is made to P2. If P1
66996 ** does contain an entry whose prefix matches the P3/P4 record then control
66997 ** falls through to the next instruction and P1 is left pointing at the
66998 ** matching entry.
67000 ** See also: Found, NotExists, IsUnique
67002 case OP_NotFound: /* jump, in3 */
67003 case OP_Found: { /* jump, in3 */
67004 #if 0 /* local variables moved into u.bc */
67005 int alreadyExists;
67006 VdbeCursor *pC;
67007 int res;
67008 char *pFree;
67009 UnpackedRecord *pIdxKey;
67010 UnpackedRecord r;
67011 char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
67012 #endif /* local variables moved into u.bc */
67014 #ifdef SQLITE_TEST
67015 sqlite3_found_count++;
67016 #endif
67018 u.bc.alreadyExists = 0;
67019 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67020 assert( pOp->p4type==P4_INT32 );
67021 u.bc.pC = p->apCsr[pOp->p1];
67022 assert( u.bc.pC!=0 );
67023 pIn3 = &aMem[pOp->p3];
67024 if( ALWAYS(u.bc.pC->pCursor!=0) ){
67026 assert( u.bc.pC->isTable==0 );
67027 if( pOp->p4.i>0 ){
67028 u.bc.r.pKeyInfo = u.bc.pC->pKeyInfo;
67029 u.bc.r.nField = (u16)pOp->p4.i;
67030 u.bc.r.aMem = pIn3;
67031 #ifdef SQLITE_DEBUG
67032 { int i; for(i=0; i<u.bc.r.nField; i++) assert( memIsValid(&u.bc.r.aMem[i]) ); }
67033 #endif
67034 u.bc.r.flags = UNPACKED_PREFIX_MATCH;
67035 u.bc.pIdxKey = &u.bc.r;
67036 }else{
67037 u.bc.pIdxKey = sqlite3VdbeAllocUnpackedRecord(
67038 u.bc.pC->pKeyInfo, u.bc.aTempRec, sizeof(u.bc.aTempRec), &u.bc.pFree
67040 if( u.bc.pIdxKey==0 ) goto no_mem;
67041 assert( pIn3->flags & MEM_Blob );
67042 assert( (pIn3->flags & MEM_Zero)==0 ); /* zeroblobs already expanded */
67043 sqlite3VdbeRecordUnpack(u.bc.pC->pKeyInfo, pIn3->n, pIn3->z, u.bc.pIdxKey);
67044 u.bc.pIdxKey->flags |= UNPACKED_PREFIX_MATCH;
67046 rc = sqlite3BtreeMovetoUnpacked(u.bc.pC->pCursor, u.bc.pIdxKey, 0, 0, &u.bc.res);
67047 if( pOp->p4.i==0 ){
67048 sqlite3DbFree(db, u.bc.pFree);
67050 if( rc!=SQLITE_OK ){
67051 break;
67053 u.bc.alreadyExists = (u.bc.res==0);
67054 u.bc.pC->deferredMoveto = 0;
67055 u.bc.pC->cacheStatus = CACHE_STALE;
67057 if( pOp->opcode==OP_Found ){
67058 if( u.bc.alreadyExists ) pc = pOp->p2 - 1;
67059 }else{
67060 if( !u.bc.alreadyExists ) pc = pOp->p2 - 1;
67062 break;
67065 /* Opcode: IsUnique P1 P2 P3 P4 *
67067 ** Cursor P1 is open on an index b-tree - that is to say, a btree which
67068 ** no data and where the key are records generated by OP_MakeRecord with
67069 ** the list field being the integer ROWID of the entry that the index
67070 ** entry refers to.
67072 ** The P3 register contains an integer record number. Call this record
67073 ** number R. Register P4 is the first in a set of N contiguous registers
67074 ** that make up an unpacked index key that can be used with cursor P1.
67075 ** The value of N can be inferred from the cursor. N includes the rowid
67076 ** value appended to the end of the index record. This rowid value may
67077 ** or may not be the same as R.
67079 ** If any of the N registers beginning with register P4 contains a NULL
67080 ** value, jump immediately to P2.
67082 ** Otherwise, this instruction checks if cursor P1 contains an entry
67083 ** where the first (N-1) fields match but the rowid value at the end
67084 ** of the index entry is not R. If there is no such entry, control jumps
67085 ** to instruction P2. Otherwise, the rowid of the conflicting index
67086 ** entry is copied to register P3 and control falls through to the next
67087 ** instruction.
67089 ** See also: NotFound, NotExists, Found
67091 case OP_IsUnique: { /* jump, in3 */
67092 #if 0 /* local variables moved into u.bd */
67093 u16 ii;
67094 VdbeCursor *pCx;
67095 BtCursor *pCrsr;
67096 u16 nField;
67097 Mem *aMx;
67098 UnpackedRecord r; /* B-Tree index search key */
67099 i64 R; /* Rowid stored in register P3 */
67100 #endif /* local variables moved into u.bd */
67102 pIn3 = &aMem[pOp->p3];
67103 u.bd.aMx = &aMem[pOp->p4.i];
67104 /* Assert that the values of parameters P1 and P4 are in range. */
67105 assert( pOp->p4type==P4_INT32 );
67106 assert( pOp->p4.i>0 && pOp->p4.i<=p->nMem );
67107 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67109 /* Find the index cursor. */
67110 u.bd.pCx = p->apCsr[pOp->p1];
67111 assert( u.bd.pCx->deferredMoveto==0 );
67112 u.bd.pCx->seekResult = 0;
67113 u.bd.pCx->cacheStatus = CACHE_STALE;
67114 u.bd.pCrsr = u.bd.pCx->pCursor;
67116 /* If any of the values are NULL, take the jump. */
67117 u.bd.nField = u.bd.pCx->pKeyInfo->nField;
67118 for(u.bd.ii=0; u.bd.ii<u.bd.nField; u.bd.ii++){
67119 if( u.bd.aMx[u.bd.ii].flags & MEM_Null ){
67120 pc = pOp->p2 - 1;
67121 u.bd.pCrsr = 0;
67122 break;
67125 assert( (u.bd.aMx[u.bd.nField].flags & MEM_Null)==0 );
67127 if( u.bd.pCrsr!=0 ){
67128 /* Populate the index search key. */
67129 u.bd.r.pKeyInfo = u.bd.pCx->pKeyInfo;
67130 u.bd.r.nField = u.bd.nField + 1;
67131 u.bd.r.flags = UNPACKED_PREFIX_SEARCH;
67132 u.bd.r.aMem = u.bd.aMx;
67133 #ifdef SQLITE_DEBUG
67134 { int i; for(i=0; i<u.bd.r.nField; i++) assert( memIsValid(&u.bd.r.aMem[i]) ); }
67135 #endif
67137 /* Extract the value of u.bd.R from register P3. */
67138 sqlite3VdbeMemIntegerify(pIn3);
67139 u.bd.R = pIn3->u.i;
67141 /* Search the B-Tree index. If no conflicting record is found, jump
67142 ** to P2. Otherwise, copy the rowid of the conflicting record to
67143 ** register P3 and fall through to the next instruction. */
67144 rc = sqlite3BtreeMovetoUnpacked(u.bd.pCrsr, &u.bd.r, 0, 0, &u.bd.pCx->seekResult);
67145 if( (u.bd.r.flags & UNPACKED_PREFIX_SEARCH) || u.bd.r.rowid==u.bd.R ){
67146 pc = pOp->p2 - 1;
67147 }else{
67148 pIn3->u.i = u.bd.r.rowid;
67151 break;
67154 /* Opcode: NotExists P1 P2 P3 * *
67156 ** Use the content of register P3 as an integer key. If a record
67157 ** with that key does not exist in table of P1, then jump to P2.
67158 ** If the record does exist, then fall through. The cursor is left
67159 ** pointing to the record if it exists.
67161 ** The difference between this operation and NotFound is that this
67162 ** operation assumes the key is an integer and that P1 is a table whereas
67163 ** NotFound assumes key is a blob constructed from MakeRecord and
67164 ** P1 is an index.
67166 ** See also: Found, NotFound, IsUnique
67168 case OP_NotExists: { /* jump, in3 */
67169 #if 0 /* local variables moved into u.be */
67170 VdbeCursor *pC;
67171 BtCursor *pCrsr;
67172 int res;
67173 u64 iKey;
67174 #endif /* local variables moved into u.be */
67176 pIn3 = &aMem[pOp->p3];
67177 assert( pIn3->flags & MEM_Int );
67178 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67179 u.be.pC = p->apCsr[pOp->p1];
67180 assert( u.be.pC!=0 );
67181 assert( u.be.pC->isTable );
67182 assert( u.be.pC->pseudoTableReg==0 );
67183 u.be.pCrsr = u.be.pC->pCursor;
67184 if( ALWAYS(u.be.pCrsr!=0) ){
67185 u.be.res = 0;
67186 u.be.iKey = pIn3->u.i;
67187 rc = sqlite3BtreeMovetoUnpacked(u.be.pCrsr, 0, u.be.iKey, 0, &u.be.res);
67188 u.be.pC->lastRowid = pIn3->u.i;
67189 u.be.pC->rowidIsValid = u.be.res==0 ?1:0;
67190 u.be.pC->nullRow = 0;
67191 u.be.pC->cacheStatus = CACHE_STALE;
67192 u.be.pC->deferredMoveto = 0;
67193 if( u.be.res!=0 ){
67194 pc = pOp->p2 - 1;
67195 assert( u.be.pC->rowidIsValid==0 );
67197 u.be.pC->seekResult = u.be.res;
67198 }else{
67199 /* This happens when an attempt to open a read cursor on the
67200 ** sqlite_master table returns SQLITE_EMPTY.
67202 pc = pOp->p2 - 1;
67203 assert( u.be.pC->rowidIsValid==0 );
67204 u.be.pC->seekResult = 0;
67206 break;
67209 /* Opcode: Sequence P1 P2 * * *
67211 ** Find the next available sequence number for cursor P1.
67212 ** Write the sequence number into register P2.
67213 ** The sequence number on the cursor is incremented after this
67214 ** instruction.
67216 case OP_Sequence: { /* out2-prerelease */
67217 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67218 assert( p->apCsr[pOp->p1]!=0 );
67219 pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
67220 break;
67224 /* Opcode: NewRowid P1 P2 P3 * *
67226 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
67227 ** The record number is not previously used as a key in the database
67228 ** table that cursor P1 points to. The new record number is written
67229 ** written to register P2.
67231 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
67232 ** the largest previously generated record number. No new record numbers are
67233 ** allowed to be less than this value. When this value reaches its maximum,
67234 ** an SQLITE_FULL error is generated. The P3 register is updated with the '
67235 ** generated record number. This P3 mechanism is used to help implement the
67236 ** AUTOINCREMENT feature.
67238 case OP_NewRowid: { /* out2-prerelease */
67239 #if 0 /* local variables moved into u.bf */
67240 i64 v; /* The new rowid */
67241 VdbeCursor *pC; /* Cursor of table to get the new rowid */
67242 int res; /* Result of an sqlite3BtreeLast() */
67243 int cnt; /* Counter to limit the number of searches */
67244 Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */
67245 VdbeFrame *pFrame; /* Root frame of VDBE */
67246 #endif /* local variables moved into u.bf */
67248 u.bf.v = 0;
67249 u.bf.res = 0;
67250 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67251 u.bf.pC = p->apCsr[pOp->p1];
67252 assert( u.bf.pC!=0 );
67253 if( NEVER(u.bf.pC->pCursor==0) ){
67254 /* The zero initialization above is all that is needed */
67255 }else{
67256 /* The next rowid or record number (different terms for the same
67257 ** thing) is obtained in a two-step algorithm.
67259 ** First we attempt to find the largest existing rowid and add one
67260 ** to that. But if the largest existing rowid is already the maximum
67261 ** positive integer, we have to fall through to the second
67262 ** probabilistic algorithm
67264 ** The second algorithm is to select a rowid at random and see if
67265 ** it already exists in the table. If it does not exist, we have
67266 ** succeeded. If the random rowid does exist, we select a new one
67267 ** and try again, up to 100 times.
67269 assert( u.bf.pC->isTable );
67271 #ifdef SQLITE_32BIT_ROWID
67272 # define MAX_ROWID 0x7fffffff
67273 #else
67274 /* Some compilers complain about constants of the form 0x7fffffffffffffff.
67275 ** Others complain about 0x7ffffffffffffffffLL. The following macro seems
67276 ** to provide the constant while making all compilers happy.
67278 # define MAX_ROWID (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
67279 #endif
67281 if( !u.bf.pC->useRandomRowid ){
67282 u.bf.v = sqlite3BtreeGetCachedRowid(u.bf.pC->pCursor);
67283 if( u.bf.v==0 ){
67284 rc = sqlite3BtreeLast(u.bf.pC->pCursor, &u.bf.res);
67285 if( rc!=SQLITE_OK ){
67286 goto abort_due_to_error;
67288 if( u.bf.res ){
67289 u.bf.v = 1; /* IMP: R-61914-48074 */
67290 }else{
67291 assert( sqlite3BtreeCursorIsValid(u.bf.pC->pCursor) );
67292 rc = sqlite3BtreeKeySize(u.bf.pC->pCursor, &u.bf.v);
67293 assert( rc==SQLITE_OK ); /* Cannot fail following BtreeLast() */
67294 if( u.bf.v==MAX_ROWID ){
67295 u.bf.pC->useRandomRowid = 1;
67296 }else{
67297 u.bf.v++; /* IMP: R-29538-34987 */
67302 #ifndef SQLITE_OMIT_AUTOINCREMENT
67303 if( pOp->p3 ){
67304 /* Assert that P3 is a valid memory cell. */
67305 assert( pOp->p3>0 );
67306 if( p->pFrame ){
67307 for(u.bf.pFrame=p->pFrame; u.bf.pFrame->pParent; u.bf.pFrame=u.bf.pFrame->pParent);
67308 /* Assert that P3 is a valid memory cell. */
67309 assert( pOp->p3<=u.bf.pFrame->nMem );
67310 u.bf.pMem = &u.bf.pFrame->aMem[pOp->p3];
67311 }else{
67312 /* Assert that P3 is a valid memory cell. */
67313 assert( pOp->p3<=p->nMem );
67314 u.bf.pMem = &aMem[pOp->p3];
67315 memAboutToChange(p, u.bf.pMem);
67317 assert( memIsValid(u.bf.pMem) );
67319 REGISTER_TRACE(pOp->p3, u.bf.pMem);
67320 sqlite3VdbeMemIntegerify(u.bf.pMem);
67321 assert( (u.bf.pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */
67322 if( u.bf.pMem->u.i==MAX_ROWID || u.bf.pC->useRandomRowid ){
67323 rc = SQLITE_FULL; /* IMP: R-12275-61338 */
67324 goto abort_due_to_error;
67326 if( u.bf.v<u.bf.pMem->u.i+1 ){
67327 u.bf.v = u.bf.pMem->u.i + 1;
67329 u.bf.pMem->u.i = u.bf.v;
67331 #endif
67333 sqlite3BtreeSetCachedRowid(u.bf.pC->pCursor, u.bf.v<MAX_ROWID ? u.bf.v+1 : 0);
67335 if( u.bf.pC->useRandomRowid ){
67336 /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
67337 ** largest possible integer (9223372036854775807) then the database
67338 ** engine starts picking positive candidate ROWIDs at random until
67339 ** it finds one that is not previously used. */
67340 assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is
67341 ** an AUTOINCREMENT table. */
67342 /* on the first attempt, simply do one more than previous */
67343 u.bf.v = lastRowid;
67344 u.bf.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
67345 u.bf.v++; /* ensure non-zero */
67346 u.bf.cnt = 0;
67347 while( ((rc = sqlite3BtreeMovetoUnpacked(u.bf.pC->pCursor, 0, (u64)u.bf.v,
67348 0, &u.bf.res))==SQLITE_OK)
67349 && (u.bf.res==0)
67350 && (++u.bf.cnt<100)){
67351 /* collision - try another random rowid */
67352 sqlite3_randomness(sizeof(u.bf.v), &u.bf.v);
67353 if( u.bf.cnt<5 ){
67354 /* try "small" random rowids for the initial attempts */
67355 u.bf.v &= 0xffffff;
67356 }else{
67357 u.bf.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
67359 u.bf.v++; /* ensure non-zero */
67361 if( rc==SQLITE_OK && u.bf.res==0 ){
67362 rc = SQLITE_FULL; /* IMP: R-38219-53002 */
67363 goto abort_due_to_error;
67365 assert( u.bf.v>0 ); /* EV: R-40812-03570 */
67367 u.bf.pC->rowidIsValid = 0;
67368 u.bf.pC->deferredMoveto = 0;
67369 u.bf.pC->cacheStatus = CACHE_STALE;
67371 pOut->u.i = u.bf.v;
67372 break;
67375 /* Opcode: Insert P1 P2 P3 P4 P5
67377 ** Write an entry into the table of cursor P1. A new entry is
67378 ** created if it doesn't already exist or the data for an existing
67379 ** entry is overwritten. The data is the value MEM_Blob stored in register
67380 ** number P2. The key is stored in register P3. The key must
67381 ** be a MEM_Int.
67383 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
67384 ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set,
67385 ** then rowid is stored for subsequent return by the
67386 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
67388 ** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
67389 ** the last seek operation (OP_NotExists) was a success, then this
67390 ** operation will not attempt to find the appropriate row before doing
67391 ** the insert but will instead overwrite the row that the cursor is
67392 ** currently pointing to. Presumably, the prior OP_NotExists opcode
67393 ** has already positioned the cursor correctly. This is an optimization
67394 ** that boosts performance by avoiding redundant seeks.
67396 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
67397 ** UPDATE operation. Otherwise (if the flag is clear) then this opcode
67398 ** is part of an INSERT operation. The difference is only important to
67399 ** the update hook.
67401 ** Parameter P4 may point to a string containing the table-name, or
67402 ** may be NULL. If it is not NULL, then the update-hook
67403 ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
67405 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
67406 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
67407 ** and register P2 becomes ephemeral. If the cursor is changed, the
67408 ** value of register P2 will then change. Make sure this does not
67409 ** cause any problems.)
67411 ** This instruction only works on tables. The equivalent instruction
67412 ** for indices is OP_IdxInsert.
67414 /* Opcode: InsertInt P1 P2 P3 P4 P5
67416 ** This works exactly like OP_Insert except that the key is the
67417 ** integer value P3, not the value of the integer stored in register P3.
67419 case OP_Insert:
67420 case OP_InsertInt: {
67421 #if 0 /* local variables moved into u.bg */
67422 Mem *pData; /* MEM cell holding data for the record to be inserted */
67423 Mem *pKey; /* MEM cell holding key for the record */
67424 i64 iKey; /* The integer ROWID or key for the record to be inserted */
67425 VdbeCursor *pC; /* Cursor to table into which insert is written */
67426 int nZero; /* Number of zero-bytes to append */
67427 int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
67428 const char *zDb; /* database name - used by the update hook */
67429 const char *zTbl; /* Table name - used by the opdate hook */
67430 int op; /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
67431 #endif /* local variables moved into u.bg */
67433 u.bg.pData = &aMem[pOp->p2];
67434 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67435 assert( memIsValid(u.bg.pData) );
67436 u.bg.pC = p->apCsr[pOp->p1];
67437 assert( u.bg.pC!=0 );
67438 assert( u.bg.pC->pCursor!=0 );
67439 assert( u.bg.pC->pseudoTableReg==0 );
67440 assert( u.bg.pC->isTable );
67441 REGISTER_TRACE(pOp->p2, u.bg.pData);
67443 if( pOp->opcode==OP_Insert ){
67444 u.bg.pKey = &aMem[pOp->p3];
67445 assert( u.bg.pKey->flags & MEM_Int );
67446 assert( memIsValid(u.bg.pKey) );
67447 REGISTER_TRACE(pOp->p3, u.bg.pKey);
67448 u.bg.iKey = u.bg.pKey->u.i;
67449 }else{
67450 assert( pOp->opcode==OP_InsertInt );
67451 u.bg.iKey = pOp->p3;
67454 if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
67455 if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = u.bg.iKey;
67456 if( u.bg.pData->flags & MEM_Null ){
67457 u.bg.pData->z = 0;
67458 u.bg.pData->n = 0;
67459 }else{
67460 assert( u.bg.pData->flags & (MEM_Blob|MEM_Str) );
67462 u.bg.seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bg.pC->seekResult : 0);
67463 if( u.bg.pData->flags & MEM_Zero ){
67464 u.bg.nZero = u.bg.pData->u.nZero;
67465 }else{
67466 u.bg.nZero = 0;
67468 sqlite3BtreeSetCachedRowid(u.bg.pC->pCursor, 0);
67469 rc = sqlite3BtreeInsert(u.bg.pC->pCursor, 0, u.bg.iKey,
67470 u.bg.pData->z, u.bg.pData->n, u.bg.nZero,
67471 pOp->p5 & OPFLAG_APPEND, u.bg.seekResult
67473 u.bg.pC->rowidIsValid = 0;
67474 u.bg.pC->deferredMoveto = 0;
67475 u.bg.pC->cacheStatus = CACHE_STALE;
67477 /* Invoke the update-hook if required. */
67478 if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
67479 u.bg.zDb = db->aDb[u.bg.pC->iDb].zName;
67480 u.bg.zTbl = pOp->p4.z;
67481 u.bg.op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
67482 assert( u.bg.pC->isTable );
67483 db->xUpdateCallback(db->pUpdateArg, u.bg.op, u.bg.zDb, u.bg.zTbl, u.bg.iKey);
67484 assert( u.bg.pC->iDb>=0 );
67486 break;
67489 /* Opcode: Delete P1 P2 * P4 *
67491 ** Delete the record at which the P1 cursor is currently pointing.
67493 ** The cursor will be left pointing at either the next or the previous
67494 ** record in the table. If it is left pointing at the next record, then
67495 ** the next Next instruction will be a no-op. Hence it is OK to delete
67496 ** a record from within an Next loop.
67498 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
67499 ** incremented (otherwise not).
67501 ** P1 must not be pseudo-table. It has to be a real table with
67502 ** multiple rows.
67504 ** If P4 is not NULL, then it is the name of the table that P1 is
67505 ** pointing to. The update hook will be invoked, if it exists.
67506 ** If P4 is not NULL then the P1 cursor must have been positioned
67507 ** using OP_NotFound prior to invoking this opcode.
67509 case OP_Delete: {
67510 #if 0 /* local variables moved into u.bh */
67511 i64 iKey;
67512 VdbeCursor *pC;
67513 #endif /* local variables moved into u.bh */
67515 u.bh.iKey = 0;
67516 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67517 u.bh.pC = p->apCsr[pOp->p1];
67518 assert( u.bh.pC!=0 );
67519 assert( u.bh.pC->pCursor!=0 ); /* Only valid for real tables, no pseudotables */
67521 /* If the update-hook will be invoked, set u.bh.iKey to the rowid of the
67522 ** row being deleted.
67524 if( db->xUpdateCallback && pOp->p4.z ){
67525 assert( u.bh.pC->isTable );
67526 assert( u.bh.pC->rowidIsValid ); /* lastRowid set by previous OP_NotFound */
67527 u.bh.iKey = u.bh.pC->lastRowid;
67530 /* The OP_Delete opcode always follows an OP_NotExists or OP_Last or
67531 ** OP_Column on the same table without any intervening operations that
67532 ** might move or invalidate the cursor. Hence cursor u.bh.pC is always pointing
67533 ** to the row to be deleted and the sqlite3VdbeCursorMoveto() operation
67534 ** below is always a no-op and cannot fail. We will run it anyhow, though,
67535 ** to guard against future changes to the code generator.
67537 assert( u.bh.pC->deferredMoveto==0 );
67538 rc = sqlite3VdbeCursorMoveto(u.bh.pC);
67539 if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
67541 sqlite3BtreeSetCachedRowid(u.bh.pC->pCursor, 0);
67542 rc = sqlite3BtreeDelete(u.bh.pC->pCursor);
67543 u.bh.pC->cacheStatus = CACHE_STALE;
67545 /* Invoke the update-hook if required. */
67546 if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
67547 const char *zDb = db->aDb[u.bh.pC->iDb].zName;
67548 const char *zTbl = pOp->p4.z;
67549 db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, u.bh.iKey);
67550 assert( u.bh.pC->iDb>=0 );
67552 if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
67553 break;
67555 /* Opcode: ResetCount * * * * *
67557 ** The value of the change counter is copied to the database handle
67558 ** change counter (returned by subsequent calls to sqlite3_changes()).
67559 ** Then the VMs internal change counter resets to 0.
67560 ** This is used by trigger programs.
67562 case OP_ResetCount: {
67563 sqlite3VdbeSetChanges(db, p->nChange);
67564 p->nChange = 0;
67565 break;
67568 /* Opcode: SorterCompare P1 P2 P3
67570 ** P1 is a sorter cursor. This instruction compares the record blob in
67571 ** register P3 with the entry that the sorter cursor currently points to.
67572 ** If, excluding the rowid fields at the end, the two records are a match,
67573 ** fall through to the next instruction. Otherwise, jump to instruction P2.
67575 case OP_SorterCompare: {
67576 #if 0 /* local variables moved into u.bi */
67577 VdbeCursor *pC;
67578 int res;
67579 #endif /* local variables moved into u.bi */
67581 u.bi.pC = p->apCsr[pOp->p1];
67582 assert( isSorter(u.bi.pC) );
67583 pIn3 = &aMem[pOp->p3];
67584 rc = sqlite3VdbeSorterCompare(u.bi.pC, pIn3, &u.bi.res);
67585 if( u.bi.res ){
67586 pc = pOp->p2-1;
67588 break;
67591 /* Opcode: SorterData P1 P2 * * *
67593 ** Write into register P2 the current sorter data for sorter cursor P1.
67595 case OP_SorterData: {
67596 #if 0 /* local variables moved into u.bj */
67597 VdbeCursor *pC;
67598 #endif /* local variables moved into u.bj */
67599 #ifndef SQLITE_OMIT_MERGE_SORT
67600 pOut = &aMem[pOp->p2];
67601 u.bj.pC = p->apCsr[pOp->p1];
67602 assert( u.bj.pC->isSorter );
67603 rc = sqlite3VdbeSorterRowkey(u.bj.pC, pOut);
67604 #else
67605 pOp->opcode = OP_RowKey;
67606 pc--;
67607 #endif
67608 break;
67611 /* Opcode: RowData P1 P2 * * *
67613 ** Write into register P2 the complete row data for cursor P1.
67614 ** There is no interpretation of the data.
67615 ** It is just copied onto the P2 register exactly as
67616 ** it is found in the database file.
67618 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
67619 ** of a real table, not a pseudo-table.
67621 /* Opcode: RowKey P1 P2 * * *
67623 ** Write into register P2 the complete row key for cursor P1.
67624 ** There is no interpretation of the data.
67625 ** The key is copied onto the P3 register exactly as
67626 ** it is found in the database file.
67628 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
67629 ** of a real table, not a pseudo-table.
67631 case OP_RowKey:
67632 case OP_RowData: {
67633 #if 0 /* local variables moved into u.bk */
67634 VdbeCursor *pC;
67635 BtCursor *pCrsr;
67636 u32 n;
67637 i64 n64;
67638 #endif /* local variables moved into u.bk */
67640 pOut = &aMem[pOp->p2];
67641 memAboutToChange(p, pOut);
67643 /* Note that RowKey and RowData are really exactly the same instruction */
67644 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67645 u.bk.pC = p->apCsr[pOp->p1];
67646 assert( u.bk.pC->isSorter==0 );
67647 assert( u.bk.pC->isTable || pOp->opcode!=OP_RowData );
67648 assert( u.bk.pC->isIndex || pOp->opcode==OP_RowData );
67649 assert( u.bk.pC!=0 );
67650 assert( u.bk.pC->nullRow==0 );
67651 assert( u.bk.pC->pseudoTableReg==0 );
67652 assert( !u.bk.pC->isSorter );
67653 assert( u.bk.pC->pCursor!=0 );
67654 u.bk.pCrsr = u.bk.pC->pCursor;
67655 assert( sqlite3BtreeCursorIsValid(u.bk.pCrsr) );
67657 /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
67658 ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
67659 ** the cursor. Hence the following sqlite3VdbeCursorMoveto() call is always
67660 ** a no-op and can never fail. But we leave it in place as a safety.
67662 assert( u.bk.pC->deferredMoveto==0 );
67663 rc = sqlite3VdbeCursorMoveto(u.bk.pC);
67664 if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
67666 if( u.bk.pC->isIndex ){
67667 assert( !u.bk.pC->isTable );
67668 VVA_ONLY(rc =) sqlite3BtreeKeySize(u.bk.pCrsr, &u.bk.n64);
67669 assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */
67670 if( u.bk.n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
67671 goto too_big;
67673 u.bk.n = (u32)u.bk.n64;
67674 }else{
67675 VVA_ONLY(rc =) sqlite3BtreeDataSize(u.bk.pCrsr, &u.bk.n);
67676 assert( rc==SQLITE_OK ); /* DataSize() cannot fail */
67677 if( u.bk.n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
67678 goto too_big;
67681 if( sqlite3VdbeMemGrow(pOut, u.bk.n, 0) ){
67682 goto no_mem;
67684 pOut->n = u.bk.n;
67685 MemSetTypeFlag(pOut, MEM_Blob);
67686 if( u.bk.pC->isIndex ){
67687 rc = sqlite3BtreeKey(u.bk.pCrsr, 0, u.bk.n, pOut->z);
67688 }else{
67689 rc = sqlite3BtreeData(u.bk.pCrsr, 0, u.bk.n, pOut->z);
67691 pOut->enc = SQLITE_UTF8; /* In case the blob is ever cast to text */
67692 UPDATE_MAX_BLOBSIZE(pOut);
67693 break;
67696 /* Opcode: Rowid P1 P2 * * *
67698 ** Store in register P2 an integer which is the key of the table entry that
67699 ** P1 is currently point to.
67701 ** P1 can be either an ordinary table or a virtual table. There used to
67702 ** be a separate OP_VRowid opcode for use with virtual tables, but this
67703 ** one opcode now works for both table types.
67705 case OP_Rowid: { /* out2-prerelease */
67706 #if 0 /* local variables moved into u.bl */
67707 VdbeCursor *pC;
67708 i64 v;
67709 sqlite3_vtab *pVtab;
67710 const sqlite3_module *pModule;
67711 #endif /* local variables moved into u.bl */
67713 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67714 u.bl.pC = p->apCsr[pOp->p1];
67715 assert( u.bl.pC!=0 );
67716 assert( u.bl.pC->pseudoTableReg==0 );
67717 if( u.bl.pC->nullRow ){
67718 pOut->flags = MEM_Null;
67719 break;
67720 }else if( u.bl.pC->deferredMoveto ){
67721 u.bl.v = u.bl.pC->movetoTarget;
67722 #ifndef SQLITE_OMIT_VIRTUALTABLE
67723 }else if( u.bl.pC->pVtabCursor ){
67724 u.bl.pVtab = u.bl.pC->pVtabCursor->pVtab;
67725 u.bl.pModule = u.bl.pVtab->pModule;
67726 assert( u.bl.pModule->xRowid );
67727 rc = u.bl.pModule->xRowid(u.bl.pC->pVtabCursor, &u.bl.v);
67728 importVtabErrMsg(p, u.bl.pVtab);
67729 #endif /* SQLITE_OMIT_VIRTUALTABLE */
67730 }else{
67731 assert( u.bl.pC->pCursor!=0 );
67732 rc = sqlite3VdbeCursorMoveto(u.bl.pC);
67733 if( rc ) goto abort_due_to_error;
67734 if( u.bl.pC->rowidIsValid ){
67735 u.bl.v = u.bl.pC->lastRowid;
67736 }else{
67737 rc = sqlite3BtreeKeySize(u.bl.pC->pCursor, &u.bl.v);
67738 assert( rc==SQLITE_OK ); /* Always so because of CursorMoveto() above */
67741 pOut->u.i = u.bl.v;
67742 break;
67745 /* Opcode: NullRow P1 * * * *
67747 ** Move the cursor P1 to a null row. Any OP_Column operations
67748 ** that occur while the cursor is on the null row will always
67749 ** write a NULL.
67751 case OP_NullRow: {
67752 #if 0 /* local variables moved into u.bm */
67753 VdbeCursor *pC;
67754 #endif /* local variables moved into u.bm */
67756 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67757 u.bm.pC = p->apCsr[pOp->p1];
67758 assert( u.bm.pC!=0 );
67759 u.bm.pC->nullRow = 1;
67760 u.bm.pC->rowidIsValid = 0;
67761 assert( u.bm.pC->pCursor || u.bm.pC->pVtabCursor );
67762 if( u.bm.pC->pCursor ){
67763 sqlite3BtreeClearCursor(u.bm.pC->pCursor);
67765 break;
67768 /* Opcode: Last P1 P2 * * *
67770 ** The next use of the Rowid or Column or Next instruction for P1
67771 ** will refer to the last entry in the database table or index.
67772 ** If the table or index is empty and P2>0, then jump immediately to P2.
67773 ** If P2 is 0 or if the table or index is not empty, fall through
67774 ** to the following instruction.
67776 case OP_Last: { /* jump */
67777 #if 0 /* local variables moved into u.bn */
67778 VdbeCursor *pC;
67779 BtCursor *pCrsr;
67780 int res;
67781 #endif /* local variables moved into u.bn */
67783 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67784 u.bn.pC = p->apCsr[pOp->p1];
67785 assert( u.bn.pC!=0 );
67786 u.bn.pCrsr = u.bn.pC->pCursor;
67787 u.bn.res = 0;
67788 if( ALWAYS(u.bn.pCrsr!=0) ){
67789 rc = sqlite3BtreeLast(u.bn.pCrsr, &u.bn.res);
67791 u.bn.pC->nullRow = (u8)u.bn.res;
67792 u.bn.pC->deferredMoveto = 0;
67793 u.bn.pC->rowidIsValid = 0;
67794 u.bn.pC->cacheStatus = CACHE_STALE;
67795 if( pOp->p2>0 && u.bn.res ){
67796 pc = pOp->p2 - 1;
67798 break;
67802 /* Opcode: Sort P1 P2 * * *
67804 ** This opcode does exactly the same thing as OP_Rewind except that
67805 ** it increments an undocumented global variable used for testing.
67807 ** Sorting is accomplished by writing records into a sorting index,
67808 ** then rewinding that index and playing it back from beginning to
67809 ** end. We use the OP_Sort opcode instead of OP_Rewind to do the
67810 ** rewinding so that the global variable will be incremented and
67811 ** regression tests can determine whether or not the optimizer is
67812 ** correctly optimizing out sorts.
67814 case OP_SorterSort: /* jump */
67815 #ifdef SQLITE_OMIT_MERGE_SORT
67816 pOp->opcode = OP_Sort;
67817 #endif
67818 case OP_Sort: { /* jump */
67819 #ifdef SQLITE_TEST
67820 sqlite3_sort_count++;
67821 sqlite3_search_count--;
67822 #endif
67823 p->aCounter[SQLITE_STMTSTATUS_SORT-1]++;
67824 /* Fall through into OP_Rewind */
67826 /* Opcode: Rewind P1 P2 * * *
67828 ** The next use of the Rowid or Column or Next instruction for P1
67829 ** will refer to the first entry in the database table or index.
67830 ** If the table or index is empty and P2>0, then jump immediately to P2.
67831 ** If P2 is 0 or if the table or index is not empty, fall through
67832 ** to the following instruction.
67834 case OP_Rewind: { /* jump */
67835 #if 0 /* local variables moved into u.bo */
67836 VdbeCursor *pC;
67837 BtCursor *pCrsr;
67838 int res;
67839 #endif /* local variables moved into u.bo */
67841 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67842 u.bo.pC = p->apCsr[pOp->p1];
67843 assert( u.bo.pC!=0 );
67844 assert( u.bo.pC->isSorter==(pOp->opcode==OP_SorterSort) );
67845 u.bo.res = 1;
67846 if( isSorter(u.bo.pC) ){
67847 rc = sqlite3VdbeSorterRewind(db, u.bo.pC, &u.bo.res);
67848 }else{
67849 u.bo.pCrsr = u.bo.pC->pCursor;
67850 assert( u.bo.pCrsr );
67851 rc = sqlite3BtreeFirst(u.bo.pCrsr, &u.bo.res);
67852 u.bo.pC->atFirst = u.bo.res==0 ?1:0;
67853 u.bo.pC->deferredMoveto = 0;
67854 u.bo.pC->cacheStatus = CACHE_STALE;
67855 u.bo.pC->rowidIsValid = 0;
67857 u.bo.pC->nullRow = (u8)u.bo.res;
67858 assert( pOp->p2>0 && pOp->p2<p->nOp );
67859 if( u.bo.res ){
67860 pc = pOp->p2 - 1;
67862 break;
67865 /* Opcode: Next P1 P2 * P4 P5
67867 ** Advance cursor P1 so that it points to the next key/data pair in its
67868 ** table or index. If there are no more key/value pairs then fall through
67869 ** to the following instruction. But if the cursor advance was successful,
67870 ** jump immediately to P2.
67872 ** The P1 cursor must be for a real table, not a pseudo-table.
67874 ** P4 is always of type P4_ADVANCE. The function pointer points to
67875 ** sqlite3BtreeNext().
67877 ** If P5 is positive and the jump is taken, then event counter
67878 ** number P5-1 in the prepared statement is incremented.
67880 ** See also: Prev
67882 /* Opcode: Prev P1 P2 * * P5
67884 ** Back up cursor P1 so that it points to the previous key/data pair in its
67885 ** table or index. If there is no previous key/value pairs then fall through
67886 ** to the following instruction. But if the cursor backup was successful,
67887 ** jump immediately to P2.
67889 ** The P1 cursor must be for a real table, not a pseudo-table.
67891 ** P4 is always of type P4_ADVANCE. The function pointer points to
67892 ** sqlite3BtreePrevious().
67894 ** If P5 is positive and the jump is taken, then event counter
67895 ** number P5-1 in the prepared statement is incremented.
67897 case OP_SorterNext: /* jump */
67898 #ifdef SQLITE_OMIT_MERGE_SORT
67899 pOp->opcode = OP_Next;
67900 #endif
67901 case OP_Prev: /* jump */
67902 case OP_Next: { /* jump */
67903 #if 0 /* local variables moved into u.bp */
67904 VdbeCursor *pC;
67905 int res;
67906 #endif /* local variables moved into u.bp */
67908 CHECK_FOR_INTERRUPT;
67909 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67910 assert( pOp->p5<=ArraySize(p->aCounter) );
67911 u.bp.pC = p->apCsr[pOp->p1];
67912 if( u.bp.pC==0 ){
67913 break; /* See ticket #2273 */
67915 assert( u.bp.pC->isSorter==(pOp->opcode==OP_SorterNext) );
67916 if( isSorter(u.bp.pC) ){
67917 assert( pOp->opcode==OP_SorterNext );
67918 rc = sqlite3VdbeSorterNext(db, u.bp.pC, &u.bp.res);
67919 }else{
67920 u.bp.res = 1;
67921 assert( u.bp.pC->deferredMoveto==0 );
67922 assert( u.bp.pC->pCursor );
67923 assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
67924 assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
67925 rc = pOp->p4.xAdvance(u.bp.pC->pCursor, &u.bp.res);
67927 u.bp.pC->nullRow = (u8)u.bp.res;
67928 u.bp.pC->cacheStatus = CACHE_STALE;
67929 if( u.bp.res==0 ){
67930 pc = pOp->p2 - 1;
67931 if( pOp->p5 ) p->aCounter[pOp->p5-1]++;
67932 #ifdef SQLITE_TEST
67933 sqlite3_search_count++;
67934 #endif
67936 u.bp.pC->rowidIsValid = 0;
67937 break;
67940 /* Opcode: IdxInsert P1 P2 P3 * P5
67942 ** Register P2 holds an SQL index key made using the
67943 ** MakeRecord instructions. This opcode writes that key
67944 ** into the index P1. Data for the entry is nil.
67946 ** P3 is a flag that provides a hint to the b-tree layer that this
67947 ** insert is likely to be an append.
67949 ** This instruction only works for indices. The equivalent instruction
67950 ** for tables is OP_Insert.
67952 case OP_SorterInsert: /* in2 */
67953 #ifdef SQLITE_OMIT_MERGE_SORT
67954 pOp->opcode = OP_IdxInsert;
67955 #endif
67956 case OP_IdxInsert: { /* in2 */
67957 #if 0 /* local variables moved into u.bq */
67958 VdbeCursor *pC;
67959 BtCursor *pCrsr;
67960 int nKey;
67961 const char *zKey;
67962 #endif /* local variables moved into u.bq */
67964 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67965 u.bq.pC = p->apCsr[pOp->p1];
67966 assert( u.bq.pC!=0 );
67967 assert( u.bq.pC->isSorter==(pOp->opcode==OP_SorterInsert) );
67968 pIn2 = &aMem[pOp->p2];
67969 assert( pIn2->flags & MEM_Blob );
67970 u.bq.pCrsr = u.bq.pC->pCursor;
67971 if( ALWAYS(u.bq.pCrsr!=0) ){
67972 assert( u.bq.pC->isTable==0 );
67973 rc = ExpandBlob(pIn2);
67974 if( rc==SQLITE_OK ){
67975 if( isSorter(u.bq.pC) ){
67976 rc = sqlite3VdbeSorterWrite(db, u.bq.pC, pIn2);
67977 }else{
67978 u.bq.nKey = pIn2->n;
67979 u.bq.zKey = pIn2->z;
67980 rc = sqlite3BtreeInsert(u.bq.pCrsr, u.bq.zKey, u.bq.nKey, "", 0, 0, pOp->p3,
67981 ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bq.pC->seekResult : 0)
67983 assert( u.bq.pC->deferredMoveto==0 );
67984 u.bq.pC->cacheStatus = CACHE_STALE;
67988 break;
67991 /* Opcode: IdxDelete P1 P2 P3 * *
67993 ** The content of P3 registers starting at register P2 form
67994 ** an unpacked index key. This opcode removes that entry from the
67995 ** index opened by cursor P1.
67997 case OP_IdxDelete: {
67998 #if 0 /* local variables moved into u.br */
67999 VdbeCursor *pC;
68000 BtCursor *pCrsr;
68001 int res;
68002 UnpackedRecord r;
68003 #endif /* local variables moved into u.br */
68005 assert( pOp->p3>0 );
68006 assert( pOp->p2>0 && pOp->p2+pOp->p3<=p->nMem+1 );
68007 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68008 u.br.pC = p->apCsr[pOp->p1];
68009 assert( u.br.pC!=0 );
68010 u.br.pCrsr = u.br.pC->pCursor;
68011 if( ALWAYS(u.br.pCrsr!=0) ){
68012 u.br.r.pKeyInfo = u.br.pC->pKeyInfo;
68013 u.br.r.nField = (u16)pOp->p3;
68014 u.br.r.flags = 0;
68015 u.br.r.aMem = &aMem[pOp->p2];
68016 #ifdef SQLITE_DEBUG
68017 { int i; for(i=0; i<u.br.r.nField; i++) assert( memIsValid(&u.br.r.aMem[i]) ); }
68018 #endif
68019 rc = sqlite3BtreeMovetoUnpacked(u.br.pCrsr, &u.br.r, 0, 0, &u.br.res);
68020 if( rc==SQLITE_OK && u.br.res==0 ){
68021 rc = sqlite3BtreeDelete(u.br.pCrsr);
68023 assert( u.br.pC->deferredMoveto==0 );
68024 u.br.pC->cacheStatus = CACHE_STALE;
68026 break;
68029 /* Opcode: IdxRowid P1 P2 * * *
68031 ** Write into register P2 an integer which is the last entry in the record at
68032 ** the end of the index key pointed to by cursor P1. This integer should be
68033 ** the rowid of the table entry to which this index entry points.
68035 ** See also: Rowid, MakeRecord.
68037 case OP_IdxRowid: { /* out2-prerelease */
68038 #if 0 /* local variables moved into u.bs */
68039 BtCursor *pCrsr;
68040 VdbeCursor *pC;
68041 i64 rowid;
68042 #endif /* local variables moved into u.bs */
68044 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68045 u.bs.pC = p->apCsr[pOp->p1];
68046 assert( u.bs.pC!=0 );
68047 u.bs.pCrsr = u.bs.pC->pCursor;
68048 pOut->flags = MEM_Null;
68049 if( ALWAYS(u.bs.pCrsr!=0) ){
68050 rc = sqlite3VdbeCursorMoveto(u.bs.pC);
68051 if( NEVER(rc) ) goto abort_due_to_error;
68052 assert( u.bs.pC->deferredMoveto==0 );
68053 assert( u.bs.pC->isTable==0 );
68054 if( !u.bs.pC->nullRow ){
68055 rc = sqlite3VdbeIdxRowid(db, u.bs.pCrsr, &u.bs.rowid);
68056 if( rc!=SQLITE_OK ){
68057 goto abort_due_to_error;
68059 pOut->u.i = u.bs.rowid;
68060 pOut->flags = MEM_Int;
68063 break;
68066 /* Opcode: IdxGE P1 P2 P3 P4 P5
68068 ** The P4 register values beginning with P3 form an unpacked index
68069 ** key that omits the ROWID. Compare this key value against the index
68070 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
68072 ** If the P1 index entry is greater than or equal to the key value
68073 ** then jump to P2. Otherwise fall through to the next instruction.
68075 ** If P5 is non-zero then the key value is increased by an epsilon
68076 ** prior to the comparison. This make the opcode work like IdxGT except
68077 ** that if the key from register P3 is a prefix of the key in the cursor,
68078 ** the result is false whereas it would be true with IdxGT.
68080 /* Opcode: IdxLT P1 P2 P3 P4 P5
68082 ** The P4 register values beginning with P3 form an unpacked index
68083 ** key that omits the ROWID. Compare this key value against the index
68084 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
68086 ** If the P1 index entry is less than the key value then jump to P2.
68087 ** Otherwise fall through to the next instruction.
68089 ** If P5 is non-zero then the key value is increased by an epsilon prior
68090 ** to the comparison. This makes the opcode work like IdxLE.
68092 case OP_IdxLT: /* jump */
68093 case OP_IdxGE: { /* jump */
68094 #if 0 /* local variables moved into u.bt */
68095 VdbeCursor *pC;
68096 int res;
68097 UnpackedRecord r;
68098 #endif /* local variables moved into u.bt */
68100 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68101 u.bt.pC = p->apCsr[pOp->p1];
68102 assert( u.bt.pC!=0 );
68103 assert( u.bt.pC->isOrdered );
68104 if( ALWAYS(u.bt.pC->pCursor!=0) ){
68105 assert( u.bt.pC->deferredMoveto==0 );
68106 assert( pOp->p5==0 || pOp->p5==1 );
68107 assert( pOp->p4type==P4_INT32 );
68108 u.bt.r.pKeyInfo = u.bt.pC->pKeyInfo;
68109 u.bt.r.nField = (u16)pOp->p4.i;
68110 if( pOp->p5 ){
68111 u.bt.r.flags = UNPACKED_INCRKEY | UNPACKED_IGNORE_ROWID;
68112 }else{
68113 u.bt.r.flags = UNPACKED_IGNORE_ROWID;
68115 u.bt.r.aMem = &aMem[pOp->p3];
68116 #ifdef SQLITE_DEBUG
68117 { int i; for(i=0; i<u.bt.r.nField; i++) assert( memIsValid(&u.bt.r.aMem[i]) ); }
68118 #endif
68119 rc = sqlite3VdbeIdxKeyCompare(u.bt.pC, &u.bt.r, &u.bt.res);
68120 if( pOp->opcode==OP_IdxLT ){
68121 u.bt.res = -u.bt.res;
68122 }else{
68123 assert( pOp->opcode==OP_IdxGE );
68124 u.bt.res++;
68126 if( u.bt.res>0 ){
68127 pc = pOp->p2 - 1 ;
68130 break;
68133 /* Opcode: Destroy P1 P2 P3 * *
68135 ** Delete an entire database table or index whose root page in the database
68136 ** file is given by P1.
68138 ** The table being destroyed is in the main database file if P3==0. If
68139 ** P3==1 then the table to be clear is in the auxiliary database file
68140 ** that is used to store tables create using CREATE TEMPORARY TABLE.
68142 ** If AUTOVACUUM is enabled then it is possible that another root page
68143 ** might be moved into the newly deleted root page in order to keep all
68144 ** root pages contiguous at the beginning of the database. The former
68145 ** value of the root page that moved - its value before the move occurred -
68146 ** is stored in register P2. If no page
68147 ** movement was required (because the table being dropped was already
68148 ** the last one in the database) then a zero is stored in register P2.
68149 ** If AUTOVACUUM is disabled then a zero is stored in register P2.
68151 ** See also: Clear
68153 case OP_Destroy: { /* out2-prerelease */
68154 #if 0 /* local variables moved into u.bu */
68155 int iMoved;
68156 int iCnt;
68157 Vdbe *pVdbe;
68158 int iDb;
68159 #endif /* local variables moved into u.bu */
68160 #ifndef SQLITE_OMIT_VIRTUALTABLE
68161 u.bu.iCnt = 0;
68162 for(u.bu.pVdbe=db->pVdbe; u.bu.pVdbe; u.bu.pVdbe = u.bu.pVdbe->pNext){
68163 if( u.bu.pVdbe->magic==VDBE_MAGIC_RUN && u.bu.pVdbe->inVtabMethod<2 && u.bu.pVdbe->pc>=0 ){
68164 u.bu.iCnt++;
68167 #else
68168 u.bu.iCnt = db->activeVdbeCnt;
68169 #endif
68170 pOut->flags = MEM_Null;
68171 if( u.bu.iCnt>1 ){
68172 rc = SQLITE_LOCKED;
68173 p->errorAction = OE_Abort;
68174 }else{
68175 u.bu.iDb = pOp->p3;
68176 assert( u.bu.iCnt==1 );
68177 assert( (p->btreeMask & (((yDbMask)1)<<u.bu.iDb))!=0 );
68178 rc = sqlite3BtreeDropTable(db->aDb[u.bu.iDb].pBt, pOp->p1, &u.bu.iMoved);
68179 pOut->flags = MEM_Int;
68180 pOut->u.i = u.bu.iMoved;
68181 #ifndef SQLITE_OMIT_AUTOVACUUM
68182 if( rc==SQLITE_OK && u.bu.iMoved!=0 ){
68183 sqlite3RootPageMoved(db, u.bu.iDb, u.bu.iMoved, pOp->p1);
68184 /* All OP_Destroy operations occur on the same btree */
68185 assert( resetSchemaOnFault==0 || resetSchemaOnFault==u.bu.iDb+1 );
68186 resetSchemaOnFault = u.bu.iDb+1;
68188 #endif
68190 break;
68193 /* Opcode: Clear P1 P2 P3
68195 ** Delete all contents of the database table or index whose root page
68196 ** in the database file is given by P1. But, unlike Destroy, do not
68197 ** remove the table or index from the database file.
68199 ** The table being clear is in the main database file if P2==0. If
68200 ** P2==1 then the table to be clear is in the auxiliary database file
68201 ** that is used to store tables create using CREATE TEMPORARY TABLE.
68203 ** If the P3 value is non-zero, then the table referred to must be an
68204 ** intkey table (an SQL table, not an index). In this case the row change
68205 ** count is incremented by the number of rows in the table being cleared.
68206 ** If P3 is greater than zero, then the value stored in register P3 is
68207 ** also incremented by the number of rows in the table being cleared.
68209 ** See also: Destroy
68211 case OP_Clear: {
68212 #if 0 /* local variables moved into u.bv */
68213 int nChange;
68214 #endif /* local variables moved into u.bv */
68216 u.bv.nChange = 0;
68217 assert( (p->btreeMask & (((yDbMask)1)<<pOp->p2))!=0 );
68218 rc = sqlite3BtreeClearTable(
68219 db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &u.bv.nChange : 0)
68221 if( pOp->p3 ){
68222 p->nChange += u.bv.nChange;
68223 if( pOp->p3>0 ){
68224 assert( memIsValid(&aMem[pOp->p3]) );
68225 memAboutToChange(p, &aMem[pOp->p3]);
68226 aMem[pOp->p3].u.i += u.bv.nChange;
68229 break;
68232 /* Opcode: CreateTable P1 P2 * * *
68234 ** Allocate a new table in the main database file if P1==0 or in the
68235 ** auxiliary database file if P1==1 or in an attached database if
68236 ** P1>1. Write the root page number of the new table into
68237 ** register P2
68239 ** The difference between a table and an index is this: A table must
68240 ** have a 4-byte integer key and can have arbitrary data. An index
68241 ** has an arbitrary key but no data.
68243 ** See also: CreateIndex
68245 /* Opcode: CreateIndex P1 P2 * * *
68247 ** Allocate a new index in the main database file if P1==0 or in the
68248 ** auxiliary database file if P1==1 or in an attached database if
68249 ** P1>1. Write the root page number of the new table into
68250 ** register P2.
68252 ** See documentation on OP_CreateTable for additional information.
68254 case OP_CreateIndex: /* out2-prerelease */
68255 case OP_CreateTable: { /* out2-prerelease */
68256 #if 0 /* local variables moved into u.bw */
68257 int pgno;
68258 int flags;
68259 Db *pDb;
68260 #endif /* local variables moved into u.bw */
68262 u.bw.pgno = 0;
68263 assert( pOp->p1>=0 && pOp->p1<db->nDb );
68264 assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
68265 u.bw.pDb = &db->aDb[pOp->p1];
68266 assert( u.bw.pDb->pBt!=0 );
68267 if( pOp->opcode==OP_CreateTable ){
68268 /* u.bw.flags = BTREE_INTKEY; */
68269 u.bw.flags = BTREE_INTKEY;
68270 }else{
68271 u.bw.flags = BTREE_BLOBKEY;
68273 rc = sqlite3BtreeCreateTable(u.bw.pDb->pBt, &u.bw.pgno, u.bw.flags);
68274 pOut->u.i = u.bw.pgno;
68275 break;
68278 /* Opcode: ParseSchema P1 * * P4 *
68280 ** Read and parse all entries from the SQLITE_MASTER table of database P1
68281 ** that match the WHERE clause P4.
68283 ** This opcode invokes the parser to create a new virtual machine,
68284 ** then runs the new virtual machine. It is thus a re-entrant opcode.
68286 case OP_ParseSchema: {
68287 #if 0 /* local variables moved into u.bx */
68288 int iDb;
68289 const char *zMaster;
68290 char *zSql;
68291 InitData initData;
68292 #endif /* local variables moved into u.bx */
68294 /* Any prepared statement that invokes this opcode will hold mutexes
68295 ** on every btree. This is a prerequisite for invoking
68296 ** sqlite3InitCallback().
68298 #ifdef SQLITE_DEBUG
68299 for(u.bx.iDb=0; u.bx.iDb<db->nDb; u.bx.iDb++){
68300 assert( u.bx.iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[u.bx.iDb].pBt) );
68302 #endif
68304 u.bx.iDb = pOp->p1;
68305 assert( u.bx.iDb>=0 && u.bx.iDb<db->nDb );
68306 assert( DbHasProperty(db, u.bx.iDb, DB_SchemaLoaded) );
68307 /* Used to be a conditional */ {
68308 u.bx.zMaster = SCHEMA_TABLE(u.bx.iDb);
68309 u.bx.initData.db = db;
68310 u.bx.initData.iDb = pOp->p1;
68311 u.bx.initData.pzErrMsg = &p->zErrMsg;
68312 u.bx.zSql = sqlite3MPrintf(db,
68313 "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
68314 db->aDb[u.bx.iDb].zName, u.bx.zMaster, pOp->p4.z);
68315 if( u.bx.zSql==0 ){
68316 rc = SQLITE_NOMEM;
68317 }else{
68318 assert( db->init.busy==0 );
68319 db->init.busy = 1;
68320 u.bx.initData.rc = SQLITE_OK;
68321 assert( !db->mallocFailed );
68322 rc = sqlite3_exec(db, u.bx.zSql, sqlite3InitCallback, &u.bx.initData, 0);
68323 if( rc==SQLITE_OK ) rc = u.bx.initData.rc;
68324 sqlite3DbFree(db, u.bx.zSql);
68325 db->init.busy = 0;
68328 if( rc==SQLITE_NOMEM ){
68329 goto no_mem;
68331 break;
68334 #if !defined(SQLITE_OMIT_ANALYZE)
68335 /* Opcode: LoadAnalysis P1 * * * *
68337 ** Read the sqlite_stat1 table for database P1 and load the content
68338 ** of that table into the internal index hash table. This will cause
68339 ** the analysis to be used when preparing all subsequent queries.
68341 case OP_LoadAnalysis: {
68342 assert( pOp->p1>=0 && pOp->p1<db->nDb );
68343 rc = sqlite3AnalysisLoad(db, pOp->p1);
68344 break;
68346 #endif /* !defined(SQLITE_OMIT_ANALYZE) */
68348 /* Opcode: DropTable P1 * * P4 *
68350 ** Remove the internal (in-memory) data structures that describe
68351 ** the table named P4 in database P1. This is called after a table
68352 ** is dropped in order to keep the internal representation of the
68353 ** schema consistent with what is on disk.
68355 case OP_DropTable: {
68356 sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
68357 break;
68360 /* Opcode: DropIndex P1 * * P4 *
68362 ** Remove the internal (in-memory) data structures that describe
68363 ** the index named P4 in database P1. This is called after an index
68364 ** is dropped in order to keep the internal representation of the
68365 ** schema consistent with what is on disk.
68367 case OP_DropIndex: {
68368 sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
68369 break;
68372 /* Opcode: DropTrigger P1 * * P4 *
68374 ** Remove the internal (in-memory) data structures that describe
68375 ** the trigger named P4 in database P1. This is called after a trigger
68376 ** is dropped in order to keep the internal representation of the
68377 ** schema consistent with what is on disk.
68379 case OP_DropTrigger: {
68380 sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
68381 break;
68385 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
68386 /* Opcode: IntegrityCk P1 P2 P3 * P5
68388 ** Do an analysis of the currently open database. Store in
68389 ** register P1 the text of an error message describing any problems.
68390 ** If no problems are found, store a NULL in register P1.
68392 ** The register P3 contains the maximum number of allowed errors.
68393 ** At most reg(P3) errors will be reported.
68394 ** In other words, the analysis stops as soon as reg(P1) errors are
68395 ** seen. Reg(P1) is updated with the number of errors remaining.
68397 ** The root page numbers of all tables in the database are integer
68398 ** stored in reg(P1), reg(P1+1), reg(P1+2), .... There are P2 tables
68399 ** total.
68401 ** If P5 is not zero, the check is done on the auxiliary database
68402 ** file, not the main database file.
68404 ** This opcode is used to implement the integrity_check pragma.
68406 case OP_IntegrityCk: {
68407 #if 0 /* local variables moved into u.by */
68408 int nRoot; /* Number of tables to check. (Number of root pages.) */
68409 int *aRoot; /* Array of rootpage numbers for tables to be checked */
68410 int j; /* Loop counter */
68411 int nErr; /* Number of errors reported */
68412 char *z; /* Text of the error report */
68413 Mem *pnErr; /* Register keeping track of errors remaining */
68414 #endif /* local variables moved into u.by */
68416 u.by.nRoot = pOp->p2;
68417 assert( u.by.nRoot>0 );
68418 u.by.aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(u.by.nRoot+1) );
68419 if( u.by.aRoot==0 ) goto no_mem;
68420 assert( pOp->p3>0 && pOp->p3<=p->nMem );
68421 u.by.pnErr = &aMem[pOp->p3];
68422 assert( (u.by.pnErr->flags & MEM_Int)!=0 );
68423 assert( (u.by.pnErr->flags & (MEM_Str|MEM_Blob))==0 );
68424 pIn1 = &aMem[pOp->p1];
68425 for(u.by.j=0; u.by.j<u.by.nRoot; u.by.j++){
68426 u.by.aRoot[u.by.j] = (int)sqlite3VdbeIntValue(&pIn1[u.by.j]);
68428 u.by.aRoot[u.by.j] = 0;
68429 assert( pOp->p5<db->nDb );
68430 assert( (p->btreeMask & (((yDbMask)1)<<pOp->p5))!=0 );
68431 u.by.z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, u.by.aRoot, u.by.nRoot,
68432 (int)u.by.pnErr->u.i, &u.by.nErr);
68433 sqlite3DbFree(db, u.by.aRoot);
68434 u.by.pnErr->u.i -= u.by.nErr;
68435 sqlite3VdbeMemSetNull(pIn1);
68436 if( u.by.nErr==0 ){
68437 assert( u.by.z==0 );
68438 }else if( u.by.z==0 ){
68439 goto no_mem;
68440 }else{
68441 sqlite3VdbeMemSetStr(pIn1, u.by.z, -1, SQLITE_UTF8, sqlite3_free);
68443 UPDATE_MAX_BLOBSIZE(pIn1);
68444 sqlite3VdbeChangeEncoding(pIn1, encoding);
68445 break;
68447 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
68449 /* Opcode: RowSetAdd P1 P2 * * *
68451 ** Insert the integer value held by register P2 into a boolean index
68452 ** held in register P1.
68454 ** An assertion fails if P2 is not an integer.
68456 case OP_RowSetAdd: { /* in1, in2 */
68457 pIn1 = &aMem[pOp->p1];
68458 pIn2 = &aMem[pOp->p2];
68459 assert( (pIn2->flags & MEM_Int)!=0 );
68460 if( (pIn1->flags & MEM_RowSet)==0 ){
68461 sqlite3VdbeMemSetRowSet(pIn1);
68462 if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
68464 sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
68465 break;
68468 /* Opcode: RowSetRead P1 P2 P3 * *
68470 ** Extract the smallest value from boolean index P1 and put that value into
68471 ** register P3. Or, if boolean index P1 is initially empty, leave P3
68472 ** unchanged and jump to instruction P2.
68474 case OP_RowSetRead: { /* jump, in1, out3 */
68475 #if 0 /* local variables moved into u.bz */
68476 i64 val;
68477 #endif /* local variables moved into u.bz */
68478 CHECK_FOR_INTERRUPT;
68479 pIn1 = &aMem[pOp->p1];
68480 if( (pIn1->flags & MEM_RowSet)==0
68481 || sqlite3RowSetNext(pIn1->u.pRowSet, &u.bz.val)==0
68483 /* The boolean index is empty */
68484 sqlite3VdbeMemSetNull(pIn1);
68485 pc = pOp->p2 - 1;
68486 }else{
68487 /* A value was pulled from the index */
68488 sqlite3VdbeMemSetInt64(&aMem[pOp->p3], u.bz.val);
68490 break;
68493 /* Opcode: RowSetTest P1 P2 P3 P4
68495 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
68496 ** contains a RowSet object and that RowSet object contains
68497 ** the value held in P3, jump to register P2. Otherwise, insert the
68498 ** integer in P3 into the RowSet and continue on to the
68499 ** next opcode.
68501 ** The RowSet object is optimized for the case where successive sets
68502 ** of integers, where each set contains no duplicates. Each set
68503 ** of values is identified by a unique P4 value. The first set
68504 ** must have P4==0, the final set P4=-1. P4 must be either -1 or
68505 ** non-negative. For non-negative values of P4 only the lower 4
68506 ** bits are significant.
68508 ** This allows optimizations: (a) when P4==0 there is no need to test
68509 ** the rowset object for P3, as it is guaranteed not to contain it,
68510 ** (b) when P4==-1 there is no need to insert the value, as it will
68511 ** never be tested for, and (c) when a value that is part of set X is
68512 ** inserted, there is no need to search to see if the same value was
68513 ** previously inserted as part of set X (only if it was previously
68514 ** inserted as part of some other set).
68516 case OP_RowSetTest: { /* jump, in1, in3 */
68517 #if 0 /* local variables moved into u.ca */
68518 int iSet;
68519 int exists;
68520 #endif /* local variables moved into u.ca */
68522 pIn1 = &aMem[pOp->p1];
68523 pIn3 = &aMem[pOp->p3];
68524 u.ca.iSet = pOp->p4.i;
68525 assert( pIn3->flags&MEM_Int );
68527 /* If there is anything other than a rowset object in memory cell P1,
68528 ** delete it now and initialize P1 with an empty rowset
68530 if( (pIn1->flags & MEM_RowSet)==0 ){
68531 sqlite3VdbeMemSetRowSet(pIn1);
68532 if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
68535 assert( pOp->p4type==P4_INT32 );
68536 assert( u.ca.iSet==-1 || u.ca.iSet>=0 );
68537 if( u.ca.iSet ){
68538 u.ca.exists = sqlite3RowSetTest(pIn1->u.pRowSet,
68539 (u8)(u.ca.iSet>=0 ? u.ca.iSet & 0xf : 0xff),
68540 pIn3->u.i);
68541 if( u.ca.exists ){
68542 pc = pOp->p2 - 1;
68543 break;
68546 if( u.ca.iSet>=0 ){
68547 sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
68549 break;
68553 #ifndef SQLITE_OMIT_TRIGGER
68555 /* Opcode: Program P1 P2 P3 P4 *
68557 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
68559 ** P1 contains the address of the memory cell that contains the first memory
68560 ** cell in an array of values used as arguments to the sub-program. P2
68561 ** contains the address to jump to if the sub-program throws an IGNORE
68562 ** exception using the RAISE() function. Register P3 contains the address
68563 ** of a memory cell in this (the parent) VM that is used to allocate the
68564 ** memory required by the sub-vdbe at runtime.
68566 ** P4 is a pointer to the VM containing the trigger program.
68568 case OP_Program: { /* jump */
68569 #if 0 /* local variables moved into u.cb */
68570 int nMem; /* Number of memory registers for sub-program */
68571 int nByte; /* Bytes of runtime space required for sub-program */
68572 Mem *pRt; /* Register to allocate runtime space */
68573 Mem *pMem; /* Used to iterate through memory cells */
68574 Mem *pEnd; /* Last memory cell in new array */
68575 VdbeFrame *pFrame; /* New vdbe frame to execute in */
68576 SubProgram *pProgram; /* Sub-program to execute */
68577 void *t; /* Token identifying trigger */
68578 #endif /* local variables moved into u.cb */
68580 u.cb.pProgram = pOp->p4.pProgram;
68581 u.cb.pRt = &aMem[pOp->p3];
68582 assert( memIsValid(u.cb.pRt) );
68583 assert( u.cb.pProgram->nOp>0 );
68585 /* If the p5 flag is clear, then recursive invocation of triggers is
68586 ** disabled for backwards compatibility (p5 is set if this sub-program
68587 ** is really a trigger, not a foreign key action, and the flag set
68588 ** and cleared by the "PRAGMA recursive_triggers" command is clear).
68590 ** It is recursive invocation of triggers, at the SQL level, that is
68591 ** disabled. In some cases a single trigger may generate more than one
68592 ** SubProgram (if the trigger may be executed with more than one different
68593 ** ON CONFLICT algorithm). SubProgram structures associated with a
68594 ** single trigger all have the same value for the SubProgram.token
68595 ** variable. */
68596 if( pOp->p5 ){
68597 u.cb.t = u.cb.pProgram->token;
68598 for(u.cb.pFrame=p->pFrame; u.cb.pFrame && u.cb.pFrame->token!=u.cb.t; u.cb.pFrame=u.cb.pFrame->pParent);
68599 if( u.cb.pFrame ) break;
68602 if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
68603 rc = SQLITE_ERROR;
68604 sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
68605 break;
68608 /* Register u.cb.pRt is used to store the memory required to save the state
68609 ** of the current program, and the memory required at runtime to execute
68610 ** the trigger program. If this trigger has been fired before, then u.cb.pRt
68611 ** is already allocated. Otherwise, it must be initialized. */
68612 if( (u.cb.pRt->flags&MEM_Frame)==0 ){
68613 /* SubProgram.nMem is set to the number of memory cells used by the
68614 ** program stored in SubProgram.aOp. As well as these, one memory
68615 ** cell is required for each cursor used by the program. Set local
68616 ** variable u.cb.nMem (and later, VdbeFrame.nChildMem) to this value.
68618 u.cb.nMem = u.cb.pProgram->nMem + u.cb.pProgram->nCsr;
68619 u.cb.nByte = ROUND8(sizeof(VdbeFrame))
68620 + u.cb.nMem * sizeof(Mem)
68621 + u.cb.pProgram->nCsr * sizeof(VdbeCursor *);
68622 u.cb.pFrame = sqlite3DbMallocZero(db, u.cb.nByte);
68623 if( !u.cb.pFrame ){
68624 goto no_mem;
68626 sqlite3VdbeMemRelease(u.cb.pRt);
68627 u.cb.pRt->flags = MEM_Frame;
68628 u.cb.pRt->u.pFrame = u.cb.pFrame;
68630 u.cb.pFrame->v = p;
68631 u.cb.pFrame->nChildMem = u.cb.nMem;
68632 u.cb.pFrame->nChildCsr = u.cb.pProgram->nCsr;
68633 u.cb.pFrame->pc = pc;
68634 u.cb.pFrame->aMem = p->aMem;
68635 u.cb.pFrame->nMem = p->nMem;
68636 u.cb.pFrame->apCsr = p->apCsr;
68637 u.cb.pFrame->nCursor = p->nCursor;
68638 u.cb.pFrame->aOp = p->aOp;
68639 u.cb.pFrame->nOp = p->nOp;
68640 u.cb.pFrame->token = u.cb.pProgram->token;
68642 u.cb.pEnd = &VdbeFrameMem(u.cb.pFrame)[u.cb.pFrame->nChildMem];
68643 for(u.cb.pMem=VdbeFrameMem(u.cb.pFrame); u.cb.pMem!=u.cb.pEnd; u.cb.pMem++){
68644 u.cb.pMem->flags = MEM_Null;
68645 u.cb.pMem->db = db;
68647 }else{
68648 u.cb.pFrame = u.cb.pRt->u.pFrame;
68649 assert( u.cb.pProgram->nMem+u.cb.pProgram->nCsr==u.cb.pFrame->nChildMem );
68650 assert( u.cb.pProgram->nCsr==u.cb.pFrame->nChildCsr );
68651 assert( pc==u.cb.pFrame->pc );
68654 p->nFrame++;
68655 u.cb.pFrame->pParent = p->pFrame;
68656 u.cb.pFrame->lastRowid = lastRowid;
68657 u.cb.pFrame->nChange = p->nChange;
68658 p->nChange = 0;
68659 p->pFrame = u.cb.pFrame;
68660 p->aMem = aMem = &VdbeFrameMem(u.cb.pFrame)[-1];
68661 p->nMem = u.cb.pFrame->nChildMem;
68662 p->nCursor = (u16)u.cb.pFrame->nChildCsr;
68663 p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
68664 p->aOp = aOp = u.cb.pProgram->aOp;
68665 p->nOp = u.cb.pProgram->nOp;
68666 pc = -1;
68668 break;
68671 /* Opcode: Param P1 P2 * * *
68673 ** This opcode is only ever present in sub-programs called via the
68674 ** OP_Program instruction. Copy a value currently stored in a memory
68675 ** cell of the calling (parent) frame to cell P2 in the current frames
68676 ** address space. This is used by trigger programs to access the new.*
68677 ** and old.* values.
68679 ** The address of the cell in the parent frame is determined by adding
68680 ** the value of the P1 argument to the value of the P1 argument to the
68681 ** calling OP_Program instruction.
68683 case OP_Param: { /* out2-prerelease */
68684 #if 0 /* local variables moved into u.cc */
68685 VdbeFrame *pFrame;
68686 Mem *pIn;
68687 #endif /* local variables moved into u.cc */
68688 u.cc.pFrame = p->pFrame;
68689 u.cc.pIn = &u.cc.pFrame->aMem[pOp->p1 + u.cc.pFrame->aOp[u.cc.pFrame->pc].p1];
68690 sqlite3VdbeMemShallowCopy(pOut, u.cc.pIn, MEM_Ephem);
68691 break;
68694 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
68696 #ifndef SQLITE_OMIT_FOREIGN_KEY
68697 /* Opcode: FkCounter P1 P2 * * *
68699 ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
68700 ** If P1 is non-zero, the database constraint counter is incremented
68701 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
68702 ** statement counter is incremented (immediate foreign key constraints).
68704 case OP_FkCounter: {
68705 if( pOp->p1 ){
68706 db->nDeferredCons += pOp->p2;
68707 }else{
68708 p->nFkConstraint += pOp->p2;
68710 break;
68713 /* Opcode: FkIfZero P1 P2 * * *
68715 ** This opcode tests if a foreign key constraint-counter is currently zero.
68716 ** If so, jump to instruction P2. Otherwise, fall through to the next
68717 ** instruction.
68719 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
68720 ** is zero (the one that counts deferred constraint violations). If P1 is
68721 ** zero, the jump is taken if the statement constraint-counter is zero
68722 ** (immediate foreign key constraint violations).
68724 case OP_FkIfZero: { /* jump */
68725 if( pOp->p1 ){
68726 if( db->nDeferredCons==0 ) pc = pOp->p2-1;
68727 }else{
68728 if( p->nFkConstraint==0 ) pc = pOp->p2-1;
68730 break;
68732 #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
68734 #ifndef SQLITE_OMIT_AUTOINCREMENT
68735 /* Opcode: MemMax P1 P2 * * *
68737 ** P1 is a register in the root frame of this VM (the root frame is
68738 ** different from the current frame if this instruction is being executed
68739 ** within a sub-program). Set the value of register P1 to the maximum of
68740 ** its current value and the value in register P2.
68742 ** This instruction throws an error if the memory cell is not initially
68743 ** an integer.
68745 case OP_MemMax: { /* in2 */
68746 #if 0 /* local variables moved into u.cd */
68747 Mem *pIn1;
68748 VdbeFrame *pFrame;
68749 #endif /* local variables moved into u.cd */
68750 if( p->pFrame ){
68751 for(u.cd.pFrame=p->pFrame; u.cd.pFrame->pParent; u.cd.pFrame=u.cd.pFrame->pParent);
68752 u.cd.pIn1 = &u.cd.pFrame->aMem[pOp->p1];
68753 }else{
68754 u.cd.pIn1 = &aMem[pOp->p1];
68756 assert( memIsValid(u.cd.pIn1) );
68757 sqlite3VdbeMemIntegerify(u.cd.pIn1);
68758 pIn2 = &aMem[pOp->p2];
68759 sqlite3VdbeMemIntegerify(pIn2);
68760 if( u.cd.pIn1->u.i<pIn2->u.i){
68761 u.cd.pIn1->u.i = pIn2->u.i;
68763 break;
68765 #endif /* SQLITE_OMIT_AUTOINCREMENT */
68767 /* Opcode: IfPos P1 P2 * * *
68769 ** If the value of register P1 is 1 or greater, jump to P2.
68771 ** It is illegal to use this instruction on a register that does
68772 ** not contain an integer. An assertion fault will result if you try.
68774 case OP_IfPos: { /* jump, in1 */
68775 pIn1 = &aMem[pOp->p1];
68776 assert( pIn1->flags&MEM_Int );
68777 if( pIn1->u.i>0 ){
68778 pc = pOp->p2 - 1;
68780 break;
68783 /* Opcode: IfNeg P1 P2 * * *
68785 ** If the value of register P1 is less than zero, jump to P2.
68787 ** It is illegal to use this instruction on a register that does
68788 ** not contain an integer. An assertion fault will result if you try.
68790 case OP_IfNeg: { /* jump, in1 */
68791 pIn1 = &aMem[pOp->p1];
68792 assert( pIn1->flags&MEM_Int );
68793 if( pIn1->u.i<0 ){
68794 pc = pOp->p2 - 1;
68796 break;
68799 /* Opcode: IfZero P1 P2 P3 * *
68801 ** The register P1 must contain an integer. Add literal P3 to the
68802 ** value in register P1. If the result is exactly 0, jump to P2.
68804 ** It is illegal to use this instruction on a register that does
68805 ** not contain an integer. An assertion fault will result if you try.
68807 case OP_IfZero: { /* jump, in1 */
68808 pIn1 = &aMem[pOp->p1];
68809 assert( pIn1->flags&MEM_Int );
68810 pIn1->u.i += pOp->p3;
68811 if( pIn1->u.i==0 ){
68812 pc = pOp->p2 - 1;
68814 break;
68817 /* Opcode: AggStep * P2 P3 P4 P5
68819 ** Execute the step function for an aggregate. The
68820 ** function has P5 arguments. P4 is a pointer to the FuncDef
68821 ** structure that specifies the function. Use register
68822 ** P3 as the accumulator.
68824 ** The P5 arguments are taken from register P2 and its
68825 ** successors.
68827 case OP_AggStep: {
68828 #if 0 /* local variables moved into u.ce */
68829 int n;
68830 int i;
68831 Mem *pMem;
68832 Mem *pRec;
68833 sqlite3_context ctx;
68834 sqlite3_value **apVal;
68835 #endif /* local variables moved into u.ce */
68837 u.ce.n = pOp->p5;
68838 assert( u.ce.n>=0 );
68839 u.ce.pRec = &aMem[pOp->p2];
68840 u.ce.apVal = p->apArg;
68841 assert( u.ce.apVal || u.ce.n==0 );
68842 for(u.ce.i=0; u.ce.i<u.ce.n; u.ce.i++, u.ce.pRec++){
68843 assert( memIsValid(u.ce.pRec) );
68844 u.ce.apVal[u.ce.i] = u.ce.pRec;
68845 memAboutToChange(p, u.ce.pRec);
68846 sqlite3VdbeMemStoreType(u.ce.pRec);
68848 u.ce.ctx.pFunc = pOp->p4.pFunc;
68849 assert( pOp->p3>0 && pOp->p3<=p->nMem );
68850 u.ce.ctx.pMem = u.ce.pMem = &aMem[pOp->p3];
68851 u.ce.pMem->n++;
68852 u.ce.ctx.s.flags = MEM_Null;
68853 u.ce.ctx.s.z = 0;
68854 u.ce.ctx.s.zMalloc = 0;
68855 u.ce.ctx.s.xDel = 0;
68856 u.ce.ctx.s.db = db;
68857 u.ce.ctx.isError = 0;
68858 u.ce.ctx.pColl = 0;
68859 if( u.ce.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
68860 assert( pOp>p->aOp );
68861 assert( pOp[-1].p4type==P4_COLLSEQ );
68862 assert( pOp[-1].opcode==OP_CollSeq );
68863 u.ce.ctx.pColl = pOp[-1].p4.pColl;
68865 (u.ce.ctx.pFunc->xStep)(&u.ce.ctx, u.ce.n, u.ce.apVal); /* IMP: R-24505-23230 */
68866 if( u.ce.ctx.isError ){
68867 sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.ce.ctx.s));
68868 rc = u.ce.ctx.isError;
68871 sqlite3VdbeMemRelease(&u.ce.ctx.s);
68873 break;
68876 /* Opcode: AggFinal P1 P2 * P4 *
68878 ** Execute the finalizer function for an aggregate. P1 is
68879 ** the memory location that is the accumulator for the aggregate.
68881 ** P2 is the number of arguments that the step function takes and
68882 ** P4 is a pointer to the FuncDef for this function. The P2
68883 ** argument is not used by this opcode. It is only there to disambiguate
68884 ** functions that can take varying numbers of arguments. The
68885 ** P4 argument is only needed for the degenerate case where
68886 ** the step function was not previously called.
68888 case OP_AggFinal: {
68889 #if 0 /* local variables moved into u.cf */
68890 Mem *pMem;
68891 #endif /* local variables moved into u.cf */
68892 assert( pOp->p1>0 && pOp->p1<=p->nMem );
68893 u.cf.pMem = &aMem[pOp->p1];
68894 assert( (u.cf.pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
68895 rc = sqlite3VdbeMemFinalize(u.cf.pMem, pOp->p4.pFunc);
68896 if( rc ){
68897 sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(u.cf.pMem));
68899 sqlite3VdbeChangeEncoding(u.cf.pMem, encoding);
68900 UPDATE_MAX_BLOBSIZE(u.cf.pMem);
68901 if( sqlite3VdbeMemTooBig(u.cf.pMem) ){
68902 goto too_big;
68904 break;
68907 #ifndef SQLITE_OMIT_WAL
68908 /* Opcode: Checkpoint P1 P2 P3 * *
68910 ** Checkpoint database P1. This is a no-op if P1 is not currently in
68911 ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL
68912 ** or RESTART. Write 1 or 0 into mem[P3] if the checkpoint returns
68913 ** SQLITE_BUSY or not, respectively. Write the number of pages in the
68914 ** WAL after the checkpoint into mem[P3+1] and the number of pages
68915 ** in the WAL that have been checkpointed after the checkpoint
68916 ** completes into mem[P3+2]. However on an error, mem[P3+1] and
68917 ** mem[P3+2] are initialized to -1.
68919 case OP_Checkpoint: {
68920 #if 0 /* local variables moved into u.cg */
68921 int i; /* Loop counter */
68922 int aRes[3]; /* Results */
68923 Mem *pMem; /* Write results here */
68924 #endif /* local variables moved into u.cg */
68926 u.cg.aRes[0] = 0;
68927 u.cg.aRes[1] = u.cg.aRes[2] = -1;
68928 assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
68929 || pOp->p2==SQLITE_CHECKPOINT_FULL
68930 || pOp->p2==SQLITE_CHECKPOINT_RESTART
68932 rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &u.cg.aRes[1], &u.cg.aRes[2]);
68933 if( rc==SQLITE_BUSY ){
68934 rc = SQLITE_OK;
68935 u.cg.aRes[0] = 1;
68937 for(u.cg.i=0, u.cg.pMem = &aMem[pOp->p3]; u.cg.i<3; u.cg.i++, u.cg.pMem++){
68938 sqlite3VdbeMemSetInt64(u.cg.pMem, (i64)u.cg.aRes[u.cg.i]);
68940 break;
68942 #endif
68944 #ifndef SQLITE_OMIT_PRAGMA
68945 /* Opcode: JournalMode P1 P2 P3 * P5
68947 ** Change the journal mode of database P1 to P3. P3 must be one of the
68948 ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
68949 ** modes (delete, truncate, persist, off and memory), this is a simple
68950 ** operation. No IO is required.
68952 ** If changing into or out of WAL mode the procedure is more complicated.
68954 ** Write a string containing the final journal-mode to register P2.
68956 case OP_JournalMode: { /* out2-prerelease */
68957 #if 0 /* local variables moved into u.ch */
68958 Btree *pBt; /* Btree to change journal mode of */
68959 Pager *pPager; /* Pager associated with pBt */
68960 int eNew; /* New journal mode */
68961 int eOld; /* The old journal mode */
68962 const char *zFilename; /* Name of database file for pPager */
68963 #endif /* local variables moved into u.ch */
68965 u.ch.eNew = pOp->p3;
68966 assert( u.ch.eNew==PAGER_JOURNALMODE_DELETE
68967 || u.ch.eNew==PAGER_JOURNALMODE_TRUNCATE
68968 || u.ch.eNew==PAGER_JOURNALMODE_PERSIST
68969 || u.ch.eNew==PAGER_JOURNALMODE_OFF
68970 || u.ch.eNew==PAGER_JOURNALMODE_MEMORY
68971 || u.ch.eNew==PAGER_JOURNALMODE_WAL
68972 || u.ch.eNew==PAGER_JOURNALMODE_QUERY
68974 assert( pOp->p1>=0 && pOp->p1<db->nDb );
68976 u.ch.pBt = db->aDb[pOp->p1].pBt;
68977 u.ch.pPager = sqlite3BtreePager(u.ch.pBt);
68978 u.ch.eOld = sqlite3PagerGetJournalMode(u.ch.pPager);
68979 if( u.ch.eNew==PAGER_JOURNALMODE_QUERY ) u.ch.eNew = u.ch.eOld;
68980 if( !sqlite3PagerOkToChangeJournalMode(u.ch.pPager) ) u.ch.eNew = u.ch.eOld;
68982 #ifndef SQLITE_OMIT_WAL
68983 u.ch.zFilename = sqlite3PagerFilename(u.ch.pPager);
68985 /* Do not allow a transition to journal_mode=WAL for a database
68986 ** in temporary storage or if the VFS does not support shared memory
68988 if( u.ch.eNew==PAGER_JOURNALMODE_WAL
68989 && (sqlite3Strlen30(u.ch.zFilename)==0 /* Temp file */
68990 || !sqlite3PagerWalSupported(u.ch.pPager)) /* No shared-memory support */
68992 u.ch.eNew = u.ch.eOld;
68995 if( (u.ch.eNew!=u.ch.eOld)
68996 && (u.ch.eOld==PAGER_JOURNALMODE_WAL || u.ch.eNew==PAGER_JOURNALMODE_WAL)
68998 if( !db->autoCommit || db->activeVdbeCnt>1 ){
68999 rc = SQLITE_ERROR;
69000 sqlite3SetString(&p->zErrMsg, db,
69001 "cannot change %s wal mode from within a transaction",
69002 (u.ch.eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
69004 break;
69005 }else{
69007 if( u.ch.eOld==PAGER_JOURNALMODE_WAL ){
69008 /* If leaving WAL mode, close the log file. If successful, the call
69009 ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
69010 ** file. An EXCLUSIVE lock may still be held on the database file
69011 ** after a successful return.
69013 rc = sqlite3PagerCloseWal(u.ch.pPager);
69014 if( rc==SQLITE_OK ){
69015 sqlite3PagerSetJournalMode(u.ch.pPager, u.ch.eNew);
69017 }else if( u.ch.eOld==PAGER_JOURNALMODE_MEMORY ){
69018 /* Cannot transition directly from MEMORY to WAL. Use mode OFF
69019 ** as an intermediate */
69020 sqlite3PagerSetJournalMode(u.ch.pPager, PAGER_JOURNALMODE_OFF);
69023 /* Open a transaction on the database file. Regardless of the journal
69024 ** mode, this transaction always uses a rollback journal.
69026 assert( sqlite3BtreeIsInTrans(u.ch.pBt)==0 );
69027 if( rc==SQLITE_OK ){
69028 rc = sqlite3BtreeSetVersion(u.ch.pBt, (u.ch.eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
69032 #endif /* ifndef SQLITE_OMIT_WAL */
69034 if( rc ){
69035 u.ch.eNew = u.ch.eOld;
69037 u.ch.eNew = sqlite3PagerSetJournalMode(u.ch.pPager, u.ch.eNew);
69039 pOut = &aMem[pOp->p2];
69040 pOut->flags = MEM_Str|MEM_Static|MEM_Term;
69041 pOut->z = (char *)sqlite3JournalModename(u.ch.eNew);
69042 pOut->n = sqlite3Strlen30(pOut->z);
69043 pOut->enc = SQLITE_UTF8;
69044 sqlite3VdbeChangeEncoding(pOut, encoding);
69045 break;
69047 #endif /* SQLITE_OMIT_PRAGMA */
69049 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
69050 /* Opcode: Vacuum * * * * *
69052 ** Vacuum the entire database. This opcode will cause other virtual
69053 ** machines to be created and run. It may not be called from within
69054 ** a transaction.
69056 case OP_Vacuum: {
69057 rc = sqlite3RunVacuum(&p->zErrMsg, db);
69058 break;
69060 #endif
69062 #if !defined(SQLITE_OMIT_AUTOVACUUM)
69063 /* Opcode: IncrVacuum P1 P2 * * *
69065 ** Perform a single step of the incremental vacuum procedure on
69066 ** the P1 database. If the vacuum has finished, jump to instruction
69067 ** P2. Otherwise, fall through to the next instruction.
69069 case OP_IncrVacuum: { /* jump */
69070 #if 0 /* local variables moved into u.ci */
69071 Btree *pBt;
69072 #endif /* local variables moved into u.ci */
69074 assert( pOp->p1>=0 && pOp->p1<db->nDb );
69075 assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
69076 u.ci.pBt = db->aDb[pOp->p1].pBt;
69077 rc = sqlite3BtreeIncrVacuum(u.ci.pBt);
69078 if( rc==SQLITE_DONE ){
69079 pc = pOp->p2 - 1;
69080 rc = SQLITE_OK;
69082 break;
69084 #endif
69086 /* Opcode: Expire P1 * * * *
69088 ** Cause precompiled statements to become expired. An expired statement
69089 ** fails with an error code of SQLITE_SCHEMA if it is ever executed
69090 ** (via sqlite3_step()).
69092 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
69093 ** then only the currently executing statement is affected.
69095 case OP_Expire: {
69096 if( !pOp->p1 ){
69097 sqlite3ExpirePreparedStatements(db);
69098 }else{
69099 p->expired = 1;
69101 break;
69104 #ifndef SQLITE_OMIT_SHARED_CACHE
69105 /* Opcode: TableLock P1 P2 P3 P4 *
69107 ** Obtain a lock on a particular table. This instruction is only used when
69108 ** the shared-cache feature is enabled.
69110 ** P1 is the index of the database in sqlite3.aDb[] of the database
69111 ** on which the lock is acquired. A readlock is obtained if P3==0 or
69112 ** a write lock if P3==1.
69114 ** P2 contains the root-page of the table to lock.
69116 ** P4 contains a pointer to the name of the table being locked. This is only
69117 ** used to generate an error message if the lock cannot be obtained.
69119 case OP_TableLock: {
69120 u8 isWriteLock = (u8)pOp->p3;
69121 if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
69122 int p1 = pOp->p1;
69123 assert( p1>=0 && p1<db->nDb );
69124 assert( (p->btreeMask & (((yDbMask)1)<<p1))!=0 );
69125 assert( isWriteLock==0 || isWriteLock==1 );
69126 rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
69127 if( (rc&0xFF)==SQLITE_LOCKED ){
69128 const char *z = pOp->p4.z;
69129 sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
69132 break;
69134 #endif /* SQLITE_OMIT_SHARED_CACHE */
69136 #ifndef SQLITE_OMIT_VIRTUALTABLE
69137 /* Opcode: VBegin * * * P4 *
69139 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
69140 ** xBegin method for that table.
69142 ** Also, whether or not P4 is set, check that this is not being called from
69143 ** within a callback to a virtual table xSync() method. If it is, the error
69144 ** code will be set to SQLITE_LOCKED.
69146 case OP_VBegin: {
69147 #if 0 /* local variables moved into u.cj */
69148 VTable *pVTab;
69149 #endif /* local variables moved into u.cj */
69150 u.cj.pVTab = pOp->p4.pVtab;
69151 rc = sqlite3VtabBegin(db, u.cj.pVTab);
69152 if( u.cj.pVTab ) importVtabErrMsg(p, u.cj.pVTab->pVtab);
69153 break;
69155 #endif /* SQLITE_OMIT_VIRTUALTABLE */
69157 #ifndef SQLITE_OMIT_VIRTUALTABLE
69158 /* Opcode: VCreate P1 * * P4 *
69160 ** P4 is the name of a virtual table in database P1. Call the xCreate method
69161 ** for that table.
69163 case OP_VCreate: {
69164 rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
69165 break;
69167 #endif /* SQLITE_OMIT_VIRTUALTABLE */
69169 #ifndef SQLITE_OMIT_VIRTUALTABLE
69170 /* Opcode: VDestroy P1 * * P4 *
69172 ** P4 is the name of a virtual table in database P1. Call the xDestroy method
69173 ** of that table.
69175 case OP_VDestroy: {
69176 p->inVtabMethod = 2;
69177 rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
69178 p->inVtabMethod = 0;
69179 break;
69181 #endif /* SQLITE_OMIT_VIRTUALTABLE */
69183 #ifndef SQLITE_OMIT_VIRTUALTABLE
69184 /* Opcode: VOpen P1 * * P4 *
69186 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
69187 ** P1 is a cursor number. This opcode opens a cursor to the virtual
69188 ** table and stores that cursor in P1.
69190 case OP_VOpen: {
69191 #if 0 /* local variables moved into u.ck */
69192 VdbeCursor *pCur;
69193 sqlite3_vtab_cursor *pVtabCursor;
69194 sqlite3_vtab *pVtab;
69195 sqlite3_module *pModule;
69196 #endif /* local variables moved into u.ck */
69198 u.ck.pCur = 0;
69199 u.ck.pVtabCursor = 0;
69200 u.ck.pVtab = pOp->p4.pVtab->pVtab;
69201 u.ck.pModule = (sqlite3_module *)u.ck.pVtab->pModule;
69202 assert(u.ck.pVtab && u.ck.pModule);
69203 rc = u.ck.pModule->xOpen(u.ck.pVtab, &u.ck.pVtabCursor);
69204 importVtabErrMsg(p, u.ck.pVtab);
69205 if( SQLITE_OK==rc ){
69206 /* Initialize sqlite3_vtab_cursor base class */
69207 u.ck.pVtabCursor->pVtab = u.ck.pVtab;
69209 /* Initialise vdbe cursor object */
69210 u.ck.pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
69211 if( u.ck.pCur ){
69212 u.ck.pCur->pVtabCursor = u.ck.pVtabCursor;
69213 u.ck.pCur->pModule = u.ck.pVtabCursor->pVtab->pModule;
69214 }else{
69215 db->mallocFailed = 1;
69216 u.ck.pModule->xClose(u.ck.pVtabCursor);
69219 break;
69221 #endif /* SQLITE_OMIT_VIRTUALTABLE */
69223 #ifndef SQLITE_OMIT_VIRTUALTABLE
69224 /* Opcode: VFilter P1 P2 P3 P4 *
69226 ** P1 is a cursor opened using VOpen. P2 is an address to jump to if
69227 ** the filtered result set is empty.
69229 ** P4 is either NULL or a string that was generated by the xBestIndex
69230 ** method of the module. The interpretation of the P4 string is left
69231 ** to the module implementation.
69233 ** This opcode invokes the xFilter method on the virtual table specified
69234 ** by P1. The integer query plan parameter to xFilter is stored in register
69235 ** P3. Register P3+1 stores the argc parameter to be passed to the
69236 ** xFilter method. Registers P3+2..P3+1+argc are the argc
69237 ** additional parameters which are passed to
69238 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
69240 ** A jump is made to P2 if the result set after filtering would be empty.
69242 case OP_VFilter: { /* jump */
69243 #if 0 /* local variables moved into u.cl */
69244 int nArg;
69245 int iQuery;
69246 const sqlite3_module *pModule;
69247 Mem *pQuery;
69248 Mem *pArgc;
69249 sqlite3_vtab_cursor *pVtabCursor;
69250 sqlite3_vtab *pVtab;
69251 VdbeCursor *pCur;
69252 int res;
69253 int i;
69254 Mem **apArg;
69255 #endif /* local variables moved into u.cl */
69257 u.cl.pQuery = &aMem[pOp->p3];
69258 u.cl.pArgc = &u.cl.pQuery[1];
69259 u.cl.pCur = p->apCsr[pOp->p1];
69260 assert( memIsValid(u.cl.pQuery) );
69261 REGISTER_TRACE(pOp->p3, u.cl.pQuery);
69262 assert( u.cl.pCur->pVtabCursor );
69263 u.cl.pVtabCursor = u.cl.pCur->pVtabCursor;
69264 u.cl.pVtab = u.cl.pVtabCursor->pVtab;
69265 u.cl.pModule = u.cl.pVtab->pModule;
69267 /* Grab the index number and argc parameters */
69268 assert( (u.cl.pQuery->flags&MEM_Int)!=0 && u.cl.pArgc->flags==MEM_Int );
69269 u.cl.nArg = (int)u.cl.pArgc->u.i;
69270 u.cl.iQuery = (int)u.cl.pQuery->u.i;
69272 /* Invoke the xFilter method */
69274 u.cl.res = 0;
69275 u.cl.apArg = p->apArg;
69276 for(u.cl.i = 0; u.cl.i<u.cl.nArg; u.cl.i++){
69277 u.cl.apArg[u.cl.i] = &u.cl.pArgc[u.cl.i+1];
69278 sqlite3VdbeMemStoreType(u.cl.apArg[u.cl.i]);
69281 p->inVtabMethod = 1;
69282 rc = u.cl.pModule->xFilter(u.cl.pVtabCursor, u.cl.iQuery, pOp->p4.z, u.cl.nArg, u.cl.apArg);
69283 p->inVtabMethod = 0;
69284 importVtabErrMsg(p, u.cl.pVtab);
69285 if( rc==SQLITE_OK ){
69286 u.cl.res = u.cl.pModule->xEof(u.cl.pVtabCursor);
69289 if( u.cl.res ){
69290 pc = pOp->p2 - 1;
69293 u.cl.pCur->nullRow = 0;
69295 break;
69297 #endif /* SQLITE_OMIT_VIRTUALTABLE */
69299 #ifndef SQLITE_OMIT_VIRTUALTABLE
69300 /* Opcode: VColumn P1 P2 P3 * *
69302 ** Store the value of the P2-th column of
69303 ** the row of the virtual-table that the
69304 ** P1 cursor is pointing to into register P3.
69306 case OP_VColumn: {
69307 #if 0 /* local variables moved into u.cm */
69308 sqlite3_vtab *pVtab;
69309 const sqlite3_module *pModule;
69310 Mem *pDest;
69311 sqlite3_context sContext;
69312 #endif /* local variables moved into u.cm */
69314 VdbeCursor *pCur = p->apCsr[pOp->p1];
69315 assert( pCur->pVtabCursor );
69316 assert( pOp->p3>0 && pOp->p3<=p->nMem );
69317 u.cm.pDest = &aMem[pOp->p3];
69318 memAboutToChange(p, u.cm.pDest);
69319 if( pCur->nullRow ){
69320 sqlite3VdbeMemSetNull(u.cm.pDest);
69321 break;
69323 u.cm.pVtab = pCur->pVtabCursor->pVtab;
69324 u.cm.pModule = u.cm.pVtab->pModule;
69325 assert( u.cm.pModule->xColumn );
69326 memset(&u.cm.sContext, 0, sizeof(u.cm.sContext));
69328 /* The output cell may already have a buffer allocated. Move
69329 ** the current contents to u.cm.sContext.s so in case the user-function
69330 ** can use the already allocated buffer instead of allocating a
69331 ** new one.
69333 sqlite3VdbeMemMove(&u.cm.sContext.s, u.cm.pDest);
69334 MemSetTypeFlag(&u.cm.sContext.s, MEM_Null);
69336 rc = u.cm.pModule->xColumn(pCur->pVtabCursor, &u.cm.sContext, pOp->p2);
69337 importVtabErrMsg(p, u.cm.pVtab);
69338 if( u.cm.sContext.isError ){
69339 rc = u.cm.sContext.isError;
69342 /* Copy the result of the function to the P3 register. We
69343 ** do this regardless of whether or not an error occurred to ensure any
69344 ** dynamic allocation in u.cm.sContext.s (a Mem struct) is released.
69346 sqlite3VdbeChangeEncoding(&u.cm.sContext.s, encoding);
69347 sqlite3VdbeMemMove(u.cm.pDest, &u.cm.sContext.s);
69348 REGISTER_TRACE(pOp->p3, u.cm.pDest);
69349 UPDATE_MAX_BLOBSIZE(u.cm.pDest);
69351 if( sqlite3VdbeMemTooBig(u.cm.pDest) ){
69352 goto too_big;
69354 break;
69356 #endif /* SQLITE_OMIT_VIRTUALTABLE */
69358 #ifndef SQLITE_OMIT_VIRTUALTABLE
69359 /* Opcode: VNext P1 P2 * * *
69361 ** Advance virtual table P1 to the next row in its result set and
69362 ** jump to instruction P2. Or, if the virtual table has reached
69363 ** the end of its result set, then fall through to the next instruction.
69365 case OP_VNext: { /* jump */
69366 #if 0 /* local variables moved into u.cn */
69367 sqlite3_vtab *pVtab;
69368 const sqlite3_module *pModule;
69369 int res;
69370 VdbeCursor *pCur;
69371 #endif /* local variables moved into u.cn */
69373 u.cn.res = 0;
69374 u.cn.pCur = p->apCsr[pOp->p1];
69375 assert( u.cn.pCur->pVtabCursor );
69376 if( u.cn.pCur->nullRow ){
69377 break;
69379 u.cn.pVtab = u.cn.pCur->pVtabCursor->pVtab;
69380 u.cn.pModule = u.cn.pVtab->pModule;
69381 assert( u.cn.pModule->xNext );
69383 /* Invoke the xNext() method of the module. There is no way for the
69384 ** underlying implementation to return an error if one occurs during
69385 ** xNext(). Instead, if an error occurs, true is returned (indicating that
69386 ** data is available) and the error code returned when xColumn or
69387 ** some other method is next invoked on the save virtual table cursor.
69389 p->inVtabMethod = 1;
69390 rc = u.cn.pModule->xNext(u.cn.pCur->pVtabCursor);
69391 p->inVtabMethod = 0;
69392 importVtabErrMsg(p, u.cn.pVtab);
69393 if( rc==SQLITE_OK ){
69394 u.cn.res = u.cn.pModule->xEof(u.cn.pCur->pVtabCursor);
69397 if( !u.cn.res ){
69398 /* If there is data, jump to P2 */
69399 pc = pOp->p2 - 1;
69401 break;
69403 #endif /* SQLITE_OMIT_VIRTUALTABLE */
69405 #ifndef SQLITE_OMIT_VIRTUALTABLE
69406 /* Opcode: VRename P1 * * P4 *
69408 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
69409 ** This opcode invokes the corresponding xRename method. The value
69410 ** in register P1 is passed as the zName argument to the xRename method.
69412 case OP_VRename: {
69413 #if 0 /* local variables moved into u.co */
69414 sqlite3_vtab *pVtab;
69415 Mem *pName;
69416 #endif /* local variables moved into u.co */
69418 u.co.pVtab = pOp->p4.pVtab->pVtab;
69419 u.co.pName = &aMem[pOp->p1];
69420 assert( u.co.pVtab->pModule->xRename );
69421 assert( memIsValid(u.co.pName) );
69422 REGISTER_TRACE(pOp->p1, u.co.pName);
69423 assert( u.co.pName->flags & MEM_Str );
69424 testcase( u.co.pName->enc==SQLITE_UTF8 );
69425 testcase( u.co.pName->enc==SQLITE_UTF16BE );
69426 testcase( u.co.pName->enc==SQLITE_UTF16LE );
69427 rc = sqlite3VdbeChangeEncoding(u.co.pName, SQLITE_UTF8);
69428 if( rc==SQLITE_OK ){
69429 rc = u.co.pVtab->pModule->xRename(u.co.pVtab, u.co.pName->z);
69430 importVtabErrMsg(p, u.co.pVtab);
69431 p->expired = 0;
69433 break;
69435 #endif
69437 #ifndef SQLITE_OMIT_VIRTUALTABLE
69438 /* Opcode: VUpdate P1 P2 P3 P4 *
69440 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
69441 ** This opcode invokes the corresponding xUpdate method. P2 values
69442 ** are contiguous memory cells starting at P3 to pass to the xUpdate
69443 ** invocation. The value in register (P3+P2-1) corresponds to the
69444 ** p2th element of the argv array passed to xUpdate.
69446 ** The xUpdate method will do a DELETE or an INSERT or both.
69447 ** The argv[0] element (which corresponds to memory cell P3)
69448 ** is the rowid of a row to delete. If argv[0] is NULL then no
69449 ** deletion occurs. The argv[1] element is the rowid of the new
69450 ** row. This can be NULL to have the virtual table select the new
69451 ** rowid for itself. The subsequent elements in the array are
69452 ** the values of columns in the new row.
69454 ** If P2==1 then no insert is performed. argv[0] is the rowid of
69455 ** a row to delete.
69457 ** P1 is a boolean flag. If it is set to true and the xUpdate call
69458 ** is successful, then the value returned by sqlite3_last_insert_rowid()
69459 ** is set to the value of the rowid for the row just inserted.
69461 case OP_VUpdate: {
69462 #if 0 /* local variables moved into u.cp */
69463 sqlite3_vtab *pVtab;
69464 sqlite3_module *pModule;
69465 int nArg;
69466 int i;
69467 sqlite_int64 rowid;
69468 Mem **apArg;
69469 Mem *pX;
69470 #endif /* local variables moved into u.cp */
69472 assert( pOp->p2==1 || pOp->p5==OE_Fail || pOp->p5==OE_Rollback
69473 || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
69475 u.cp.pVtab = pOp->p4.pVtab->pVtab;
69476 u.cp.pModule = (sqlite3_module *)u.cp.pVtab->pModule;
69477 u.cp.nArg = pOp->p2;
69478 assert( pOp->p4type==P4_VTAB );
69479 if( ALWAYS(u.cp.pModule->xUpdate) ){
69480 u8 vtabOnConflict = db->vtabOnConflict;
69481 u.cp.apArg = p->apArg;
69482 u.cp.pX = &aMem[pOp->p3];
69483 for(u.cp.i=0; u.cp.i<u.cp.nArg; u.cp.i++){
69484 assert( memIsValid(u.cp.pX) );
69485 memAboutToChange(p, u.cp.pX);
69486 sqlite3VdbeMemStoreType(u.cp.pX);
69487 u.cp.apArg[u.cp.i] = u.cp.pX;
69488 u.cp.pX++;
69490 db->vtabOnConflict = pOp->p5;
69491 rc = u.cp.pModule->xUpdate(u.cp.pVtab, u.cp.nArg, u.cp.apArg, &u.cp.rowid);
69492 db->vtabOnConflict = vtabOnConflict;
69493 importVtabErrMsg(p, u.cp.pVtab);
69494 if( rc==SQLITE_OK && pOp->p1 ){
69495 assert( u.cp.nArg>1 && u.cp.apArg[0] && (u.cp.apArg[0]->flags&MEM_Null) );
69496 db->lastRowid = lastRowid = u.cp.rowid;
69498 if( rc==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
69499 if( pOp->p5==OE_Ignore ){
69500 rc = SQLITE_OK;
69501 }else{
69502 p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
69504 }else{
69505 p->nChange++;
69508 break;
69510 #endif /* SQLITE_OMIT_VIRTUALTABLE */
69512 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
69513 /* Opcode: Pagecount P1 P2 * * *
69515 ** Write the current number of pages in database P1 to memory cell P2.
69517 case OP_Pagecount: { /* out2-prerelease */
69518 pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
69519 break;
69521 #endif
69524 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
69525 /* Opcode: MaxPgcnt P1 P2 P3 * *
69527 ** Try to set the maximum page count for database P1 to the value in P3.
69528 ** Do not let the maximum page count fall below the current page count and
69529 ** do not change the maximum page count value if P3==0.
69531 ** Store the maximum page count after the change in register P2.
69533 case OP_MaxPgcnt: { /* out2-prerelease */
69534 unsigned int newMax;
69535 Btree *pBt;
69537 pBt = db->aDb[pOp->p1].pBt;
69538 newMax = 0;
69539 if( pOp->p3 ){
69540 newMax = sqlite3BtreeLastPage(pBt);
69541 if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
69543 pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
69544 break;
69546 #endif
69549 #ifndef SQLITE_OMIT_TRACE
69550 /* Opcode: Trace * * * P4 *
69552 ** If tracing is enabled (by the sqlite3_trace()) interface, then
69553 ** the UTF-8 string contained in P4 is emitted on the trace callback.
69555 case OP_Trace: {
69556 #if 0 /* local variables moved into u.cq */
69557 char *zTrace;
69558 char *z;
69559 #endif /* local variables moved into u.cq */
69561 if( db->xTrace && (u.cq.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0 ){
69562 u.cq.z = sqlite3VdbeExpandSql(p, u.cq.zTrace);
69563 db->xTrace(db->pTraceArg, u.cq.z);
69564 sqlite3DbFree(db, u.cq.z);
69566 #ifdef SQLITE_DEBUG
69567 if( (db->flags & SQLITE_SqlTrace)!=0
69568 && (u.cq.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
69570 sqlite3DebugPrintf("SQL-trace: %s\n", u.cq.zTrace);
69572 #endif /* SQLITE_DEBUG */
69573 break;
69575 #endif
69578 /* Opcode: Noop * * * * *
69580 ** Do nothing. This instruction is often useful as a jump
69581 ** destination.
69584 ** The magic Explain opcode are only inserted when explain==2 (which
69585 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
69586 ** This opcode records information from the optimizer. It is the
69587 ** the same as a no-op. This opcodesnever appears in a real VM program.
69589 default: { /* This is really OP_Noop and OP_Explain */
69590 assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
69591 break;
69594 /*****************************************************************************
69595 ** The cases of the switch statement above this line should all be indented
69596 ** by 6 spaces. But the left-most 6 spaces have been removed to improve the
69597 ** readability. From this point on down, the normal indentation rules are
69598 ** restored.
69599 *****************************************************************************/
69602 #ifdef VDBE_PROFILE
69604 u64 elapsed = sqlite3Hwtime() - start;
69605 pOp->cycles += elapsed;
69606 pOp->cnt++;
69607 #if 0
69608 fprintf(stdout, "%10llu ", elapsed);
69609 sqlite3VdbePrintOp(stdout, origPc, &aOp[origPc]);
69610 #endif
69612 #endif
69614 /* The following code adds nothing to the actual functionality
69615 ** of the program. It is only here for testing and debugging.
69616 ** On the other hand, it does burn CPU cycles every time through
69617 ** the evaluator loop. So we can leave it out when NDEBUG is defined.
69619 #ifndef NDEBUG
69620 assert( pc>=-1 && pc<p->nOp );
69622 #ifdef SQLITE_DEBUG
69623 if( p->trace ){
69624 if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc);
69625 if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){
69626 registerTrace(p->trace, pOp->p2, &aMem[pOp->p2]);
69628 if( pOp->opflags & OPFLG_OUT3 ){
69629 registerTrace(p->trace, pOp->p3, &aMem[pOp->p3]);
69632 #endif /* SQLITE_DEBUG */
69633 #endif /* NDEBUG */
69634 } /* The end of the for(;;) loop the loops through opcodes */
69636 /* If we reach this point, it means that execution is finished with
69637 ** an error of some kind.
69639 vdbe_error_halt:
69640 assert( rc );
69641 p->rc = rc;
69642 testcase( sqlite3GlobalConfig.xLog!=0 );
69643 sqlite3_log(rc, "statement aborts at %d: [%s] %s",
69644 pc, p->zSql, p->zErrMsg);
69645 sqlite3VdbeHalt(p);
69646 if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
69647 rc = SQLITE_ERROR;
69648 if( resetSchemaOnFault>0 ){
69649 sqlite3ResetInternalSchema(db, resetSchemaOnFault-1);
69652 /* This is the only way out of this procedure. We have to
69653 ** release the mutexes on btrees that were acquired at the
69654 ** top. */
69655 vdbe_return:
69656 db->lastRowid = lastRowid;
69657 sqlite3VdbeLeave(p);
69658 return rc;
69660 /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
69661 ** is encountered.
69663 too_big:
69664 sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
69665 rc = SQLITE_TOOBIG;
69666 goto vdbe_error_halt;
69668 /* Jump to here if a malloc() fails.
69670 no_mem:
69671 db->mallocFailed = 1;
69672 sqlite3SetString(&p->zErrMsg, db, "out of memory");
69673 rc = SQLITE_NOMEM;
69674 goto vdbe_error_halt;
69676 /* Jump to here for any other kind of fatal error. The "rc" variable
69677 ** should hold the error number.
69679 abort_due_to_error:
69680 assert( p->zErrMsg==0 );
69681 if( db->mallocFailed ) rc = SQLITE_NOMEM;
69682 if( rc!=SQLITE_IOERR_NOMEM ){
69683 sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
69685 goto vdbe_error_halt;
69687 /* Jump to here if the sqlite3_interrupt() API sets the interrupt
69688 ** flag.
69690 abort_due_to_interrupt:
69691 assert( db->u1.isInterrupted );
69692 rc = SQLITE_INTERRUPT;
69693 p->rc = rc;
69694 sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
69695 goto vdbe_error_halt;
69698 /************** End of vdbe.c ************************************************/
69699 /************** Begin file vdbeblob.c ****************************************/
69701 ** 2007 May 1
69703 ** The author disclaims copyright to this source code. In place of
69704 ** a legal notice, here is a blessing:
69706 ** May you do good and not evil.
69707 ** May you find forgiveness for yourself and forgive others.
69708 ** May you share freely, never taking more than you give.
69710 *************************************************************************
69712 ** This file contains code used to implement incremental BLOB I/O.
69716 #ifndef SQLITE_OMIT_INCRBLOB
69719 ** Valid sqlite3_blob* handles point to Incrblob structures.
69721 typedef struct Incrblob Incrblob;
69722 struct Incrblob {
69723 int flags; /* Copy of "flags" passed to sqlite3_blob_open() */
69724 int nByte; /* Size of open blob, in bytes */
69725 int iOffset; /* Byte offset of blob in cursor data */
69726 int iCol; /* Table column this handle is open on */
69727 BtCursor *pCsr; /* Cursor pointing at blob row */
69728 sqlite3_stmt *pStmt; /* Statement holding cursor open */
69729 sqlite3 *db; /* The associated database */
69734 ** This function is used by both blob_open() and blob_reopen(). It seeks
69735 ** the b-tree cursor associated with blob handle p to point to row iRow.
69736 ** If successful, SQLITE_OK is returned and subsequent calls to
69737 ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
69739 ** If an error occurs, or if the specified row does not exist or does not
69740 ** contain a value of type TEXT or BLOB in the column nominated when the
69741 ** blob handle was opened, then an error code is returned and *pzErr may
69742 ** be set to point to a buffer containing an error message. It is the
69743 ** responsibility of the caller to free the error message buffer using
69744 ** sqlite3DbFree().
69746 ** If an error does occur, then the b-tree cursor is closed. All subsequent
69747 ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
69748 ** immediately return SQLITE_ABORT.
69750 static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
69751 int rc; /* Error code */
69752 char *zErr = 0; /* Error message */
69753 Vdbe *v = (Vdbe *)p->pStmt;
69755 /* Set the value of the SQL statements only variable to integer iRow.
69756 ** This is done directly instead of using sqlite3_bind_int64() to avoid
69757 ** triggering asserts related to mutexes.
69759 assert( v->aVar[0].flags&MEM_Int );
69760 v->aVar[0].u.i = iRow;
69762 rc = sqlite3_step(p->pStmt);
69763 if( rc==SQLITE_ROW ){
69764 u32 type = v->apCsr[0]->aType[p->iCol];
69765 if( type<12 ){
69766 zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
69767 type==0?"null": type==7?"real": "integer"
69769 rc = SQLITE_ERROR;
69770 sqlite3_finalize(p->pStmt);
69771 p->pStmt = 0;
69772 }else{
69773 p->iOffset = v->apCsr[0]->aOffset[p->iCol];
69774 p->nByte = sqlite3VdbeSerialTypeLen(type);
69775 p->pCsr = v->apCsr[0]->pCursor;
69776 sqlite3BtreeEnterCursor(p->pCsr);
69777 sqlite3BtreeCacheOverflow(p->pCsr);
69778 sqlite3BtreeLeaveCursor(p->pCsr);
69782 if( rc==SQLITE_ROW ){
69783 rc = SQLITE_OK;
69784 }else if( p->pStmt ){
69785 rc = sqlite3_finalize(p->pStmt);
69786 p->pStmt = 0;
69787 if( rc==SQLITE_OK ){
69788 zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
69789 rc = SQLITE_ERROR;
69790 }else{
69791 zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
69795 assert( rc!=SQLITE_OK || zErr==0 );
69796 assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
69798 *pzErr = zErr;
69799 return rc;
69803 ** Open a blob handle.
69805 SQLITE_API int sqlite3_blob_open(
69806 sqlite3* db, /* The database connection */
69807 const char *zDb, /* The attached database containing the blob */
69808 const char *zTable, /* The table containing the blob */
69809 const char *zColumn, /* The column containing the blob */
69810 sqlite_int64 iRow, /* The row containing the glob */
69811 int flags, /* True -> read/write access, false -> read-only */
69812 sqlite3_blob **ppBlob /* Handle for accessing the blob returned here */
69814 int nAttempt = 0;
69815 int iCol; /* Index of zColumn in row-record */
69817 /* This VDBE program seeks a btree cursor to the identified
69818 ** db/table/row entry. The reason for using a vdbe program instead
69819 ** of writing code to use the b-tree layer directly is that the
69820 ** vdbe program will take advantage of the various transaction,
69821 ** locking and error handling infrastructure built into the vdbe.
69823 ** After seeking the cursor, the vdbe executes an OP_ResultRow.
69824 ** Code external to the Vdbe then "borrows" the b-tree cursor and
69825 ** uses it to implement the blob_read(), blob_write() and
69826 ** blob_bytes() functions.
69828 ** The sqlite3_blob_close() function finalizes the vdbe program,
69829 ** which closes the b-tree cursor and (possibly) commits the
69830 ** transaction.
69832 static const VdbeOpList openBlob[] = {
69833 {OP_Transaction, 0, 0, 0}, /* 0: Start a transaction */
69834 {OP_VerifyCookie, 0, 0, 0}, /* 1: Check the schema cookie */
69835 {OP_TableLock, 0, 0, 0}, /* 2: Acquire a read or write lock */
69837 /* One of the following two instructions is replaced by an OP_Noop. */
69838 {OP_OpenRead, 0, 0, 0}, /* 3: Open cursor 0 for reading */
69839 {OP_OpenWrite, 0, 0, 0}, /* 4: Open cursor 0 for read/write */
69841 {OP_Variable, 1, 1, 1}, /* 5: Push the rowid to the stack */
69842 {OP_NotExists, 0, 10, 1}, /* 6: Seek the cursor */
69843 {OP_Column, 0, 0, 1}, /* 7 */
69844 {OP_ResultRow, 1, 0, 0}, /* 8 */
69845 {OP_Goto, 0, 5, 0}, /* 9 */
69846 {OP_Close, 0, 0, 0}, /* 10 */
69847 {OP_Halt, 0, 0, 0}, /* 11 */
69850 int rc = SQLITE_OK;
69851 char *zErr = 0;
69852 Table *pTab;
69853 Parse *pParse = 0;
69854 Incrblob *pBlob = 0;
69856 flags = !!flags; /* flags = (flags ? 1 : 0); */
69857 *ppBlob = 0;
69859 sqlite3_mutex_enter(db->mutex);
69861 pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
69862 if( !pBlob ) goto blob_open_out;
69863 pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
69864 if( !pParse ) goto blob_open_out;
69866 do {
69867 memset(pParse, 0, sizeof(Parse));
69868 pParse->db = db;
69869 sqlite3DbFree(db, zErr);
69870 zErr = 0;
69872 sqlite3BtreeEnterAll(db);
69873 pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
69874 if( pTab && IsVirtual(pTab) ){
69875 pTab = 0;
69876 sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
69878 #ifndef SQLITE_OMIT_VIEW
69879 if( pTab && pTab->pSelect ){
69880 pTab = 0;
69881 sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
69883 #endif
69884 if( !pTab ){
69885 if( pParse->zErrMsg ){
69886 sqlite3DbFree(db, zErr);
69887 zErr = pParse->zErrMsg;
69888 pParse->zErrMsg = 0;
69890 rc = SQLITE_ERROR;
69891 sqlite3BtreeLeaveAll(db);
69892 goto blob_open_out;
69895 /* Now search pTab for the exact column. */
69896 for(iCol=0; iCol<pTab->nCol; iCol++) {
69897 if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
69898 break;
69901 if( iCol==pTab->nCol ){
69902 sqlite3DbFree(db, zErr);
69903 zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
69904 rc = SQLITE_ERROR;
69905 sqlite3BtreeLeaveAll(db);
69906 goto blob_open_out;
69909 /* If the value is being opened for writing, check that the
69910 ** column is not indexed, and that it is not part of a foreign key.
69911 ** It is against the rules to open a column to which either of these
69912 ** descriptions applies for writing. */
69913 if( flags ){
69914 const char *zFault = 0;
69915 Index *pIdx;
69916 #ifndef SQLITE_OMIT_FOREIGN_KEY
69917 if( db->flags&SQLITE_ForeignKeys ){
69918 /* Check that the column is not part of an FK child key definition. It
69919 ** is not necessary to check if it is part of a parent key, as parent
69920 ** key columns must be indexed. The check below will pick up this
69921 ** case. */
69922 FKey *pFKey;
69923 for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
69924 int j;
69925 for(j=0; j<pFKey->nCol; j++){
69926 if( pFKey->aCol[j].iFrom==iCol ){
69927 zFault = "foreign key";
69932 #endif
69933 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
69934 int j;
69935 for(j=0; j<pIdx->nColumn; j++){
69936 if( pIdx->aiColumn[j]==iCol ){
69937 zFault = "indexed";
69941 if( zFault ){
69942 sqlite3DbFree(db, zErr);
69943 zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
69944 rc = SQLITE_ERROR;
69945 sqlite3BtreeLeaveAll(db);
69946 goto blob_open_out;
69950 pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(db);
69951 assert( pBlob->pStmt || db->mallocFailed );
69952 if( pBlob->pStmt ){
69953 Vdbe *v = (Vdbe *)pBlob->pStmt;
69954 int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
69956 sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
69959 /* Configure the OP_Transaction */
69960 sqlite3VdbeChangeP1(v, 0, iDb);
69961 sqlite3VdbeChangeP2(v, 0, flags);
69963 /* Configure the OP_VerifyCookie */
69964 sqlite3VdbeChangeP1(v, 1, iDb);
69965 sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
69966 sqlite3VdbeChangeP3(v, 1, pTab->pSchema->iGeneration);
69968 /* Make sure a mutex is held on the table to be accessed */
69969 sqlite3VdbeUsesBtree(v, iDb);
69971 /* Configure the OP_TableLock instruction */
69972 #ifdef SQLITE_OMIT_SHARED_CACHE
69973 sqlite3VdbeChangeToNoop(v, 2);
69974 #else
69975 sqlite3VdbeChangeP1(v, 2, iDb);
69976 sqlite3VdbeChangeP2(v, 2, pTab->tnum);
69977 sqlite3VdbeChangeP3(v, 2, flags);
69978 sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
69979 #endif
69981 /* Remove either the OP_OpenWrite or OpenRead. Set the P2
69982 ** parameter of the other to pTab->tnum. */
69983 sqlite3VdbeChangeToNoop(v, 4 - flags);
69984 sqlite3VdbeChangeP2(v, 3 + flags, pTab->tnum);
69985 sqlite3VdbeChangeP3(v, 3 + flags, iDb);
69987 /* Configure the number of columns. Configure the cursor to
69988 ** think that the table has one more column than it really
69989 ** does. An OP_Column to retrieve this imaginary column will
69990 ** always return an SQL NULL. This is useful because it means
69991 ** we can invoke OP_Column to fill in the vdbe cursors type
69992 ** and offset cache without causing any IO.
69994 sqlite3VdbeChangeP4(v, 3+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
69995 sqlite3VdbeChangeP2(v, 7, pTab->nCol);
69996 if( !db->mallocFailed ){
69997 pParse->nVar = 1;
69998 pParse->nMem = 1;
69999 pParse->nTab = 1;
70000 sqlite3VdbeMakeReady(v, pParse);
70004 pBlob->flags = flags;
70005 pBlob->iCol = iCol;
70006 pBlob->db = db;
70007 sqlite3BtreeLeaveAll(db);
70008 if( db->mallocFailed ){
70009 goto blob_open_out;
70011 sqlite3_bind_int64(pBlob->pStmt, 1, iRow);
70012 rc = blobSeekToRow(pBlob, iRow, &zErr);
70013 } while( (++nAttempt)<5 && rc==SQLITE_SCHEMA );
70015 blob_open_out:
70016 if( rc==SQLITE_OK && db->mallocFailed==0 ){
70017 *ppBlob = (sqlite3_blob *)pBlob;
70018 }else{
70019 if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
70020 sqlite3DbFree(db, pBlob);
70022 sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
70023 sqlite3DbFree(db, zErr);
70024 sqlite3StackFree(db, pParse);
70025 rc = sqlite3ApiExit(db, rc);
70026 sqlite3_mutex_leave(db->mutex);
70027 return rc;
70031 ** Close a blob handle that was previously created using
70032 ** sqlite3_blob_open().
70034 SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
70035 Incrblob *p = (Incrblob *)pBlob;
70036 int rc;
70037 sqlite3 *db;
70039 if( p ){
70040 db = p->db;
70041 sqlite3_mutex_enter(db->mutex);
70042 rc = sqlite3_finalize(p->pStmt);
70043 sqlite3DbFree(db, p);
70044 sqlite3_mutex_leave(db->mutex);
70045 }else{
70046 rc = SQLITE_OK;
70048 return rc;
70052 ** Perform a read or write operation on a blob
70054 static int blobReadWrite(
70055 sqlite3_blob *pBlob,
70056 void *z,
70057 int n,
70058 int iOffset,
70059 int (*xCall)(BtCursor*, u32, u32, void*)
70061 int rc;
70062 Incrblob *p = (Incrblob *)pBlob;
70063 Vdbe *v;
70064 sqlite3 *db;
70066 if( p==0 ) return SQLITE_MISUSE_BKPT;
70067 db = p->db;
70068 sqlite3_mutex_enter(db->mutex);
70069 v = (Vdbe*)p->pStmt;
70071 if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
70072 /* Request is out of range. Return a transient error. */
70073 rc = SQLITE_ERROR;
70074 sqlite3Error(db, SQLITE_ERROR, 0);
70075 }else if( v==0 ){
70076 /* If there is no statement handle, then the blob-handle has
70077 ** already been invalidated. Return SQLITE_ABORT in this case.
70079 rc = SQLITE_ABORT;
70080 }else{
70081 /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
70082 ** returned, clean-up the statement handle.
70084 assert( db == v->db );
70085 sqlite3BtreeEnterCursor(p->pCsr);
70086 rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
70087 sqlite3BtreeLeaveCursor(p->pCsr);
70088 if( rc==SQLITE_ABORT ){
70089 sqlite3VdbeFinalize(v);
70090 p->pStmt = 0;
70091 }else{
70092 db->errCode = rc;
70093 v->rc = rc;
70096 rc = sqlite3ApiExit(db, rc);
70097 sqlite3_mutex_leave(db->mutex);
70098 return rc;
70102 ** Read data from a blob handle.
70104 SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
70105 return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
70109 ** Write data to a blob handle.
70111 SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
70112 return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
70116 ** Query a blob handle for the size of the data.
70118 ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
70119 ** so no mutex is required for access.
70121 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
70122 Incrblob *p = (Incrblob *)pBlob;
70123 return (p && p->pStmt) ? p->nByte : 0;
70127 ** Move an existing blob handle to point to a different row of the same
70128 ** database table.
70130 ** If an error occurs, or if the specified row does not exist or does not
70131 ** contain a blob or text value, then an error code is returned and the
70132 ** database handle error code and message set. If this happens, then all
70133 ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
70134 ** immediately return SQLITE_ABORT.
70136 SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
70137 int rc;
70138 Incrblob *p = (Incrblob *)pBlob;
70139 sqlite3 *db;
70141 if( p==0 ) return SQLITE_MISUSE_BKPT;
70142 db = p->db;
70143 sqlite3_mutex_enter(db->mutex);
70145 if( p->pStmt==0 ){
70146 /* If there is no statement handle, then the blob-handle has
70147 ** already been invalidated. Return SQLITE_ABORT in this case.
70149 rc = SQLITE_ABORT;
70150 }else{
70151 char *zErr;
70152 rc = blobSeekToRow(p, iRow, &zErr);
70153 if( rc!=SQLITE_OK ){
70154 sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
70155 sqlite3DbFree(db, zErr);
70157 assert( rc!=SQLITE_SCHEMA );
70160 rc = sqlite3ApiExit(db, rc);
70161 assert( rc==SQLITE_OK || p->pStmt==0 );
70162 sqlite3_mutex_leave(db->mutex);
70163 return rc;
70166 #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
70168 /************** End of vdbeblob.c ********************************************/
70169 /************** Begin file vdbesort.c ****************************************/
70171 ** 2011 July 9
70173 ** The author disclaims copyright to this source code. In place of
70174 ** a legal notice, here is a blessing:
70176 ** May you do good and not evil.
70177 ** May you find forgiveness for yourself and forgive others.
70178 ** May you share freely, never taking more than you give.
70180 *************************************************************************
70181 ** This file contains code for the VdbeSorter object, used in concert with
70182 ** a VdbeCursor to sort large numbers of keys (as may be required, for
70183 ** example, by CREATE INDEX statements on tables too large to fit in main
70184 ** memory).
70188 #ifndef SQLITE_OMIT_MERGE_SORT
70190 typedef struct VdbeSorterIter VdbeSorterIter;
70191 typedef struct SorterRecord SorterRecord;
70194 ** NOTES ON DATA STRUCTURE USED FOR N-WAY MERGES:
70196 ** As keys are added to the sorter, they are written to disk in a series
70197 ** of sorted packed-memory-arrays (PMAs). The size of each PMA is roughly
70198 ** the same as the cache-size allowed for temporary databases. In order
70199 ** to allow the caller to extract keys from the sorter in sorted order,
70200 ** all PMAs currently stored on disk must be merged together. This comment
70201 ** describes the data structure used to do so. The structure supports
70202 ** merging any number of arrays in a single pass with no redundant comparison
70203 ** operations.
70205 ** The aIter[] array contains an iterator for each of the PMAs being merged.
70206 ** An aIter[] iterator either points to a valid key or else is at EOF. For
70207 ** the purposes of the paragraphs below, we assume that the array is actually
70208 ** N elements in size, where N is the smallest power of 2 greater to or equal
70209 ** to the number of iterators being merged. The extra aIter[] elements are
70210 ** treated as if they are empty (always at EOF).
70212 ** The aTree[] array is also N elements in size. The value of N is stored in
70213 ** the VdbeSorter.nTree variable.
70215 ** The final (N/2) elements of aTree[] contain the results of comparing
70216 ** pairs of iterator keys together. Element i contains the result of
70217 ** comparing aIter[2*i-N] and aIter[2*i-N+1]. Whichever key is smaller, the
70218 ** aTree element is set to the index of it.
70220 ** For the purposes of this comparison, EOF is considered greater than any
70221 ** other key value. If the keys are equal (only possible with two EOF
70222 ** values), it doesn't matter which index is stored.
70224 ** The (N/4) elements of aTree[] that preceed the final (N/2) described
70225 ** above contains the index of the smallest of each block of 4 iterators.
70226 ** And so on. So that aTree[1] contains the index of the iterator that
70227 ** currently points to the smallest key value. aTree[0] is unused.
70229 ** Example:
70231 ** aIter[0] -> Banana
70232 ** aIter[1] -> Feijoa
70233 ** aIter[2] -> Elderberry
70234 ** aIter[3] -> Currant
70235 ** aIter[4] -> Grapefruit
70236 ** aIter[5] -> Apple
70237 ** aIter[6] -> Durian
70238 ** aIter[7] -> EOF
70240 ** aTree[] = { X, 5 0, 5 0, 3, 5, 6 }
70242 ** The current element is "Apple" (the value of the key indicated by
70243 ** iterator 5). When the Next() operation is invoked, iterator 5 will
70244 ** be advanced to the next key in its segment. Say the next key is
70245 ** "Eggplant":
70247 ** aIter[5] -> Eggplant
70249 ** The contents of aTree[] are updated first by comparing the new iterator
70250 ** 5 key to the current key of iterator 4 (still "Grapefruit"). The iterator
70251 ** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
70252 ** The value of iterator 6 - "Durian" - is now smaller than that of iterator
70253 ** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
70254 ** so the value written into element 1 of the array is 0. As follows:
70256 ** aTree[] = { X, 0 0, 6 0, 3, 5, 6 }
70258 ** In other words, each time we advance to the next sorter element, log2(N)
70259 ** key comparison operations are required, where N is the number of segments
70260 ** being merged (rounded up to the next power of 2).
70262 struct VdbeSorter {
70263 int nInMemory; /* Current size of pRecord list as PMA */
70264 int nTree; /* Used size of aTree/aIter (power of 2) */
70265 VdbeSorterIter *aIter; /* Array of iterators to merge */
70266 int *aTree; /* Current state of incremental merge */
70267 i64 iWriteOff; /* Current write offset within file pTemp1 */
70268 i64 iReadOff; /* Current read offset within file pTemp1 */
70269 sqlite3_file *pTemp1; /* PMA file 1 */
70270 int nPMA; /* Number of PMAs stored in pTemp1 */
70271 SorterRecord *pRecord; /* Head of in-memory record list */
70272 int mnPmaSize; /* Minimum PMA size, in bytes */
70273 int mxPmaSize; /* Maximum PMA size, in bytes. 0==no limit */
70274 UnpackedRecord *pUnpacked; /* Used to unpack keys */
70278 ** The following type is an iterator for a PMA. It caches the current key in
70279 ** variables nKey/aKey. If the iterator is at EOF, pFile==0.
70281 struct VdbeSorterIter {
70282 i64 iReadOff; /* Current read offset */
70283 i64 iEof; /* 1 byte past EOF for this iterator */
70284 sqlite3_file *pFile; /* File iterator is reading from */
70285 int nAlloc; /* Bytes of space at aAlloc */
70286 u8 *aAlloc; /* Allocated space */
70287 int nKey; /* Number of bytes in key */
70288 u8 *aKey; /* Pointer to current key */
70292 ** A structure to store a single record. All in-memory records are connected
70293 ** together into a linked list headed at VdbeSorter.pRecord using the
70294 ** SorterRecord.pNext pointer.
70296 struct SorterRecord {
70297 void *pVal;
70298 int nVal;
70299 SorterRecord *pNext;
70302 /* Minimum allowable value for the VdbeSorter.nWorking variable */
70303 #define SORTER_MIN_WORKING 10
70305 /* Maximum number of segments to merge in a single pass. */
70306 #define SORTER_MAX_MERGE_COUNT 16
70309 ** Free all memory belonging to the VdbeSorterIter object passed as the second
70310 ** argument. All structure fields are set to zero before returning.
70312 static void vdbeSorterIterZero(sqlite3 *db, VdbeSorterIter *pIter){
70313 sqlite3DbFree(db, pIter->aAlloc);
70314 memset(pIter, 0, sizeof(VdbeSorterIter));
70318 ** Advance iterator pIter to the next key in its PMA. Return SQLITE_OK if
70319 ** no error occurs, or an SQLite error code if one does.
70321 static int vdbeSorterIterNext(
70322 sqlite3 *db, /* Database handle (for sqlite3DbMalloc() ) */
70323 VdbeSorterIter *pIter /* Iterator to advance */
70325 int rc; /* Return Code */
70326 int nRead; /* Number of bytes read */
70327 int nRec = 0; /* Size of record in bytes */
70328 int iOff = 0; /* Size of serialized size varint in bytes */
70330 assert( pIter->iEof>=pIter->iReadOff );
70331 if( pIter->iEof-pIter->iReadOff>5 ){
70332 nRead = 5;
70333 }else{
70334 nRead = (int)(pIter->iEof - pIter->iReadOff);
70336 if( nRead<=0 ){
70337 /* This is an EOF condition */
70338 vdbeSorterIterZero(db, pIter);
70339 return SQLITE_OK;
70342 rc = sqlite3OsRead(pIter->pFile, pIter->aAlloc, nRead, pIter->iReadOff);
70343 if( rc==SQLITE_OK ){
70344 iOff = getVarint32(pIter->aAlloc, nRec);
70345 if( (iOff+nRec)>nRead ){
70346 int nRead2; /* Number of extra bytes to read */
70347 if( (iOff+nRec)>pIter->nAlloc ){
70348 int nNew = pIter->nAlloc*2;
70349 while( (iOff+nRec)>nNew ) nNew = nNew*2;
70350 pIter->aAlloc = sqlite3DbReallocOrFree(db, pIter->aAlloc, nNew);
70351 if( !pIter->aAlloc ) return SQLITE_NOMEM;
70352 pIter->nAlloc = nNew;
70355 nRead2 = iOff + nRec - nRead;
70356 rc = sqlite3OsRead(
70357 pIter->pFile, &pIter->aAlloc[nRead], nRead2, pIter->iReadOff+nRead
70362 assert( rc!=SQLITE_OK || nRec>0 );
70363 pIter->iReadOff += iOff+nRec;
70364 pIter->nKey = nRec;
70365 pIter->aKey = &pIter->aAlloc[iOff];
70366 return rc;
70370 ** Write a single varint, value iVal, to file-descriptor pFile. Return
70371 ** SQLITE_OK if successful, or an SQLite error code if some error occurs.
70373 ** The value of *piOffset when this function is called is used as the byte
70374 ** offset in file pFile to write to. Before returning, *piOffset is
70375 ** incremented by the number of bytes written.
70377 static int vdbeSorterWriteVarint(
70378 sqlite3_file *pFile, /* File to write to */
70379 i64 iVal, /* Value to write as a varint */
70380 i64 *piOffset /* IN/OUT: Write offset in file pFile */
70382 u8 aVarint[9]; /* Buffer large enough for a varint */
70383 int nVarint; /* Number of used bytes in varint */
70384 int rc; /* Result of write() call */
70386 nVarint = sqlite3PutVarint(aVarint, iVal);
70387 rc = sqlite3OsWrite(pFile, aVarint, nVarint, *piOffset);
70388 *piOffset += nVarint;
70390 return rc;
70394 ** Read a single varint from file-descriptor pFile. Return SQLITE_OK if
70395 ** successful, or an SQLite error code if some error occurs.
70397 ** The value of *piOffset when this function is called is used as the
70398 ** byte offset in file pFile from whence to read the varint. If successful
70399 ** (i.e. if no IO error occurs), then *piOffset is set to the offset of
70400 ** the first byte past the end of the varint before returning. *piVal is
70401 ** set to the integer value read. If an error occurs, the final values of
70402 ** both *piOffset and *piVal are undefined.
70404 static int vdbeSorterReadVarint(
70405 sqlite3_file *pFile, /* File to read from */
70406 i64 *piOffset, /* IN/OUT: Read offset in pFile */
70407 i64 *piVal /* OUT: Value read from file */
70409 u8 aVarint[9]; /* Buffer large enough for a varint */
70410 i64 iOff = *piOffset; /* Offset in file to read from */
70411 int rc; /* Return code */
70413 rc = sqlite3OsRead(pFile, aVarint, 9, iOff);
70414 if( rc==SQLITE_OK ){
70415 *piOffset += getVarint(aVarint, (u64 *)piVal);
70418 return rc;
70422 ** Initialize iterator pIter to scan through the PMA stored in file pFile
70423 ** starting at offset iStart and ending at offset iEof-1. This function
70424 ** leaves the iterator pointing to the first key in the PMA (or EOF if the
70425 ** PMA is empty).
70427 static int vdbeSorterIterInit(
70428 sqlite3 *db, /* Database handle */
70429 VdbeSorter *pSorter, /* Sorter object */
70430 i64 iStart, /* Start offset in pFile */
70431 VdbeSorterIter *pIter, /* Iterator to populate */
70432 i64 *pnByte /* IN/OUT: Increment this value by PMA size */
70434 int rc;
70436 assert( pSorter->iWriteOff>iStart );
70437 assert( pIter->aAlloc==0 );
70438 pIter->pFile = pSorter->pTemp1;
70439 pIter->iReadOff = iStart;
70440 pIter->nAlloc = 128;
70441 pIter->aAlloc = (u8 *)sqlite3DbMallocRaw(db, pIter->nAlloc);
70442 if( !pIter->aAlloc ){
70443 rc = SQLITE_NOMEM;
70444 }else{
70445 i64 nByte; /* Total size of PMA in bytes */
70446 rc = vdbeSorterReadVarint(pSorter->pTemp1, &pIter->iReadOff, &nByte);
70447 *pnByte += nByte;
70448 pIter->iEof = pIter->iReadOff + nByte;
70450 if( rc==SQLITE_OK ){
70451 rc = vdbeSorterIterNext(db, pIter);
70453 return rc;
70458 ** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2,
70459 ** size nKey2 bytes). Argument pKeyInfo supplies the collation functions
70460 ** used by the comparison. If an error occurs, return an SQLite error code.
70461 ** Otherwise, return SQLITE_OK and set *pRes to a negative, zero or positive
70462 ** value, depending on whether key1 is smaller, equal to or larger than key2.
70464 ** If the bOmitRowid argument is non-zero, assume both keys end in a rowid
70465 ** field. For the purposes of the comparison, ignore it. Also, if bOmitRowid
70466 ** is true and key1 contains even a single NULL value, it is considered to
70467 ** be less than key2. Even if key2 also contains NULL values.
70469 ** If pKey2 is passed a NULL pointer, then it is assumed that the pCsr->aSpace
70470 ** has been allocated and contains an unpacked record that is used as key2.
70472 static void vdbeSorterCompare(
70473 VdbeCursor *pCsr, /* Cursor object (for pKeyInfo) */
70474 int bOmitRowid, /* Ignore rowid field at end of keys */
70475 void *pKey1, int nKey1, /* Left side of comparison */
70476 void *pKey2, int nKey2, /* Right side of comparison */
70477 int *pRes /* OUT: Result of comparison */
70479 KeyInfo *pKeyInfo = pCsr->pKeyInfo;
70480 VdbeSorter *pSorter = pCsr->pSorter;
70481 UnpackedRecord *r2 = pSorter->pUnpacked;
70482 int i;
70484 if( pKey2 ){
70485 sqlite3VdbeRecordUnpack(pKeyInfo, nKey2, pKey2, r2);
70488 if( bOmitRowid ){
70489 r2->nField = pKeyInfo->nField;
70490 assert( r2->nField>0 );
70491 for(i=0; i<r2->nField; i++){
70492 if( r2->aMem[i].flags & MEM_Null ){
70493 *pRes = -1;
70494 return;
70497 r2->flags |= UNPACKED_PREFIX_MATCH;
70500 *pRes = sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
70504 ** This function is called to compare two iterator keys when merging
70505 ** multiple b-tree segments. Parameter iOut is the index of the aTree[]
70506 ** value to recalculate.
70508 static int vdbeSorterDoCompare(VdbeCursor *pCsr, int iOut){
70509 VdbeSorter *pSorter = pCsr->pSorter;
70510 int i1;
70511 int i2;
70512 int iRes;
70513 VdbeSorterIter *p1;
70514 VdbeSorterIter *p2;
70516 assert( iOut<pSorter->nTree && iOut>0 );
70518 if( iOut>=(pSorter->nTree/2) ){
70519 i1 = (iOut - pSorter->nTree/2) * 2;
70520 i2 = i1 + 1;
70521 }else{
70522 i1 = pSorter->aTree[iOut*2];
70523 i2 = pSorter->aTree[iOut*2+1];
70526 p1 = &pSorter->aIter[i1];
70527 p2 = &pSorter->aIter[i2];
70529 if( p1->pFile==0 ){
70530 iRes = i2;
70531 }else if( p2->pFile==0 ){
70532 iRes = i1;
70533 }else{
70534 int res;
70535 assert( pCsr->pSorter->pUnpacked!=0 ); /* allocated in vdbeSorterMerge() */
70536 vdbeSorterCompare(
70537 pCsr, 0, p1->aKey, p1->nKey, p2->aKey, p2->nKey, &res
70539 if( res<=0 ){
70540 iRes = i1;
70541 }else{
70542 iRes = i2;
70546 pSorter->aTree[iOut] = iRes;
70547 return SQLITE_OK;
70551 ** Initialize the temporary index cursor just opened as a sorter cursor.
70553 SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *db, VdbeCursor *pCsr){
70554 int pgsz; /* Page size of main database */
70555 int mxCache; /* Cache size */
70556 VdbeSorter *pSorter; /* The new sorter */
70557 char *d; /* Dummy */
70559 assert( pCsr->pKeyInfo && pCsr->pBt==0 );
70560 pCsr->pSorter = pSorter = sqlite3DbMallocZero(db, sizeof(VdbeSorter));
70561 if( pSorter==0 ){
70562 return SQLITE_NOMEM;
70565 pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pCsr->pKeyInfo, 0, 0, &d);
70566 if( pSorter->pUnpacked==0 ) return SQLITE_NOMEM;
70567 assert( pSorter->pUnpacked==(UnpackedRecord *)d );
70569 if( !sqlite3TempInMemory(db) ){
70570 pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
70571 pSorter->mnPmaSize = SORTER_MIN_WORKING * pgsz;
70572 mxCache = db->aDb[0].pSchema->cache_size;
70573 if( mxCache<SORTER_MIN_WORKING ) mxCache = SORTER_MIN_WORKING;
70574 pSorter->mxPmaSize = mxCache * pgsz;
70577 return SQLITE_OK;
70581 ** Free the list of sorted records starting at pRecord.
70583 static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
70584 SorterRecord *p;
70585 SorterRecord *pNext;
70586 for(p=pRecord; p; p=pNext){
70587 pNext = p->pNext;
70588 sqlite3DbFree(db, p);
70593 ** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
70595 SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
70596 VdbeSorter *pSorter = pCsr->pSorter;
70597 if( pSorter ){
70598 if( pSorter->aIter ){
70599 int i;
70600 for(i=0; i<pSorter->nTree; i++){
70601 vdbeSorterIterZero(db, &pSorter->aIter[i]);
70603 sqlite3DbFree(db, pSorter->aIter);
70605 if( pSorter->pTemp1 ){
70606 sqlite3OsCloseFree(pSorter->pTemp1);
70608 vdbeSorterRecordFree(db, pSorter->pRecord);
70609 sqlite3DbFree(db, pSorter->pUnpacked);
70610 sqlite3DbFree(db, pSorter);
70611 pCsr->pSorter = 0;
70616 ** Allocate space for a file-handle and open a temporary file. If successful,
70617 ** set *ppFile to point to the malloc'd file-handle and return SQLITE_OK.
70618 ** Otherwise, set *ppFile to 0 and return an SQLite error code.
70620 static int vdbeSorterOpenTempFile(sqlite3 *db, sqlite3_file **ppFile){
70621 int dummy;
70622 return sqlite3OsOpenMalloc(db->pVfs, 0, ppFile,
70623 SQLITE_OPEN_TEMP_JOURNAL |
70624 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
70625 SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE, &dummy
70630 ** Merge the two sorted lists p1 and p2 into a single list.
70631 ** Set *ppOut to the head of the new list.
70633 static void vdbeSorterMerge(
70634 VdbeCursor *pCsr, /* For pKeyInfo */
70635 SorterRecord *p1, /* First list to merge */
70636 SorterRecord *p2, /* Second list to merge */
70637 SorterRecord **ppOut /* OUT: Head of merged list */
70639 SorterRecord *pFinal = 0;
70640 SorterRecord **pp = &pFinal;
70641 void *pVal2 = p2 ? p2->pVal : 0;
70643 while( p1 && p2 ){
70644 int res;
70645 vdbeSorterCompare(pCsr, 0, p1->pVal, p1->nVal, pVal2, p2->nVal, &res);
70646 if( res<=0 ){
70647 *pp = p1;
70648 pp = &p1->pNext;
70649 p1 = p1->pNext;
70650 pVal2 = 0;
70651 }else{
70652 *pp = p2;
70653 pp = &p2->pNext;
70654 p2 = p2->pNext;
70655 if( p2==0 ) break;
70656 pVal2 = p2->pVal;
70659 *pp = p1 ? p1 : p2;
70660 *ppOut = pFinal;
70664 ** Sort the linked list of records headed at pCsr->pRecord. Return SQLITE_OK
70665 ** if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if an error
70666 ** occurs.
70668 static int vdbeSorterSort(VdbeCursor *pCsr){
70669 int i;
70670 SorterRecord **aSlot;
70671 SorterRecord *p;
70672 VdbeSorter *pSorter = pCsr->pSorter;
70674 aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
70675 if( !aSlot ){
70676 return SQLITE_NOMEM;
70679 p = pSorter->pRecord;
70680 while( p ){
70681 SorterRecord *pNext = p->pNext;
70682 p->pNext = 0;
70683 for(i=0; aSlot[i]; i++){
70684 vdbeSorterMerge(pCsr, p, aSlot[i], &p);
70685 aSlot[i] = 0;
70687 aSlot[i] = p;
70688 p = pNext;
70691 p = 0;
70692 for(i=0; i<64; i++){
70693 vdbeSorterMerge(pCsr, p, aSlot[i], &p);
70695 pSorter->pRecord = p;
70697 sqlite3_free(aSlot);
70698 return SQLITE_OK;
70703 ** Write the current contents of the in-memory linked-list to a PMA. Return
70704 ** SQLITE_OK if successful, or an SQLite error code otherwise.
70706 ** The format of a PMA is:
70708 ** * A varint. This varint contains the total number of bytes of content
70709 ** in the PMA (not including the varint itself).
70711 ** * One or more records packed end-to-end in order of ascending keys.
70712 ** Each record consists of a varint followed by a blob of data (the
70713 ** key). The varint is the number of bytes in the blob of data.
70715 static int vdbeSorterListToPMA(sqlite3 *db, VdbeCursor *pCsr){
70716 int rc = SQLITE_OK; /* Return code */
70717 VdbeSorter *pSorter = pCsr->pSorter;
70719 if( pSorter->nInMemory==0 ){
70720 assert( pSorter->pRecord==0 );
70721 return rc;
70724 rc = vdbeSorterSort(pCsr);
70726 /* If the first temporary PMA file has not been opened, open it now. */
70727 if( rc==SQLITE_OK && pSorter->pTemp1==0 ){
70728 rc = vdbeSorterOpenTempFile(db, &pSorter->pTemp1);
70729 assert( rc!=SQLITE_OK || pSorter->pTemp1 );
70730 assert( pSorter->iWriteOff==0 );
70731 assert( pSorter->nPMA==0 );
70734 if( rc==SQLITE_OK ){
70735 i64 iOff = pSorter->iWriteOff;
70736 SorterRecord *p;
70737 SorterRecord *pNext = 0;
70738 static const char eightZeros[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
70740 pSorter->nPMA++;
70741 rc = vdbeSorterWriteVarint(pSorter->pTemp1, pSorter->nInMemory, &iOff);
70742 for(p=pSorter->pRecord; rc==SQLITE_OK && p; p=pNext){
70743 pNext = p->pNext;
70744 rc = vdbeSorterWriteVarint(pSorter->pTemp1, p->nVal, &iOff);
70746 if( rc==SQLITE_OK ){
70747 rc = sqlite3OsWrite(pSorter->pTemp1, p->pVal, p->nVal, iOff);
70748 iOff += p->nVal;
70751 sqlite3DbFree(db, p);
70754 /* This assert verifies that unless an error has occurred, the size of
70755 ** the PMA on disk is the same as the expected size stored in
70756 ** pSorter->nInMemory. */
70757 assert( rc!=SQLITE_OK || pSorter->nInMemory==(
70758 iOff-pSorter->iWriteOff-sqlite3VarintLen(pSorter->nInMemory)
70761 pSorter->iWriteOff = iOff;
70762 if( rc==SQLITE_OK ){
70763 /* Terminate each file with 8 extra bytes so that from any offset
70764 ** in the file we can always read 9 bytes without a SHORT_READ error */
70765 rc = sqlite3OsWrite(pSorter->pTemp1, eightZeros, 8, iOff);
70767 pSorter->pRecord = p;
70770 return rc;
70774 ** Add a record to the sorter.
70776 SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
70777 sqlite3 *db, /* Database handle */
70778 VdbeCursor *pCsr, /* Sorter cursor */
70779 Mem *pVal /* Memory cell containing record */
70781 VdbeSorter *pSorter = pCsr->pSorter;
70782 int rc = SQLITE_OK; /* Return Code */
70783 SorterRecord *pNew; /* New list element */
70785 assert( pSorter );
70786 pSorter->nInMemory += sqlite3VarintLen(pVal->n) + pVal->n;
70788 pNew = (SorterRecord *)sqlite3DbMallocRaw(db, pVal->n + sizeof(SorterRecord));
70789 if( pNew==0 ){
70790 rc = SQLITE_NOMEM;
70791 }else{
70792 pNew->pVal = (void *)&pNew[1];
70793 memcpy(pNew->pVal, pVal->z, pVal->n);
70794 pNew->nVal = pVal->n;
70795 pNew->pNext = pSorter->pRecord;
70796 pSorter->pRecord = pNew;
70799 /* See if the contents of the sorter should now be written out. They
70800 ** are written out when either of the following are true:
70802 ** * The total memory allocated for the in-memory list is greater
70803 ** than (page-size * cache-size), or
70805 ** * The total memory allocated for the in-memory list is greater
70806 ** than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
70808 if( rc==SQLITE_OK && pSorter->mxPmaSize>0 && (
70809 (pSorter->nInMemory>pSorter->mxPmaSize)
70810 || (pSorter->nInMemory>pSorter->mnPmaSize && sqlite3HeapNearlyFull())
70812 rc = vdbeSorterListToPMA(db, pCsr);
70813 pSorter->nInMemory = 0;
70816 return rc;
70820 ** Helper function for sqlite3VdbeSorterRewind().
70822 static int vdbeSorterInitMerge(
70823 sqlite3 *db, /* Database handle */
70824 VdbeCursor *pCsr, /* Cursor handle for this sorter */
70825 i64 *pnByte /* Sum of bytes in all opened PMAs */
70827 VdbeSorter *pSorter = pCsr->pSorter;
70828 int rc = SQLITE_OK; /* Return code */
70829 int i; /* Used to iterator through aIter[] */
70830 i64 nByte = 0; /* Total bytes in all opened PMAs */
70832 /* Initialize the iterators. */
70833 for(i=0; i<SORTER_MAX_MERGE_COUNT; i++){
70834 VdbeSorterIter *pIter = &pSorter->aIter[i];
70835 rc = vdbeSorterIterInit(db, pSorter, pSorter->iReadOff, pIter, &nByte);
70836 pSorter->iReadOff = pIter->iEof;
70837 assert( rc!=SQLITE_OK || pSorter->iReadOff<=pSorter->iWriteOff );
70838 if( rc!=SQLITE_OK || pSorter->iReadOff>=pSorter->iWriteOff ) break;
70841 /* Initialize the aTree[] array. */
70842 for(i=pSorter->nTree-1; rc==SQLITE_OK && i>0; i--){
70843 rc = vdbeSorterDoCompare(pCsr, i);
70846 *pnByte = nByte;
70847 return rc;
70851 ** Once the sorter has been populated, this function is called to prepare
70852 ** for iterating through its contents in sorted order.
70854 SQLITE_PRIVATE int sqlite3VdbeSorterRewind(sqlite3 *db, VdbeCursor *pCsr, int *pbEof){
70855 VdbeSorter *pSorter = pCsr->pSorter;
70856 int rc; /* Return code */
70857 sqlite3_file *pTemp2 = 0; /* Second temp file to use */
70858 i64 iWrite2 = 0; /* Write offset for pTemp2 */
70859 int nIter; /* Number of iterators used */
70860 int nByte; /* Bytes of space required for aIter/aTree */
70861 int N = 2; /* Power of 2 >= nIter */
70863 assert( pSorter );
70865 /* If no data has been written to disk, then do not do so now. Instead,
70866 ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
70867 ** from the in-memory list. */
70868 if( pSorter->nPMA==0 ){
70869 *pbEof = !pSorter->pRecord;
70870 assert( pSorter->aTree==0 );
70871 return vdbeSorterSort(pCsr);
70874 /* Write the current b-tree to a PMA. Close the b-tree cursor. */
70875 rc = vdbeSorterListToPMA(db, pCsr);
70876 if( rc!=SQLITE_OK ) return rc;
70878 /* Allocate space for aIter[] and aTree[]. */
70879 nIter = pSorter->nPMA;
70880 if( nIter>SORTER_MAX_MERGE_COUNT ) nIter = SORTER_MAX_MERGE_COUNT;
70881 assert( nIter>0 );
70882 while( N<nIter ) N += N;
70883 nByte = N * (sizeof(int) + sizeof(VdbeSorterIter));
70884 pSorter->aIter = (VdbeSorterIter *)sqlite3DbMallocZero(db, nByte);
70885 if( !pSorter->aIter ) return SQLITE_NOMEM;
70886 pSorter->aTree = (int *)&pSorter->aIter[N];
70887 pSorter->nTree = N;
70889 do {
70890 int iNew; /* Index of new, merged, PMA */
70892 for(iNew=0;
70893 rc==SQLITE_OK && iNew*SORTER_MAX_MERGE_COUNT<pSorter->nPMA;
70894 iNew++
70896 i64 nWrite; /* Number of bytes in new PMA */
70898 /* If there are SORTER_MAX_MERGE_COUNT or less PMAs in file pTemp1,
70899 ** initialize an iterator for each of them and break out of the loop.
70900 ** These iterators will be incrementally merged as the VDBE layer calls
70901 ** sqlite3VdbeSorterNext().
70903 ** Otherwise, if pTemp1 contains more than SORTER_MAX_MERGE_COUNT PMAs,
70904 ** initialize interators for SORTER_MAX_MERGE_COUNT of them. These PMAs
70905 ** are merged into a single PMA that is written to file pTemp2.
70907 rc = vdbeSorterInitMerge(db, pCsr, &nWrite);
70908 assert( rc!=SQLITE_OK || pSorter->aIter[ pSorter->aTree[1] ].pFile );
70909 if( rc!=SQLITE_OK || pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
70910 break;
70913 /* Open the second temp file, if it is not already open. */
70914 if( pTemp2==0 ){
70915 assert( iWrite2==0 );
70916 rc = vdbeSorterOpenTempFile(db, &pTemp2);
70919 if( rc==SQLITE_OK ){
70920 rc = vdbeSorterWriteVarint(pTemp2, nWrite, &iWrite2);
70923 if( rc==SQLITE_OK ){
70924 int bEof = 0;
70925 while( rc==SQLITE_OK && bEof==0 ){
70926 int nToWrite;
70927 VdbeSorterIter *pIter = &pSorter->aIter[ pSorter->aTree[1] ];
70928 assert( pIter->pFile );
70929 nToWrite = pIter->nKey + sqlite3VarintLen(pIter->nKey);
70930 rc = sqlite3OsWrite(pTemp2, pIter->aAlloc, nToWrite, iWrite2);
70931 iWrite2 += nToWrite;
70932 if( rc==SQLITE_OK ){
70933 rc = sqlite3VdbeSorterNext(db, pCsr, &bEof);
70939 if( pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
70940 break;
70941 }else{
70942 sqlite3_file *pTmp = pSorter->pTemp1;
70943 pSorter->nPMA = iNew;
70944 pSorter->pTemp1 = pTemp2;
70945 pTemp2 = pTmp;
70946 pSorter->iWriteOff = iWrite2;
70947 pSorter->iReadOff = 0;
70948 iWrite2 = 0;
70950 }while( rc==SQLITE_OK );
70952 if( pTemp2 ){
70953 sqlite3OsCloseFree(pTemp2);
70955 *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
70956 return rc;
70960 ** Advance to the next element in the sorter.
70962 SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, VdbeCursor *pCsr, int *pbEof){
70963 VdbeSorter *pSorter = pCsr->pSorter;
70964 int rc; /* Return code */
70966 if( pSorter->aTree ){
70967 int iPrev = pSorter->aTree[1];/* Index of iterator to advance */
70968 int i; /* Index of aTree[] to recalculate */
70970 rc = vdbeSorterIterNext(db, &pSorter->aIter[iPrev]);
70971 for(i=(pSorter->nTree+iPrev)/2; rc==SQLITE_OK && i>0; i=i/2){
70972 rc = vdbeSorterDoCompare(pCsr, i);
70975 *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
70976 }else{
70977 SorterRecord *pFree = pSorter->pRecord;
70978 pSorter->pRecord = pFree->pNext;
70979 pFree->pNext = 0;
70980 vdbeSorterRecordFree(db, pFree);
70981 *pbEof = !pSorter->pRecord;
70982 rc = SQLITE_OK;
70984 return rc;
70988 ** Return a pointer to a buffer owned by the sorter that contains the
70989 ** current key.
70991 static void *vdbeSorterRowkey(
70992 VdbeSorter *pSorter, /* Sorter object */
70993 int *pnKey /* OUT: Size of current key in bytes */
70995 void *pKey;
70996 if( pSorter->aTree ){
70997 VdbeSorterIter *pIter;
70998 pIter = &pSorter->aIter[ pSorter->aTree[1] ];
70999 *pnKey = pIter->nKey;
71000 pKey = pIter->aKey;
71001 }else{
71002 *pnKey = pSorter->pRecord->nVal;
71003 pKey = pSorter->pRecord->pVal;
71005 return pKey;
71009 ** Copy the current sorter key into the memory cell pOut.
71011 SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(VdbeCursor *pCsr, Mem *pOut){
71012 VdbeSorter *pSorter = pCsr->pSorter;
71013 void *pKey; int nKey; /* Sorter key to copy into pOut */
71015 pKey = vdbeSorterRowkey(pSorter, &nKey);
71016 if( sqlite3VdbeMemGrow(pOut, nKey, 0) ){
71017 return SQLITE_NOMEM;
71019 pOut->n = nKey;
71020 MemSetTypeFlag(pOut, MEM_Blob);
71021 memcpy(pOut->z, pKey, nKey);
71023 return SQLITE_OK;
71027 ** Compare the key in memory cell pVal with the key that the sorter cursor
71028 ** passed as the first argument currently points to. For the purposes of
71029 ** the comparison, ignore the rowid field at the end of each record.
71031 ** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
71032 ** Otherwise, set *pRes to a negative, zero or positive value if the
71033 ** key in pVal is smaller than, equal to or larger than the current sorter
71034 ** key.
71036 SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
71037 VdbeCursor *pCsr, /* Sorter cursor */
71038 Mem *pVal, /* Value to compare to current sorter key */
71039 int *pRes /* OUT: Result of comparison */
71041 VdbeSorter *pSorter = pCsr->pSorter;
71042 void *pKey; int nKey; /* Sorter key to compare pVal with */
71044 pKey = vdbeSorterRowkey(pSorter, &nKey);
71045 vdbeSorterCompare(pCsr, 1, pVal->z, pVal->n, pKey, nKey, pRes);
71046 return SQLITE_OK;
71049 #endif /* #ifndef SQLITE_OMIT_MERGE_SORT */
71051 /************** End of vdbesort.c ********************************************/
71052 /************** Begin file journal.c *****************************************/
71054 ** 2007 August 22
71056 ** The author disclaims copyright to this source code. In place of
71057 ** a legal notice, here is a blessing:
71059 ** May you do good and not evil.
71060 ** May you find forgiveness for yourself and forgive others.
71061 ** May you share freely, never taking more than you give.
71063 *************************************************************************
71065 ** This file implements a special kind of sqlite3_file object used
71066 ** by SQLite to create journal files if the atomic-write optimization
71067 ** is enabled.
71069 ** The distinctive characteristic of this sqlite3_file is that the
71070 ** actual on disk file is created lazily. When the file is created,
71071 ** the caller specifies a buffer size for an in-memory buffer to
71072 ** be used to service read() and write() requests. The actual file
71073 ** on disk is not created or populated until either:
71075 ** 1) The in-memory representation grows too large for the allocated
71076 ** buffer, or
71077 ** 2) The sqlite3JournalCreate() function is called.
71079 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
71083 ** A JournalFile object is a subclass of sqlite3_file used by
71084 ** as an open file handle for journal files.
71086 struct JournalFile {
71087 sqlite3_io_methods *pMethod; /* I/O methods on journal files */
71088 int nBuf; /* Size of zBuf[] in bytes */
71089 char *zBuf; /* Space to buffer journal writes */
71090 int iSize; /* Amount of zBuf[] currently used */
71091 int flags; /* xOpen flags */
71092 sqlite3_vfs *pVfs; /* The "real" underlying VFS */
71093 sqlite3_file *pReal; /* The "real" underlying file descriptor */
71094 const char *zJournal; /* Name of the journal file */
71096 typedef struct JournalFile JournalFile;
71099 ** If it does not already exists, create and populate the on-disk file
71100 ** for JournalFile p.
71102 static int createFile(JournalFile *p){
71103 int rc = SQLITE_OK;
71104 if( !p->pReal ){
71105 sqlite3_file *pReal = (sqlite3_file *)&p[1];
71106 rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
71107 if( rc==SQLITE_OK ){
71108 p->pReal = pReal;
71109 if( p->iSize>0 ){
71110 assert(p->iSize<=p->nBuf);
71111 rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
71115 return rc;
71119 ** Close the file.
71121 static int jrnlClose(sqlite3_file *pJfd){
71122 JournalFile *p = (JournalFile *)pJfd;
71123 if( p->pReal ){
71124 sqlite3OsClose(p->pReal);
71126 sqlite3_free(p->zBuf);
71127 return SQLITE_OK;
71131 ** Read data from the file.
71133 static int jrnlRead(
71134 sqlite3_file *pJfd, /* The journal file from which to read */
71135 void *zBuf, /* Put the results here */
71136 int iAmt, /* Number of bytes to read */
71137 sqlite_int64 iOfst /* Begin reading at this offset */
71139 int rc = SQLITE_OK;
71140 JournalFile *p = (JournalFile *)pJfd;
71141 if( p->pReal ){
71142 rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
71143 }else if( (iAmt+iOfst)>p->iSize ){
71144 rc = SQLITE_IOERR_SHORT_READ;
71145 }else{
71146 memcpy(zBuf, &p->zBuf[iOfst], iAmt);
71148 return rc;
71152 ** Write data to the file.
71154 static int jrnlWrite(
71155 sqlite3_file *pJfd, /* The journal file into which to write */
71156 const void *zBuf, /* Take data to be written from here */
71157 int iAmt, /* Number of bytes to write */
71158 sqlite_int64 iOfst /* Begin writing at this offset into the file */
71160 int rc = SQLITE_OK;
71161 JournalFile *p = (JournalFile *)pJfd;
71162 if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
71163 rc = createFile(p);
71165 if( rc==SQLITE_OK ){
71166 if( p->pReal ){
71167 rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
71168 }else{
71169 memcpy(&p->zBuf[iOfst], zBuf, iAmt);
71170 if( p->iSize<(iOfst+iAmt) ){
71171 p->iSize = (iOfst+iAmt);
71175 return rc;
71179 ** Truncate the file.
71181 static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
71182 int rc = SQLITE_OK;
71183 JournalFile *p = (JournalFile *)pJfd;
71184 if( p->pReal ){
71185 rc = sqlite3OsTruncate(p->pReal, size);
71186 }else if( size<p->iSize ){
71187 p->iSize = size;
71189 return rc;
71193 ** Sync the file.
71195 static int jrnlSync(sqlite3_file *pJfd, int flags){
71196 int rc;
71197 JournalFile *p = (JournalFile *)pJfd;
71198 if( p->pReal ){
71199 rc = sqlite3OsSync(p->pReal, flags);
71200 }else{
71201 rc = SQLITE_OK;
71203 return rc;
71207 ** Query the size of the file in bytes.
71209 static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
71210 int rc = SQLITE_OK;
71211 JournalFile *p = (JournalFile *)pJfd;
71212 if( p->pReal ){
71213 rc = sqlite3OsFileSize(p->pReal, pSize);
71214 }else{
71215 *pSize = (sqlite_int64) p->iSize;
71217 return rc;
71221 ** Table of methods for JournalFile sqlite3_file object.
71223 static struct sqlite3_io_methods JournalFileMethods = {
71224 1, /* iVersion */
71225 jrnlClose, /* xClose */
71226 jrnlRead, /* xRead */
71227 jrnlWrite, /* xWrite */
71228 jrnlTruncate, /* xTruncate */
71229 jrnlSync, /* xSync */
71230 jrnlFileSize, /* xFileSize */
71231 0, /* xLock */
71232 0, /* xUnlock */
71233 0, /* xCheckReservedLock */
71234 0, /* xFileControl */
71235 0, /* xSectorSize */
71236 0, /* xDeviceCharacteristics */
71237 0, /* xShmMap */
71238 0, /* xShmLock */
71239 0, /* xShmBarrier */
71240 0 /* xShmUnmap */
71244 ** Open a journal file.
71246 SQLITE_PRIVATE int sqlite3JournalOpen(
71247 sqlite3_vfs *pVfs, /* The VFS to use for actual file I/O */
71248 const char *zName, /* Name of the journal file */
71249 sqlite3_file *pJfd, /* Preallocated, blank file handle */
71250 int flags, /* Opening flags */
71251 int nBuf /* Bytes buffered before opening the file */
71253 JournalFile *p = (JournalFile *)pJfd;
71254 memset(p, 0, sqlite3JournalSize(pVfs));
71255 if( nBuf>0 ){
71256 p->zBuf = sqlite3MallocZero(nBuf);
71257 if( !p->zBuf ){
71258 return SQLITE_NOMEM;
71260 }else{
71261 return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
71263 p->pMethod = &JournalFileMethods;
71264 p->nBuf = nBuf;
71265 p->flags = flags;
71266 p->zJournal = zName;
71267 p->pVfs = pVfs;
71268 return SQLITE_OK;
71272 ** If the argument p points to a JournalFile structure, and the underlying
71273 ** file has not yet been created, create it now.
71275 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
71276 if( p->pMethods!=&JournalFileMethods ){
71277 return SQLITE_OK;
71279 return createFile((JournalFile *)p);
71283 ** Return the number of bytes required to store a JournalFile that uses vfs
71284 ** pVfs to create the underlying on-disk files.
71286 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
71287 return (pVfs->szOsFile+sizeof(JournalFile));
71289 #endif
71291 /************** End of journal.c *********************************************/
71292 /************** Begin file memjournal.c **************************************/
71294 ** 2008 October 7
71296 ** The author disclaims copyright to this source code. In place of
71297 ** a legal notice, here is a blessing:
71299 ** May you do good and not evil.
71300 ** May you find forgiveness for yourself and forgive others.
71301 ** May you share freely, never taking more than you give.
71303 *************************************************************************
71305 ** This file contains code use to implement an in-memory rollback journal.
71306 ** The in-memory rollback journal is used to journal transactions for
71307 ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
71310 /* Forward references to internal structures */
71311 typedef struct MemJournal MemJournal;
71312 typedef struct FilePoint FilePoint;
71313 typedef struct FileChunk FileChunk;
71315 /* Space to hold the rollback journal is allocated in increments of
71316 ** this many bytes.
71318 ** The size chosen is a little less than a power of two. That way,
71319 ** the FileChunk object will have a size that almost exactly fills
71320 ** a power-of-two allocation. This mimimizes wasted space in power-of-two
71321 ** memory allocators.
71323 #define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
71325 /* Macro to find the minimum of two numeric values.
71327 #ifndef MIN
71328 # define MIN(x,y) ((x)<(y)?(x):(y))
71329 #endif
71332 ** The rollback journal is composed of a linked list of these structures.
71334 struct FileChunk {
71335 FileChunk *pNext; /* Next chunk in the journal */
71336 u8 zChunk[JOURNAL_CHUNKSIZE]; /* Content of this chunk */
71340 ** An instance of this object serves as a cursor into the rollback journal.
71341 ** The cursor can be either for reading or writing.
71343 struct FilePoint {
71344 sqlite3_int64 iOffset; /* Offset from the beginning of the file */
71345 FileChunk *pChunk; /* Specific chunk into which cursor points */
71349 ** This subclass is a subclass of sqlite3_file. Each open memory-journal
71350 ** is an instance of this class.
71352 struct MemJournal {
71353 sqlite3_io_methods *pMethod; /* Parent class. MUST BE FIRST */
71354 FileChunk *pFirst; /* Head of in-memory chunk-list */
71355 FilePoint endpoint; /* Pointer to the end of the file */
71356 FilePoint readpoint; /* Pointer to the end of the last xRead() */
71360 ** Read data from the in-memory journal file. This is the implementation
71361 ** of the sqlite3_vfs.xRead method.
71363 static int memjrnlRead(
71364 sqlite3_file *pJfd, /* The journal file from which to read */
71365 void *zBuf, /* Put the results here */
71366 int iAmt, /* Number of bytes to read */
71367 sqlite_int64 iOfst /* Begin reading at this offset */
71369 MemJournal *p = (MemJournal *)pJfd;
71370 u8 *zOut = zBuf;
71371 int nRead = iAmt;
71372 int iChunkOffset;
71373 FileChunk *pChunk;
71375 /* SQLite never tries to read past the end of a rollback journal file */
71376 assert( iOfst+iAmt<=p->endpoint.iOffset );
71378 if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
71379 sqlite3_int64 iOff = 0;
71380 for(pChunk=p->pFirst;
71381 ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
71382 pChunk=pChunk->pNext
71384 iOff += JOURNAL_CHUNKSIZE;
71386 }else{
71387 pChunk = p->readpoint.pChunk;
71390 iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
71391 do {
71392 int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
71393 int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
71394 memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
71395 zOut += nCopy;
71396 nRead -= iSpace;
71397 iChunkOffset = 0;
71398 } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
71399 p->readpoint.iOffset = iOfst+iAmt;
71400 p->readpoint.pChunk = pChunk;
71402 return SQLITE_OK;
71406 ** Write data to the file.
71408 static int memjrnlWrite(
71409 sqlite3_file *pJfd, /* The journal file into which to write */
71410 const void *zBuf, /* Take data to be written from here */
71411 int iAmt, /* Number of bytes to write */
71412 sqlite_int64 iOfst /* Begin writing at this offset into the file */
71414 MemJournal *p = (MemJournal *)pJfd;
71415 int nWrite = iAmt;
71416 u8 *zWrite = (u8 *)zBuf;
71418 /* An in-memory journal file should only ever be appended to. Random
71419 ** access writes are not required by sqlite.
71421 assert( iOfst==p->endpoint.iOffset );
71422 UNUSED_PARAMETER(iOfst);
71424 while( nWrite>0 ){
71425 FileChunk *pChunk = p->endpoint.pChunk;
71426 int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
71427 int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
71429 if( iChunkOffset==0 ){
71430 /* New chunk is required to extend the file. */
71431 FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
71432 if( !pNew ){
71433 return SQLITE_IOERR_NOMEM;
71435 pNew->pNext = 0;
71436 if( pChunk ){
71437 assert( p->pFirst );
71438 pChunk->pNext = pNew;
71439 }else{
71440 assert( !p->pFirst );
71441 p->pFirst = pNew;
71443 p->endpoint.pChunk = pNew;
71446 memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
71447 zWrite += iSpace;
71448 nWrite -= iSpace;
71449 p->endpoint.iOffset += iSpace;
71452 return SQLITE_OK;
71456 ** Truncate the file.
71458 static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
71459 MemJournal *p = (MemJournal *)pJfd;
71460 FileChunk *pChunk;
71461 assert(size==0);
71462 UNUSED_PARAMETER(size);
71463 pChunk = p->pFirst;
71464 while( pChunk ){
71465 FileChunk *pTmp = pChunk;
71466 pChunk = pChunk->pNext;
71467 sqlite3_free(pTmp);
71469 sqlite3MemJournalOpen(pJfd);
71470 return SQLITE_OK;
71474 ** Close the file.
71476 static int memjrnlClose(sqlite3_file *pJfd){
71477 memjrnlTruncate(pJfd, 0);
71478 return SQLITE_OK;
71483 ** Sync the file.
71485 ** Syncing an in-memory journal is a no-op. And, in fact, this routine
71486 ** is never called in a working implementation. This implementation
71487 ** exists purely as a contingency, in case some malfunction in some other
71488 ** part of SQLite causes Sync to be called by mistake.
71490 static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
71491 UNUSED_PARAMETER2(NotUsed, NotUsed2);
71492 return SQLITE_OK;
71496 ** Query the size of the file in bytes.
71498 static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
71499 MemJournal *p = (MemJournal *)pJfd;
71500 *pSize = (sqlite_int64) p->endpoint.iOffset;
71501 return SQLITE_OK;
71505 ** Table of methods for MemJournal sqlite3_file object.
71507 static const struct sqlite3_io_methods MemJournalMethods = {
71508 1, /* iVersion */
71509 memjrnlClose, /* xClose */
71510 memjrnlRead, /* xRead */
71511 memjrnlWrite, /* xWrite */
71512 memjrnlTruncate, /* xTruncate */
71513 memjrnlSync, /* xSync */
71514 memjrnlFileSize, /* xFileSize */
71515 0, /* xLock */
71516 0, /* xUnlock */
71517 0, /* xCheckReservedLock */
71518 0, /* xFileControl */
71519 0, /* xSectorSize */
71520 0, /* xDeviceCharacteristics */
71521 0, /* xShmMap */
71522 0, /* xShmLock */
71523 0, /* xShmBarrier */
71524 0 /* xShmUnlock */
71528 ** Open a journal file.
71530 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
71531 MemJournal *p = (MemJournal *)pJfd;
71532 assert( EIGHT_BYTE_ALIGNMENT(p) );
71533 memset(p, 0, sqlite3MemJournalSize());
71534 p->pMethod = (sqlite3_io_methods*)&MemJournalMethods;
71538 ** Return true if the file-handle passed as an argument is
71539 ** an in-memory journal
71541 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
71542 return pJfd->pMethods==&MemJournalMethods;
71546 ** Return the number of bytes required to store a MemJournal file descriptor.
71548 SQLITE_PRIVATE int sqlite3MemJournalSize(void){
71549 return sizeof(MemJournal);
71552 /************** End of memjournal.c ******************************************/
71553 /************** Begin file walker.c ******************************************/
71555 ** 2008 August 16
71557 ** The author disclaims copyright to this source code. In place of
71558 ** a legal notice, here is a blessing:
71560 ** May you do good and not evil.
71561 ** May you find forgiveness for yourself and forgive others.
71562 ** May you share freely, never taking more than you give.
71564 *************************************************************************
71565 ** This file contains routines used for walking the parser tree for
71566 ** an SQL statement.
71568 /* #include <stdlib.h> */
71569 /* #include <string.h> */
71573 ** Walk an expression tree. Invoke the callback once for each node
71574 ** of the expression, while decending. (In other words, the callback
71575 ** is invoked before visiting children.)
71577 ** The return value from the callback should be one of the WRC_*
71578 ** constants to specify how to proceed with the walk.
71580 ** WRC_Continue Continue descending down the tree.
71582 ** WRC_Prune Do not descend into child nodes. But allow
71583 ** the walk to continue with sibling nodes.
71585 ** WRC_Abort Do no more callbacks. Unwind the stack and
71586 ** return the top-level walk call.
71588 ** The return value from this routine is WRC_Abort to abandon the tree walk
71589 ** and WRC_Continue to continue.
71591 SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
71592 int rc;
71593 if( pExpr==0 ) return WRC_Continue;
71594 testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
71595 testcase( ExprHasProperty(pExpr, EP_Reduced) );
71596 rc = pWalker->xExprCallback(pWalker, pExpr);
71597 if( rc==WRC_Continue
71598 && !ExprHasAnyProperty(pExpr,EP_TokenOnly) ){
71599 if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
71600 if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
71601 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
71602 if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
71603 }else{
71604 if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
71607 return rc & WRC_Abort;
71611 ** Call sqlite3WalkExpr() for every expression in list p or until
71612 ** an abort request is seen.
71614 SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
71615 int i;
71616 struct ExprList_item *pItem;
71617 if( p ){
71618 for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
71619 if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
71622 return WRC_Continue;
71626 ** Walk all expressions associated with SELECT statement p. Do
71627 ** not invoke the SELECT callback on p, but do (of course) invoke
71628 ** any expr callbacks and SELECT callbacks that come from subqueries.
71629 ** Return WRC_Abort or WRC_Continue.
71631 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
71632 if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
71633 if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
71634 if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
71635 if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
71636 if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
71637 if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
71638 if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
71639 return WRC_Continue;
71643 ** Walk the parse trees associated with all subqueries in the
71644 ** FROM clause of SELECT statement p. Do not invoke the select
71645 ** callback on p, but do invoke it on each FROM clause subquery
71646 ** and on any subqueries further down in the tree. Return
71647 ** WRC_Abort or WRC_Continue;
71649 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
71650 SrcList *pSrc;
71651 int i;
71652 struct SrcList_item *pItem;
71654 pSrc = p->pSrc;
71655 if( ALWAYS(pSrc) ){
71656 for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
71657 if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
71658 return WRC_Abort;
71662 return WRC_Continue;
71666 ** Call sqlite3WalkExpr() for every expression in Select statement p.
71667 ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
71668 ** on the compound select chain, p->pPrior.
71670 ** Return WRC_Continue under normal conditions. Return WRC_Abort if
71671 ** there is an abort request.
71673 ** If the Walker does not have an xSelectCallback() then this routine
71674 ** is a no-op returning WRC_Continue.
71676 SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
71677 int rc;
71678 if( p==0 || pWalker->xSelectCallback==0 ) return WRC_Continue;
71679 rc = WRC_Continue;
71680 while( p ){
71681 rc = pWalker->xSelectCallback(pWalker, p);
71682 if( rc ) break;
71683 if( sqlite3WalkSelectExpr(pWalker, p) ) return WRC_Abort;
71684 if( sqlite3WalkSelectFrom(pWalker, p) ) return WRC_Abort;
71685 p = p->pPrior;
71687 return rc & WRC_Abort;
71690 /************** End of walker.c **********************************************/
71691 /************** Begin file resolve.c *****************************************/
71693 ** 2008 August 18
71695 ** The author disclaims copyright to this source code. In place of
71696 ** a legal notice, here is a blessing:
71698 ** May you do good and not evil.
71699 ** May you find forgiveness for yourself and forgive others.
71700 ** May you share freely, never taking more than you give.
71702 *************************************************************************
71704 ** This file contains routines used for walking the parser tree and
71705 ** resolve all identifiers by associating them with a particular
71706 ** table and column.
71708 /* #include <stdlib.h> */
71709 /* #include <string.h> */
71712 ** Turn the pExpr expression into an alias for the iCol-th column of the
71713 ** result set in pEList.
71715 ** If the result set column is a simple column reference, then this routine
71716 ** makes an exact copy. But for any other kind of expression, this
71717 ** routine make a copy of the result set column as the argument to the
71718 ** TK_AS operator. The TK_AS operator causes the expression to be
71719 ** evaluated just once and then reused for each alias.
71721 ** The reason for suppressing the TK_AS term when the expression is a simple
71722 ** column reference is so that the column reference will be recognized as
71723 ** usable by indices within the WHERE clause processing logic.
71725 ** Hack: The TK_AS operator is inhibited if zType[0]=='G'. This means
71726 ** that in a GROUP BY clause, the expression is evaluated twice. Hence:
71728 ** SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
71730 ** Is equivalent to:
71732 ** SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
71734 ** The result of random()%5 in the GROUP BY clause is probably different
71735 ** from the result in the result-set. We might fix this someday. Or
71736 ** then again, we might not...
71738 static void resolveAlias(
71739 Parse *pParse, /* Parsing context */
71740 ExprList *pEList, /* A result set */
71741 int iCol, /* A column in the result set. 0..pEList->nExpr-1 */
71742 Expr *pExpr, /* Transform this into an alias to the result set */
71743 const char *zType /* "GROUP" or "ORDER" or "" */
71745 Expr *pOrig; /* The iCol-th column of the result set */
71746 Expr *pDup; /* Copy of pOrig */
71747 sqlite3 *db; /* The database connection */
71749 assert( iCol>=0 && iCol<pEList->nExpr );
71750 pOrig = pEList->a[iCol].pExpr;
71751 assert( pOrig!=0 );
71752 assert( pOrig->flags & EP_Resolved );
71753 db = pParse->db;
71754 if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
71755 pDup = sqlite3ExprDup(db, pOrig, 0);
71756 pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
71757 if( pDup==0 ) return;
71758 if( pEList->a[iCol].iAlias==0 ){
71759 pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
71761 pDup->iTable = pEList->a[iCol].iAlias;
71762 }else if( ExprHasProperty(pOrig, EP_IntValue) || pOrig->u.zToken==0 ){
71763 pDup = sqlite3ExprDup(db, pOrig, 0);
71764 if( pDup==0 ) return;
71765 }else{
71766 char *zToken = pOrig->u.zToken;
71767 assert( zToken!=0 );
71768 pOrig->u.zToken = 0;
71769 pDup = sqlite3ExprDup(db, pOrig, 0);
71770 pOrig->u.zToken = zToken;
71771 if( pDup==0 ) return;
71772 assert( (pDup->flags & (EP_Reduced|EP_TokenOnly))==0 );
71773 pDup->flags2 |= EP2_MallocedToken;
71774 pDup->u.zToken = sqlite3DbStrDup(db, zToken);
71776 if( pExpr->flags & EP_ExpCollate ){
71777 pDup->pColl = pExpr->pColl;
71778 pDup->flags |= EP_ExpCollate;
71781 /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
71782 ** prevents ExprDelete() from deleting the Expr structure itself,
71783 ** allowing it to be repopulated by the memcpy() on the following line.
71785 ExprSetProperty(pExpr, EP_Static);
71786 sqlite3ExprDelete(db, pExpr);
71787 memcpy(pExpr, pDup, sizeof(*pExpr));
71788 sqlite3DbFree(db, pDup);
71793 ** Return TRUE if the name zCol occurs anywhere in the USING clause.
71795 ** Return FALSE if the USING clause is NULL or if it does not contain
71796 ** zCol.
71798 static int nameInUsingClause(IdList *pUsing, const char *zCol){
71799 if( pUsing ){
71800 int k;
71801 for(k=0; k<pUsing->nId; k++){
71802 if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
71805 return 0;
71810 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
71811 ** that name in the set of source tables in pSrcList and make the pExpr
71812 ** expression node refer back to that source column. The following changes
71813 ** are made to pExpr:
71815 ** pExpr->iDb Set the index in db->aDb[] of the database X
71816 ** (even if X is implied).
71817 ** pExpr->iTable Set to the cursor number for the table obtained
71818 ** from pSrcList.
71819 ** pExpr->pTab Points to the Table structure of X.Y (even if
71820 ** X and/or Y are implied.)
71821 ** pExpr->iColumn Set to the column number within the table.
71822 ** pExpr->op Set to TK_COLUMN.
71823 ** pExpr->pLeft Any expression this points to is deleted
71824 ** pExpr->pRight Any expression this points to is deleted.
71826 ** The zDb variable is the name of the database (the "X"). This value may be
71827 ** NULL meaning that name is of the form Y.Z or Z. Any available database
71828 ** can be used. The zTable variable is the name of the table (the "Y"). This
71829 ** value can be NULL if zDb is also NULL. If zTable is NULL it
71830 ** means that the form of the name is Z and that columns from any table
71831 ** can be used.
71833 ** If the name cannot be resolved unambiguously, leave an error message
71834 ** in pParse and return WRC_Abort. Return WRC_Prune on success.
71836 static int lookupName(
71837 Parse *pParse, /* The parsing context */
71838 const char *zDb, /* Name of the database containing table, or NULL */
71839 const char *zTab, /* Name of table containing column, or NULL */
71840 const char *zCol, /* Name of the column. */
71841 NameContext *pNC, /* The name context used to resolve the name */
71842 Expr *pExpr /* Make this EXPR node point to the selected column */
71844 int i, j; /* Loop counters */
71845 int cnt = 0; /* Number of matching column names */
71846 int cntTab = 0; /* Number of matching table names */
71847 sqlite3 *db = pParse->db; /* The database connection */
71848 struct SrcList_item *pItem; /* Use for looping over pSrcList items */
71849 struct SrcList_item *pMatch = 0; /* The matching pSrcList item */
71850 NameContext *pTopNC = pNC; /* First namecontext in the list */
71851 Schema *pSchema = 0; /* Schema of the expression */
71852 int isTrigger = 0;
71854 assert( pNC ); /* the name context cannot be NULL. */
71855 assert( zCol ); /* The Z in X.Y.Z cannot be NULL */
71856 assert( ~ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
71858 /* Initialize the node to no-match */
71859 pExpr->iTable = -1;
71860 pExpr->pTab = 0;
71861 ExprSetIrreducible(pExpr);
71863 /* Start at the inner-most context and move outward until a match is found */
71864 while( pNC && cnt==0 ){
71865 ExprList *pEList;
71866 SrcList *pSrcList = pNC->pSrcList;
71868 if( pSrcList ){
71869 for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
71870 Table *pTab;
71871 int iDb;
71872 Column *pCol;
71874 pTab = pItem->pTab;
71875 assert( pTab!=0 && pTab->zName!=0 );
71876 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
71877 assert( pTab->nCol>0 );
71878 if( zTab ){
71879 if( pItem->zAlias ){
71880 char *zTabName = pItem->zAlias;
71881 if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
71882 }else{
71883 char *zTabName = pTab->zName;
71884 if( NEVER(zTabName==0) || sqlite3StrICmp(zTabName, zTab)!=0 ){
71885 continue;
71887 if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
71888 continue;
71892 if( 0==(cntTab++) ){
71893 pExpr->iTable = pItem->iCursor;
71894 pExpr->pTab = pTab;
71895 pSchema = pTab->pSchema;
71896 pMatch = pItem;
71898 for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
71899 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
71900 /* If there has been exactly one prior match and this match
71901 ** is for the right-hand table of a NATURAL JOIN or is in a
71902 ** USING clause, then skip this match.
71904 if( cnt==1 ){
71905 if( pItem->jointype & JT_NATURAL ) continue;
71906 if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
71908 cnt++;
71909 pExpr->iTable = pItem->iCursor;
71910 pExpr->pTab = pTab;
71911 pMatch = pItem;
71912 pSchema = pTab->pSchema;
71913 /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
71914 pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
71915 break;
71921 #ifndef SQLITE_OMIT_TRIGGER
71922 /* If we have not already resolved the name, then maybe
71923 ** it is a new.* or old.* trigger argument reference
71925 if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
71926 int op = pParse->eTriggerOp;
71927 Table *pTab = 0;
71928 assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
71929 if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
71930 pExpr->iTable = 1;
71931 pTab = pParse->pTriggerTab;
71932 }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
71933 pExpr->iTable = 0;
71934 pTab = pParse->pTriggerTab;
71937 if( pTab ){
71938 int iCol;
71939 pSchema = pTab->pSchema;
71940 cntTab++;
71941 for(iCol=0; iCol<pTab->nCol; iCol++){
71942 Column *pCol = &pTab->aCol[iCol];
71943 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
71944 if( iCol==pTab->iPKey ){
71945 iCol = -1;
71947 break;
71950 if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) ){
71951 iCol = -1; /* IMP: R-44911-55124 */
71953 if( iCol<pTab->nCol ){
71954 cnt++;
71955 if( iCol<0 ){
71956 pExpr->affinity = SQLITE_AFF_INTEGER;
71957 }else if( pExpr->iTable==0 ){
71958 testcase( iCol==31 );
71959 testcase( iCol==32 );
71960 pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
71961 }else{
71962 testcase( iCol==31 );
71963 testcase( iCol==32 );
71964 pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
71966 pExpr->iColumn = (i16)iCol;
71967 pExpr->pTab = pTab;
71968 isTrigger = 1;
71972 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
71975 ** Perhaps the name is a reference to the ROWID
71977 if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
71978 cnt = 1;
71979 pExpr->iColumn = -1; /* IMP: R-44911-55124 */
71980 pExpr->affinity = SQLITE_AFF_INTEGER;
71984 ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
71985 ** might refer to an result-set alias. This happens, for example, when
71986 ** we are resolving names in the WHERE clause of the following command:
71988 ** SELECT a+b AS x FROM table WHERE x<10;
71990 ** In cases like this, replace pExpr with a copy of the expression that
71991 ** forms the result set entry ("a+b" in the example) and return immediately.
71992 ** Note that the expression in the result set should have already been
71993 ** resolved by the time the WHERE clause is resolved.
71995 if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
71996 for(j=0; j<pEList->nExpr; j++){
71997 char *zAs = pEList->a[j].zName;
71998 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
71999 Expr *pOrig;
72000 assert( pExpr->pLeft==0 && pExpr->pRight==0 );
72001 assert( pExpr->x.pList==0 );
72002 assert( pExpr->x.pSelect==0 );
72003 pOrig = pEList->a[j].pExpr;
72004 if( !pNC->allowAgg && ExprHasProperty(pOrig, EP_Agg) ){
72005 sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
72006 return WRC_Abort;
72008 resolveAlias(pParse, pEList, j, pExpr, "");
72009 cnt = 1;
72010 pMatch = 0;
72011 assert( zTab==0 && zDb==0 );
72012 goto lookupname_end;
72017 /* Advance to the next name context. The loop will exit when either
72018 ** we have a match (cnt>0) or when we run out of name contexts.
72020 if( cnt==0 ){
72021 pNC = pNC->pNext;
72026 ** If X and Y are NULL (in other words if only the column name Z is
72027 ** supplied) and the value of Z is enclosed in double-quotes, then
72028 ** Z is a string literal if it doesn't match any column names. In that
72029 ** case, we need to return right away and not make any changes to
72030 ** pExpr.
72032 ** Because no reference was made to outer contexts, the pNC->nRef
72033 ** fields are not changed in any context.
72035 if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
72036 pExpr->op = TK_STRING;
72037 pExpr->pTab = 0;
72038 return WRC_Prune;
72042 ** cnt==0 means there was not match. cnt>1 means there were two or
72043 ** more matches. Either way, we have an error.
72045 if( cnt!=1 ){
72046 const char *zErr;
72047 zErr = cnt==0 ? "no such column" : "ambiguous column name";
72048 if( zDb ){
72049 sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
72050 }else if( zTab ){
72051 sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
72052 }else{
72053 sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
72055 pParse->checkSchema = 1;
72056 pTopNC->nErr++;
72059 /* If a column from a table in pSrcList is referenced, then record
72060 ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
72061 ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the
72062 ** column number is greater than the number of bits in the bitmask
72063 ** then set the high-order bit of the bitmask.
72065 if( pExpr->iColumn>=0 && pMatch!=0 ){
72066 int n = pExpr->iColumn;
72067 testcase( n==BMS-1 );
72068 if( n>=BMS ){
72069 n = BMS-1;
72071 assert( pMatch->iCursor==pExpr->iTable );
72072 pMatch->colUsed |= ((Bitmask)1)<<n;
72075 /* Clean up and return
72077 sqlite3ExprDelete(db, pExpr->pLeft);
72078 pExpr->pLeft = 0;
72079 sqlite3ExprDelete(db, pExpr->pRight);
72080 pExpr->pRight = 0;
72081 pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
72082 lookupname_end:
72083 if( cnt==1 ){
72084 assert( pNC!=0 );
72085 sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
72086 /* Increment the nRef value on all name contexts from TopNC up to
72087 ** the point where the name matched. */
72088 for(;;){
72089 assert( pTopNC!=0 );
72090 pTopNC->nRef++;
72091 if( pTopNC==pNC ) break;
72092 pTopNC = pTopNC->pNext;
72094 return WRC_Prune;
72095 } else {
72096 return WRC_Abort;
72101 ** Allocate and return a pointer to an expression to load the column iCol
72102 ** from datasource iSrc in SrcList pSrc.
72104 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
72105 Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
72106 if( p ){
72107 struct SrcList_item *pItem = &pSrc->a[iSrc];
72108 p->pTab = pItem->pTab;
72109 p->iTable = pItem->iCursor;
72110 if( p->pTab->iPKey==iCol ){
72111 p->iColumn = -1;
72112 }else{
72113 p->iColumn = (ynVar)iCol;
72114 testcase( iCol==BMS );
72115 testcase( iCol==BMS-1 );
72116 pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
72118 ExprSetProperty(p, EP_Resolved);
72120 return p;
72124 ** This routine is callback for sqlite3WalkExpr().
72126 ** Resolve symbolic names into TK_COLUMN operators for the current
72127 ** node in the expression tree. Return 0 to continue the search down
72128 ** the tree or 2 to abort the tree walk.
72130 ** This routine also does error checking and name resolution for
72131 ** function names. The operator for aggregate functions is changed
72132 ** to TK_AGG_FUNCTION.
72134 static int resolveExprStep(Walker *pWalker, Expr *pExpr){
72135 NameContext *pNC;
72136 Parse *pParse;
72138 pNC = pWalker->u.pNC;
72139 assert( pNC!=0 );
72140 pParse = pNC->pParse;
72141 assert( pParse==pWalker->pParse );
72143 if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
72144 ExprSetProperty(pExpr, EP_Resolved);
72145 #ifndef NDEBUG
72146 if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
72147 SrcList *pSrcList = pNC->pSrcList;
72148 int i;
72149 for(i=0; i<pNC->pSrcList->nSrc; i++){
72150 assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
72153 #endif
72154 switch( pExpr->op ){
72156 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
72157 /* The special operator TK_ROW means use the rowid for the first
72158 ** column in the FROM clause. This is used by the LIMIT and ORDER BY
72159 ** clause processing on UPDATE and DELETE statements.
72161 case TK_ROW: {
72162 SrcList *pSrcList = pNC->pSrcList;
72163 struct SrcList_item *pItem;
72164 assert( pSrcList && pSrcList->nSrc==1 );
72165 pItem = pSrcList->a;
72166 pExpr->op = TK_COLUMN;
72167 pExpr->pTab = pItem->pTab;
72168 pExpr->iTable = pItem->iCursor;
72169 pExpr->iColumn = -1;
72170 pExpr->affinity = SQLITE_AFF_INTEGER;
72171 break;
72173 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
72175 /* A lone identifier is the name of a column.
72177 case TK_ID: {
72178 return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
72181 /* A table name and column name: ID.ID
72182 ** Or a database, table and column: ID.ID.ID
72184 case TK_DOT: {
72185 const char *zColumn;
72186 const char *zTable;
72187 const char *zDb;
72188 Expr *pRight;
72190 /* if( pSrcList==0 ) break; */
72191 pRight = pExpr->pRight;
72192 if( pRight->op==TK_ID ){
72193 zDb = 0;
72194 zTable = pExpr->pLeft->u.zToken;
72195 zColumn = pRight->u.zToken;
72196 }else{
72197 assert( pRight->op==TK_DOT );
72198 zDb = pExpr->pLeft->u.zToken;
72199 zTable = pRight->pLeft->u.zToken;
72200 zColumn = pRight->pRight->u.zToken;
72202 return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
72205 /* Resolve function names
72207 case TK_CONST_FUNC:
72208 case TK_FUNCTION: {
72209 ExprList *pList = pExpr->x.pList; /* The argument list */
72210 int n = pList ? pList->nExpr : 0; /* Number of arguments */
72211 int no_such_func = 0; /* True if no such function exists */
72212 int wrong_num_args = 0; /* True if wrong number of arguments */
72213 int is_agg = 0; /* True if is an aggregate function */
72214 int auth; /* Authorization to use the function */
72215 int nId; /* Number of characters in function name */
72216 const char *zId; /* The function name. */
72217 FuncDef *pDef; /* Information about the function */
72218 u8 enc = ENC(pParse->db); /* The database encoding */
72220 testcase( pExpr->op==TK_CONST_FUNC );
72221 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
72222 zId = pExpr->u.zToken;
72223 nId = sqlite3Strlen30(zId);
72224 pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
72225 if( pDef==0 ){
72226 pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
72227 if( pDef==0 ){
72228 no_such_func = 1;
72229 }else{
72230 wrong_num_args = 1;
72232 }else{
72233 is_agg = pDef->xFunc==0;
72235 #ifndef SQLITE_OMIT_AUTHORIZATION
72236 if( pDef ){
72237 auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
72238 if( auth!=SQLITE_OK ){
72239 if( auth==SQLITE_DENY ){
72240 sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
72241 pDef->zName);
72242 pNC->nErr++;
72244 pExpr->op = TK_NULL;
72245 return WRC_Prune;
72248 #endif
72249 if( is_agg && !pNC->allowAgg ){
72250 sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
72251 pNC->nErr++;
72252 is_agg = 0;
72253 }else if( no_such_func ){
72254 sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
72255 pNC->nErr++;
72256 }else if( wrong_num_args ){
72257 sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
72258 nId, zId);
72259 pNC->nErr++;
72261 if( is_agg ){
72262 pExpr->op = TK_AGG_FUNCTION;
72263 pNC->hasAgg = 1;
72265 if( is_agg ) pNC->allowAgg = 0;
72266 sqlite3WalkExprList(pWalker, pList);
72267 if( is_agg ) pNC->allowAgg = 1;
72268 /* FIX ME: Compute pExpr->affinity based on the expected return
72269 ** type of the function
72271 return WRC_Prune;
72273 #ifndef SQLITE_OMIT_SUBQUERY
72274 case TK_SELECT:
72275 case TK_EXISTS: testcase( pExpr->op==TK_EXISTS );
72276 #endif
72277 case TK_IN: {
72278 testcase( pExpr->op==TK_IN );
72279 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
72280 int nRef = pNC->nRef;
72281 #ifndef SQLITE_OMIT_CHECK
72282 if( pNC->isCheck ){
72283 sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
72285 #endif
72286 sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
72287 assert( pNC->nRef>=nRef );
72288 if( nRef!=pNC->nRef ){
72289 ExprSetProperty(pExpr, EP_VarSelect);
72292 break;
72294 #ifndef SQLITE_OMIT_CHECK
72295 case TK_VARIABLE: {
72296 if( pNC->isCheck ){
72297 sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
72299 break;
72301 #endif
72303 return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
72307 ** pEList is a list of expressions which are really the result set of the
72308 ** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
72309 ** This routine checks to see if pE is a simple identifier which corresponds
72310 ** to the AS-name of one of the terms of the expression list. If it is,
72311 ** this routine return an integer between 1 and N where N is the number of
72312 ** elements in pEList, corresponding to the matching entry. If there is
72313 ** no match, or if pE is not a simple identifier, then this routine
72314 ** return 0.
72316 ** pEList has been resolved. pE has not.
72318 static int resolveAsName(
72319 Parse *pParse, /* Parsing context for error messages */
72320 ExprList *pEList, /* List of expressions to scan */
72321 Expr *pE /* Expression we are trying to match */
72323 int i; /* Loop counter */
72325 UNUSED_PARAMETER(pParse);
72327 if( pE->op==TK_ID ){
72328 char *zCol = pE->u.zToken;
72329 for(i=0; i<pEList->nExpr; i++){
72330 char *zAs = pEList->a[i].zName;
72331 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
72332 return i+1;
72336 return 0;
72340 ** pE is a pointer to an expression which is a single term in the
72341 ** ORDER BY of a compound SELECT. The expression has not been
72342 ** name resolved.
72344 ** At the point this routine is called, we already know that the
72345 ** ORDER BY term is not an integer index into the result set. That
72346 ** case is handled by the calling routine.
72348 ** Attempt to match pE against result set columns in the left-most
72349 ** SELECT statement. Return the index i of the matching column,
72350 ** as an indication to the caller that it should sort by the i-th column.
72351 ** The left-most column is 1. In other words, the value returned is the
72352 ** same integer value that would be used in the SQL statement to indicate
72353 ** the column.
72355 ** If there is no match, return 0. Return -1 if an error occurs.
72357 static int resolveOrderByTermToExprList(
72358 Parse *pParse, /* Parsing context for error messages */
72359 Select *pSelect, /* The SELECT statement with the ORDER BY clause */
72360 Expr *pE /* The specific ORDER BY term */
72362 int i; /* Loop counter */
72363 ExprList *pEList; /* The columns of the result set */
72364 NameContext nc; /* Name context for resolving pE */
72365 sqlite3 *db; /* Database connection */
72366 int rc; /* Return code from subprocedures */
72367 u8 savedSuppErr; /* Saved value of db->suppressErr */
72369 assert( sqlite3ExprIsInteger(pE, &i)==0 );
72370 pEList = pSelect->pEList;
72372 /* Resolve all names in the ORDER BY term expression
72374 memset(&nc, 0, sizeof(nc));
72375 nc.pParse = pParse;
72376 nc.pSrcList = pSelect->pSrc;
72377 nc.pEList = pEList;
72378 nc.allowAgg = 1;
72379 nc.nErr = 0;
72380 db = pParse->db;
72381 savedSuppErr = db->suppressErr;
72382 db->suppressErr = 1;
72383 rc = sqlite3ResolveExprNames(&nc, pE);
72384 db->suppressErr = savedSuppErr;
72385 if( rc ) return 0;
72387 /* Try to match the ORDER BY expression against an expression
72388 ** in the result set. Return an 1-based index of the matching
72389 ** result-set entry.
72391 for(i=0; i<pEList->nExpr; i++){
72392 if( sqlite3ExprCompare(pEList->a[i].pExpr, pE)<2 ){
72393 return i+1;
72397 /* If no match, return 0. */
72398 return 0;
72402 ** Generate an ORDER BY or GROUP BY term out-of-range error.
72404 static void resolveOutOfRangeError(
72405 Parse *pParse, /* The error context into which to write the error */
72406 const char *zType, /* "ORDER" or "GROUP" */
72407 int i, /* The index (1-based) of the term out of range */
72408 int mx /* Largest permissible value of i */
72410 sqlite3ErrorMsg(pParse,
72411 "%r %s BY term out of range - should be "
72412 "between 1 and %d", i, zType, mx);
72416 ** Analyze the ORDER BY clause in a compound SELECT statement. Modify
72417 ** each term of the ORDER BY clause is a constant integer between 1
72418 ** and N where N is the number of columns in the compound SELECT.
72420 ** ORDER BY terms that are already an integer between 1 and N are
72421 ** unmodified. ORDER BY terms that are integers outside the range of
72422 ** 1 through N generate an error. ORDER BY terms that are expressions
72423 ** are matched against result set expressions of compound SELECT
72424 ** beginning with the left-most SELECT and working toward the right.
72425 ** At the first match, the ORDER BY expression is transformed into
72426 ** the integer column number.
72428 ** Return the number of errors seen.
72430 static int resolveCompoundOrderBy(
72431 Parse *pParse, /* Parsing context. Leave error messages here */
72432 Select *pSelect /* The SELECT statement containing the ORDER BY */
72434 int i;
72435 ExprList *pOrderBy;
72436 ExprList *pEList;
72437 sqlite3 *db;
72438 int moreToDo = 1;
72440 pOrderBy = pSelect->pOrderBy;
72441 if( pOrderBy==0 ) return 0;
72442 db = pParse->db;
72443 #if SQLITE_MAX_COLUMN
72444 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
72445 sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
72446 return 1;
72448 #endif
72449 for(i=0; i<pOrderBy->nExpr; i++){
72450 pOrderBy->a[i].done = 0;
72452 pSelect->pNext = 0;
72453 while( pSelect->pPrior ){
72454 pSelect->pPrior->pNext = pSelect;
72455 pSelect = pSelect->pPrior;
72457 while( pSelect && moreToDo ){
72458 struct ExprList_item *pItem;
72459 moreToDo = 0;
72460 pEList = pSelect->pEList;
72461 assert( pEList!=0 );
72462 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
72463 int iCol = -1;
72464 Expr *pE, *pDup;
72465 if( pItem->done ) continue;
72466 pE = pItem->pExpr;
72467 if( sqlite3ExprIsInteger(pE, &iCol) ){
72468 if( iCol<=0 || iCol>pEList->nExpr ){
72469 resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
72470 return 1;
72472 }else{
72473 iCol = resolveAsName(pParse, pEList, pE);
72474 if( iCol==0 ){
72475 pDup = sqlite3ExprDup(db, pE, 0);
72476 if( !db->mallocFailed ){
72477 assert(pDup);
72478 iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
72480 sqlite3ExprDelete(db, pDup);
72483 if( iCol>0 ){
72484 CollSeq *pColl = pE->pColl;
72485 int flags = pE->flags & EP_ExpCollate;
72486 sqlite3ExprDelete(db, pE);
72487 pItem->pExpr = pE = sqlite3Expr(db, TK_INTEGER, 0);
72488 if( pE==0 ) return 1;
72489 pE->pColl = pColl;
72490 pE->flags |= EP_IntValue | flags;
72491 pE->u.iValue = iCol;
72492 pItem->iCol = (u16)iCol;
72493 pItem->done = 1;
72494 }else{
72495 moreToDo = 1;
72498 pSelect = pSelect->pNext;
72500 for(i=0; i<pOrderBy->nExpr; i++){
72501 if( pOrderBy->a[i].done==0 ){
72502 sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
72503 "column in the result set", i+1);
72504 return 1;
72507 return 0;
72511 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
72512 ** the SELECT statement pSelect. If any term is reference to a
72513 ** result set expression (as determined by the ExprList.a.iCol field)
72514 ** then convert that term into a copy of the corresponding result set
72515 ** column.
72517 ** If any errors are detected, add an error message to pParse and
72518 ** return non-zero. Return zero if no errors are seen.
72520 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
72521 Parse *pParse, /* Parsing context. Leave error messages here */
72522 Select *pSelect, /* The SELECT statement containing the clause */
72523 ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
72524 const char *zType /* "ORDER" or "GROUP" */
72526 int i;
72527 sqlite3 *db = pParse->db;
72528 ExprList *pEList;
72529 struct ExprList_item *pItem;
72531 if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
72532 #if SQLITE_MAX_COLUMN
72533 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
72534 sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
72535 return 1;
72537 #endif
72538 pEList = pSelect->pEList;
72539 assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
72540 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
72541 if( pItem->iCol ){
72542 if( pItem->iCol>pEList->nExpr ){
72543 resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
72544 return 1;
72546 resolveAlias(pParse, pEList, pItem->iCol-1, pItem->pExpr, zType);
72549 return 0;
72553 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
72554 ** The Name context of the SELECT statement is pNC. zType is either
72555 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
72557 ** This routine resolves each term of the clause into an expression.
72558 ** If the order-by term is an integer I between 1 and N (where N is the
72559 ** number of columns in the result set of the SELECT) then the expression
72560 ** in the resolution is a copy of the I-th result-set expression. If
72561 ** the order-by term is an identify that corresponds to the AS-name of
72562 ** a result-set expression, then the term resolves to a copy of the
72563 ** result-set expression. Otherwise, the expression is resolved in
72564 ** the usual way - using sqlite3ResolveExprNames().
72566 ** This routine returns the number of errors. If errors occur, then
72567 ** an appropriate error message might be left in pParse. (OOM errors
72568 ** excepted.)
72570 static int resolveOrderGroupBy(
72571 NameContext *pNC, /* The name context of the SELECT statement */
72572 Select *pSelect, /* The SELECT statement holding pOrderBy */
72573 ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
72574 const char *zType /* Either "ORDER" or "GROUP", as appropriate */
72576 int i; /* Loop counter */
72577 int iCol; /* Column number */
72578 struct ExprList_item *pItem; /* A term of the ORDER BY clause */
72579 Parse *pParse; /* Parsing context */
72580 int nResult; /* Number of terms in the result set */
72582 if( pOrderBy==0 ) return 0;
72583 nResult = pSelect->pEList->nExpr;
72584 pParse = pNC->pParse;
72585 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
72586 Expr *pE = pItem->pExpr;
72587 iCol = resolveAsName(pParse, pSelect->pEList, pE);
72588 if( iCol>0 ){
72589 /* If an AS-name match is found, mark this ORDER BY column as being
72590 ** a copy of the iCol-th result-set column. The subsequent call to
72591 ** sqlite3ResolveOrderGroupBy() will convert the expression to a
72592 ** copy of the iCol-th result-set expression. */
72593 pItem->iCol = (u16)iCol;
72594 continue;
72596 if( sqlite3ExprIsInteger(pE, &iCol) ){
72597 /* The ORDER BY term is an integer constant. Again, set the column
72598 ** number so that sqlite3ResolveOrderGroupBy() will convert the
72599 ** order-by term to a copy of the result-set expression */
72600 if( iCol<1 ){
72601 resolveOutOfRangeError(pParse, zType, i+1, nResult);
72602 return 1;
72604 pItem->iCol = (u16)iCol;
72605 continue;
72608 /* Otherwise, treat the ORDER BY term as an ordinary expression */
72609 pItem->iCol = 0;
72610 if( sqlite3ResolveExprNames(pNC, pE) ){
72611 return 1;
72614 return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
72618 ** Resolve names in the SELECT statement p and all of its descendents.
72620 static int resolveSelectStep(Walker *pWalker, Select *p){
72621 NameContext *pOuterNC; /* Context that contains this SELECT */
72622 NameContext sNC; /* Name context of this SELECT */
72623 int isCompound; /* True if p is a compound select */
72624 int nCompound; /* Number of compound terms processed so far */
72625 Parse *pParse; /* Parsing context */
72626 ExprList *pEList; /* Result set expression list */
72627 int i; /* Loop counter */
72628 ExprList *pGroupBy; /* The GROUP BY clause */
72629 Select *pLeftmost; /* Left-most of SELECT of a compound */
72630 sqlite3 *db; /* Database connection */
72633 assert( p!=0 );
72634 if( p->selFlags & SF_Resolved ){
72635 return WRC_Prune;
72637 pOuterNC = pWalker->u.pNC;
72638 pParse = pWalker->pParse;
72639 db = pParse->db;
72641 /* Normally sqlite3SelectExpand() will be called first and will have
72642 ** already expanded this SELECT. However, if this is a subquery within
72643 ** an expression, sqlite3ResolveExprNames() will be called without a
72644 ** prior call to sqlite3SelectExpand(). When that happens, let
72645 ** sqlite3SelectPrep() do all of the processing for this SELECT.
72646 ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
72647 ** this routine in the correct order.
72649 if( (p->selFlags & SF_Expanded)==0 ){
72650 sqlite3SelectPrep(pParse, p, pOuterNC);
72651 return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
72654 isCompound = p->pPrior!=0;
72655 nCompound = 0;
72656 pLeftmost = p;
72657 while( p ){
72658 assert( (p->selFlags & SF_Expanded)!=0 );
72659 assert( (p->selFlags & SF_Resolved)==0 );
72660 p->selFlags |= SF_Resolved;
72662 /* Resolve the expressions in the LIMIT and OFFSET clauses. These
72663 ** are not allowed to refer to any names, so pass an empty NameContext.
72665 memset(&sNC, 0, sizeof(sNC));
72666 sNC.pParse = pParse;
72667 if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
72668 sqlite3ResolveExprNames(&sNC, p->pOffset) ){
72669 return WRC_Abort;
72672 /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
72673 ** resolve the result-set expression list.
72675 sNC.allowAgg = 1;
72676 sNC.pSrcList = p->pSrc;
72677 sNC.pNext = pOuterNC;
72679 /* Resolve names in the result set. */
72680 pEList = p->pEList;
72681 assert( pEList!=0 );
72682 for(i=0; i<pEList->nExpr; i++){
72683 Expr *pX = pEList->a[i].pExpr;
72684 if( sqlite3ResolveExprNames(&sNC, pX) ){
72685 return WRC_Abort;
72689 /* Recursively resolve names in all subqueries
72691 for(i=0; i<p->pSrc->nSrc; i++){
72692 struct SrcList_item *pItem = &p->pSrc->a[i];
72693 if( pItem->pSelect ){
72694 NameContext *pNC; /* Used to iterate name contexts */
72695 int nRef = 0; /* Refcount for pOuterNC and outer contexts */
72696 const char *zSavedContext = pParse->zAuthContext;
72698 /* Count the total number of references to pOuterNC and all of its
72699 ** parent contexts. After resolving references to expressions in
72700 ** pItem->pSelect, check if this value has changed. If so, then
72701 ** SELECT statement pItem->pSelect must be correlated. Set the
72702 ** pItem->isCorrelated flag if this is the case. */
72703 for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
72705 if( pItem->zName ) pParse->zAuthContext = pItem->zName;
72706 sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
72707 pParse->zAuthContext = zSavedContext;
72708 if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
72710 for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
72711 assert( pItem->isCorrelated==0 && nRef<=0 );
72712 pItem->isCorrelated = (nRef!=0);
72716 /* If there are no aggregate functions in the result-set, and no GROUP BY
72717 ** expression, do not allow aggregates in any of the other expressions.
72719 assert( (p->selFlags & SF_Aggregate)==0 );
72720 pGroupBy = p->pGroupBy;
72721 if( pGroupBy || sNC.hasAgg ){
72722 p->selFlags |= SF_Aggregate;
72723 }else{
72724 sNC.allowAgg = 0;
72727 /* If a HAVING clause is present, then there must be a GROUP BY clause.
72729 if( p->pHaving && !pGroupBy ){
72730 sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
72731 return WRC_Abort;
72734 /* Add the expression list to the name-context before parsing the
72735 ** other expressions in the SELECT statement. This is so that
72736 ** expressions in the WHERE clause (etc.) can refer to expressions by
72737 ** aliases in the result set.
72739 ** Minor point: If this is the case, then the expression will be
72740 ** re-evaluated for each reference to it.
72742 sNC.pEList = p->pEList;
72743 if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
72744 sqlite3ResolveExprNames(&sNC, p->pHaving)
72746 return WRC_Abort;
72749 /* The ORDER BY and GROUP BY clauses may not refer to terms in
72750 ** outer queries
72752 sNC.pNext = 0;
72753 sNC.allowAgg = 1;
72755 /* Process the ORDER BY clause for singleton SELECT statements.
72756 ** The ORDER BY clause for compounds SELECT statements is handled
72757 ** below, after all of the result-sets for all of the elements of
72758 ** the compound have been resolved.
72760 if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
72761 return WRC_Abort;
72763 if( db->mallocFailed ){
72764 return WRC_Abort;
72767 /* Resolve the GROUP BY clause. At the same time, make sure
72768 ** the GROUP BY clause does not contain aggregate functions.
72770 if( pGroupBy ){
72771 struct ExprList_item *pItem;
72773 if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
72774 return WRC_Abort;
72776 for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
72777 if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
72778 sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
72779 "the GROUP BY clause");
72780 return WRC_Abort;
72785 /* Advance to the next term of the compound
72787 p = p->pPrior;
72788 nCompound++;
72791 /* Resolve the ORDER BY on a compound SELECT after all terms of
72792 ** the compound have been resolved.
72794 if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
72795 return WRC_Abort;
72798 return WRC_Prune;
72802 ** This routine walks an expression tree and resolves references to
72803 ** table columns and result-set columns. At the same time, do error
72804 ** checking on function usage and set a flag if any aggregate functions
72805 ** are seen.
72807 ** To resolve table columns references we look for nodes (or subtrees) of the
72808 ** form X.Y.Z or Y.Z or just Z where
72810 ** X: The name of a database. Ex: "main" or "temp" or
72811 ** the symbolic name assigned to an ATTACH-ed database.
72813 ** Y: The name of a table in a FROM clause. Or in a trigger
72814 ** one of the special names "old" or "new".
72816 ** Z: The name of a column in table Y.
72818 ** The node at the root of the subtree is modified as follows:
72820 ** Expr.op Changed to TK_COLUMN
72821 ** Expr.pTab Points to the Table object for X.Y
72822 ** Expr.iColumn The column index in X.Y. -1 for the rowid.
72823 ** Expr.iTable The VDBE cursor number for X.Y
72826 ** To resolve result-set references, look for expression nodes of the
72827 ** form Z (with no X and Y prefix) where the Z matches the right-hand
72828 ** size of an AS clause in the result-set of a SELECT. The Z expression
72829 ** is replaced by a copy of the left-hand side of the result-set expression.
72830 ** Table-name and function resolution occurs on the substituted expression
72831 ** tree. For example, in:
72833 ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
72835 ** The "x" term of the order by is replaced by "a+b" to render:
72837 ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
72839 ** Function calls are checked to make sure that the function is
72840 ** defined and that the correct number of arguments are specified.
72841 ** If the function is an aggregate function, then the pNC->hasAgg is
72842 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
72843 ** If an expression contains aggregate functions then the EP_Agg
72844 ** property on the expression is set.
72846 ** An error message is left in pParse if anything is amiss. The number
72847 ** if errors is returned.
72849 SQLITE_PRIVATE int sqlite3ResolveExprNames(
72850 NameContext *pNC, /* Namespace to resolve expressions in. */
72851 Expr *pExpr /* The expression to be analyzed. */
72853 int savedHasAgg;
72854 Walker w;
72856 if( pExpr==0 ) return 0;
72857 #if SQLITE_MAX_EXPR_DEPTH>0
72859 Parse *pParse = pNC->pParse;
72860 if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
72861 return 1;
72863 pParse->nHeight += pExpr->nHeight;
72865 #endif
72866 savedHasAgg = pNC->hasAgg;
72867 pNC->hasAgg = 0;
72868 w.xExprCallback = resolveExprStep;
72869 w.xSelectCallback = resolveSelectStep;
72870 w.pParse = pNC->pParse;
72871 w.u.pNC = pNC;
72872 sqlite3WalkExpr(&w, pExpr);
72873 #if SQLITE_MAX_EXPR_DEPTH>0
72874 pNC->pParse->nHeight -= pExpr->nHeight;
72875 #endif
72876 if( pNC->nErr>0 || w.pParse->nErr>0 ){
72877 ExprSetProperty(pExpr, EP_Error);
72879 if( pNC->hasAgg ){
72880 ExprSetProperty(pExpr, EP_Agg);
72881 }else if( savedHasAgg ){
72882 pNC->hasAgg = 1;
72884 return ExprHasProperty(pExpr, EP_Error);
72889 ** Resolve all names in all expressions of a SELECT and in all
72890 ** decendents of the SELECT, including compounds off of p->pPrior,
72891 ** subqueries in expressions, and subqueries used as FROM clause
72892 ** terms.
72894 ** See sqlite3ResolveExprNames() for a description of the kinds of
72895 ** transformations that occur.
72897 ** All SELECT statements should have been expanded using
72898 ** sqlite3SelectExpand() prior to invoking this routine.
72900 SQLITE_PRIVATE void sqlite3ResolveSelectNames(
72901 Parse *pParse, /* The parser context */
72902 Select *p, /* The SELECT statement being coded. */
72903 NameContext *pOuterNC /* Name context for parent SELECT statement */
72905 Walker w;
72907 assert( p!=0 );
72908 w.xExprCallback = resolveExprStep;
72909 w.xSelectCallback = resolveSelectStep;
72910 w.pParse = pParse;
72911 w.u.pNC = pOuterNC;
72912 sqlite3WalkSelect(&w, p);
72915 /************** End of resolve.c *********************************************/
72916 /************** Begin file expr.c ********************************************/
72918 ** 2001 September 15
72920 ** The author disclaims copyright to this source code. In place of
72921 ** a legal notice, here is a blessing:
72923 ** May you do good and not evil.
72924 ** May you find forgiveness for yourself and forgive others.
72925 ** May you share freely, never taking more than you give.
72927 *************************************************************************
72928 ** This file contains routines used for analyzing expressions and
72929 ** for generating VDBE code that evaluates expressions in SQLite.
72933 ** Return the 'affinity' of the expression pExpr if any.
72935 ** If pExpr is a column, a reference to a column via an 'AS' alias,
72936 ** or a sub-select with a column as the return value, then the
72937 ** affinity of that column is returned. Otherwise, 0x00 is returned,
72938 ** indicating no affinity for the expression.
72940 ** i.e. the WHERE clause expresssions in the following statements all
72941 ** have an affinity:
72943 ** CREATE TABLE t1(a);
72944 ** SELECT * FROM t1 WHERE a;
72945 ** SELECT a AS b FROM t1 WHERE b;
72946 ** SELECT * FROM t1 WHERE (select a from t1);
72948 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
72949 int op = pExpr->op;
72950 if( op==TK_SELECT ){
72951 assert( pExpr->flags&EP_xIsSelect );
72952 return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
72954 #ifndef SQLITE_OMIT_CAST
72955 if( op==TK_CAST ){
72956 assert( !ExprHasProperty(pExpr, EP_IntValue) );
72957 return sqlite3AffinityType(pExpr->u.zToken);
72959 #endif
72960 if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER)
72961 && pExpr->pTab!=0
72963 /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
72964 ** a TK_COLUMN but was previously evaluated and cached in a register */
72965 int j = pExpr->iColumn;
72966 if( j<0 ) return SQLITE_AFF_INTEGER;
72967 assert( pExpr->pTab && j<pExpr->pTab->nCol );
72968 return pExpr->pTab->aCol[j].affinity;
72970 return pExpr->affinity;
72974 ** Set the explicit collating sequence for an expression to the
72975 ** collating sequence supplied in the second argument.
72977 SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Expr *pExpr, CollSeq *pColl){
72978 if( pExpr && pColl ){
72979 pExpr->pColl = pColl;
72980 pExpr->flags |= EP_ExpCollate;
72982 return pExpr;
72986 ** Set the collating sequence for expression pExpr to be the collating
72987 ** sequence named by pToken. Return a pointer to the revised expression.
72988 ** The collating sequence is marked as "explicit" using the EP_ExpCollate
72989 ** flag. An explicit collating sequence will override implicit
72990 ** collating sequences.
72992 SQLITE_PRIVATE Expr *sqlite3ExprSetCollByToken(Parse *pParse, Expr *pExpr, Token *pCollName){
72993 char *zColl = 0; /* Dequoted name of collation sequence */
72994 CollSeq *pColl;
72995 sqlite3 *db = pParse->db;
72996 zColl = sqlite3NameFromToken(db, pCollName);
72997 pColl = sqlite3LocateCollSeq(pParse, zColl);
72998 sqlite3ExprSetColl(pExpr, pColl);
72999 sqlite3DbFree(db, zColl);
73000 return pExpr;
73004 ** Return the default collation sequence for the expression pExpr. If
73005 ** there is no default collation type, return 0.
73007 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
73008 CollSeq *pColl = 0;
73009 Expr *p = pExpr;
73010 while( p ){
73011 int op;
73012 pColl = p->pColl;
73013 if( pColl ) break;
73014 op = p->op;
73015 if( p->pTab!=0 && (
73016 op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER || op==TK_TRIGGER
73018 /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
73019 ** a TK_COLUMN but was previously evaluated and cached in a register */
73020 const char *zColl;
73021 int j = p->iColumn;
73022 if( j>=0 ){
73023 sqlite3 *db = pParse->db;
73024 zColl = p->pTab->aCol[j].zColl;
73025 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
73026 pExpr->pColl = pColl;
73028 break;
73030 if( op!=TK_CAST && op!=TK_UPLUS ){
73031 break;
73033 p = p->pLeft;
73035 if( sqlite3CheckCollSeq(pParse, pColl) ){
73036 pColl = 0;
73038 return pColl;
73042 ** pExpr is an operand of a comparison operator. aff2 is the
73043 ** type affinity of the other operand. This routine returns the
73044 ** type affinity that should be used for the comparison operator.
73046 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
73047 char aff1 = sqlite3ExprAffinity(pExpr);
73048 if( aff1 && aff2 ){
73049 /* Both sides of the comparison are columns. If one has numeric
73050 ** affinity, use that. Otherwise use no affinity.
73052 if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
73053 return SQLITE_AFF_NUMERIC;
73054 }else{
73055 return SQLITE_AFF_NONE;
73057 }else if( !aff1 && !aff2 ){
73058 /* Neither side of the comparison is a column. Compare the
73059 ** results directly.
73061 return SQLITE_AFF_NONE;
73062 }else{
73063 /* One side is a column, the other is not. Use the columns affinity. */
73064 assert( aff1==0 || aff2==0 );
73065 return (aff1 + aff2);
73070 ** pExpr is a comparison operator. Return the type affinity that should
73071 ** be applied to both operands prior to doing the comparison.
73073 static char comparisonAffinity(Expr *pExpr){
73074 char aff;
73075 assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
73076 pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
73077 pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
73078 assert( pExpr->pLeft );
73079 aff = sqlite3ExprAffinity(pExpr->pLeft);
73080 if( pExpr->pRight ){
73081 aff = sqlite3CompareAffinity(pExpr->pRight, aff);
73082 }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
73083 aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
73084 }else if( !aff ){
73085 aff = SQLITE_AFF_NONE;
73087 return aff;
73091 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
73092 ** idx_affinity is the affinity of an indexed column. Return true
73093 ** if the index with affinity idx_affinity may be used to implement
73094 ** the comparison in pExpr.
73096 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
73097 char aff = comparisonAffinity(pExpr);
73098 switch( aff ){
73099 case SQLITE_AFF_NONE:
73100 return 1;
73101 case SQLITE_AFF_TEXT:
73102 return idx_affinity==SQLITE_AFF_TEXT;
73103 default:
73104 return sqlite3IsNumericAffinity(idx_affinity);
73109 ** Return the P5 value that should be used for a binary comparison
73110 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
73112 static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
73113 u8 aff = (char)sqlite3ExprAffinity(pExpr2);
73114 aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
73115 return aff;
73119 ** Return a pointer to the collation sequence that should be used by
73120 ** a binary comparison operator comparing pLeft and pRight.
73122 ** If the left hand expression has a collating sequence type, then it is
73123 ** used. Otherwise the collation sequence for the right hand expression
73124 ** is used, or the default (BINARY) if neither expression has a collating
73125 ** type.
73127 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
73128 ** it is not considered.
73130 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
73131 Parse *pParse,
73132 Expr *pLeft,
73133 Expr *pRight
73135 CollSeq *pColl;
73136 assert( pLeft );
73137 if( pLeft->flags & EP_ExpCollate ){
73138 assert( pLeft->pColl );
73139 pColl = pLeft->pColl;
73140 }else if( pRight && pRight->flags & EP_ExpCollate ){
73141 assert( pRight->pColl );
73142 pColl = pRight->pColl;
73143 }else{
73144 pColl = sqlite3ExprCollSeq(pParse, pLeft);
73145 if( !pColl ){
73146 pColl = sqlite3ExprCollSeq(pParse, pRight);
73149 return pColl;
73153 ** Generate code for a comparison operator.
73155 static int codeCompare(
73156 Parse *pParse, /* The parsing (and code generating) context */
73157 Expr *pLeft, /* The left operand */
73158 Expr *pRight, /* The right operand */
73159 int opcode, /* The comparison opcode */
73160 int in1, int in2, /* Register holding operands */
73161 int dest, /* Jump here if true. */
73162 int jumpIfNull /* If true, jump if either operand is NULL */
73164 int p5;
73165 int addr;
73166 CollSeq *p4;
73168 p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
73169 p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
73170 addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
73171 (void*)p4, P4_COLLSEQ);
73172 sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
73173 return addr;
73176 #if SQLITE_MAX_EXPR_DEPTH>0
73178 ** Check that argument nHeight is less than or equal to the maximum
73179 ** expression depth allowed. If it is not, leave an error message in
73180 ** pParse.
73182 SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
73183 int rc = SQLITE_OK;
73184 int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
73185 if( nHeight>mxHeight ){
73186 sqlite3ErrorMsg(pParse,
73187 "Expression tree is too large (maximum depth %d)", mxHeight
73189 rc = SQLITE_ERROR;
73191 return rc;
73194 /* The following three functions, heightOfExpr(), heightOfExprList()
73195 ** and heightOfSelect(), are used to determine the maximum height
73196 ** of any expression tree referenced by the structure passed as the
73197 ** first argument.
73199 ** If this maximum height is greater than the current value pointed
73200 ** to by pnHeight, the second parameter, then set *pnHeight to that
73201 ** value.
73203 static void heightOfExpr(Expr *p, int *pnHeight){
73204 if( p ){
73205 if( p->nHeight>*pnHeight ){
73206 *pnHeight = p->nHeight;
73210 static void heightOfExprList(ExprList *p, int *pnHeight){
73211 if( p ){
73212 int i;
73213 for(i=0; i<p->nExpr; i++){
73214 heightOfExpr(p->a[i].pExpr, pnHeight);
73218 static void heightOfSelect(Select *p, int *pnHeight){
73219 if( p ){
73220 heightOfExpr(p->pWhere, pnHeight);
73221 heightOfExpr(p->pHaving, pnHeight);
73222 heightOfExpr(p->pLimit, pnHeight);
73223 heightOfExpr(p->pOffset, pnHeight);
73224 heightOfExprList(p->pEList, pnHeight);
73225 heightOfExprList(p->pGroupBy, pnHeight);
73226 heightOfExprList(p->pOrderBy, pnHeight);
73227 heightOfSelect(p->pPrior, pnHeight);
73232 ** Set the Expr.nHeight variable in the structure passed as an
73233 ** argument. An expression with no children, Expr.pList or
73234 ** Expr.pSelect member has a height of 1. Any other expression
73235 ** has a height equal to the maximum height of any other
73236 ** referenced Expr plus one.
73238 static void exprSetHeight(Expr *p){
73239 int nHeight = 0;
73240 heightOfExpr(p->pLeft, &nHeight);
73241 heightOfExpr(p->pRight, &nHeight);
73242 if( ExprHasProperty(p, EP_xIsSelect) ){
73243 heightOfSelect(p->x.pSelect, &nHeight);
73244 }else{
73245 heightOfExprList(p->x.pList, &nHeight);
73247 p->nHeight = nHeight + 1;
73251 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
73252 ** the height is greater than the maximum allowed expression depth,
73253 ** leave an error in pParse.
73255 SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
73256 exprSetHeight(p);
73257 sqlite3ExprCheckHeight(pParse, p->nHeight);
73261 ** Return the maximum height of any expression tree referenced
73262 ** by the select statement passed as an argument.
73264 SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
73265 int nHeight = 0;
73266 heightOfSelect(p, &nHeight);
73267 return nHeight;
73269 #else
73270 #define exprSetHeight(y)
73271 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
73274 ** This routine is the core allocator for Expr nodes.
73276 ** Construct a new expression node and return a pointer to it. Memory
73277 ** for this node and for the pToken argument is a single allocation
73278 ** obtained from sqlite3DbMalloc(). The calling function
73279 ** is responsible for making sure the node eventually gets freed.
73281 ** If dequote is true, then the token (if it exists) is dequoted.
73282 ** If dequote is false, no dequoting is performance. The deQuote
73283 ** parameter is ignored if pToken is NULL or if the token does not
73284 ** appear to be quoted. If the quotes were of the form "..." (double-quotes)
73285 ** then the EP_DblQuoted flag is set on the expression node.
73287 ** Special case: If op==TK_INTEGER and pToken points to a string that
73288 ** can be translated into a 32-bit integer, then the token is not
73289 ** stored in u.zToken. Instead, the integer values is written
73290 ** into u.iValue and the EP_IntValue flag is set. No extra storage
73291 ** is allocated to hold the integer text and the dequote flag is ignored.
73293 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
73294 sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
73295 int op, /* Expression opcode */
73296 const Token *pToken, /* Token argument. Might be NULL */
73297 int dequote /* True to dequote */
73299 Expr *pNew;
73300 int nExtra = 0;
73301 int iValue = 0;
73303 if( pToken ){
73304 if( op!=TK_INTEGER || pToken->z==0
73305 || sqlite3GetInt32(pToken->z, &iValue)==0 ){
73306 nExtra = pToken->n+1;
73307 assert( iValue>=0 );
73310 pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
73311 if( pNew ){
73312 pNew->op = (u8)op;
73313 pNew->iAgg = -1;
73314 if( pToken ){
73315 if( nExtra==0 ){
73316 pNew->flags |= EP_IntValue;
73317 pNew->u.iValue = iValue;
73318 }else{
73319 int c;
73320 pNew->u.zToken = (char*)&pNew[1];
73321 assert( pToken->z!=0 || pToken->n==0 );
73322 if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
73323 pNew->u.zToken[pToken->n] = 0;
73324 if( dequote && nExtra>=3
73325 && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
73326 sqlite3Dequote(pNew->u.zToken);
73327 if( c=='"' ) pNew->flags |= EP_DblQuoted;
73331 #if SQLITE_MAX_EXPR_DEPTH>0
73332 pNew->nHeight = 1;
73333 #endif
73335 return pNew;
73339 ** Allocate a new expression node from a zero-terminated token that has
73340 ** already been dequoted.
73342 SQLITE_PRIVATE Expr *sqlite3Expr(
73343 sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
73344 int op, /* Expression opcode */
73345 const char *zToken /* Token argument. Might be NULL */
73347 Token x;
73348 x.z = zToken;
73349 x.n = zToken ? sqlite3Strlen30(zToken) : 0;
73350 return sqlite3ExprAlloc(db, op, &x, 0);
73354 ** Attach subtrees pLeft and pRight to the Expr node pRoot.
73356 ** If pRoot==NULL that means that a memory allocation error has occurred.
73357 ** In that case, delete the subtrees pLeft and pRight.
73359 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
73360 sqlite3 *db,
73361 Expr *pRoot,
73362 Expr *pLeft,
73363 Expr *pRight
73365 if( pRoot==0 ){
73366 assert( db->mallocFailed );
73367 sqlite3ExprDelete(db, pLeft);
73368 sqlite3ExprDelete(db, pRight);
73369 }else{
73370 if( pRight ){
73371 pRoot->pRight = pRight;
73372 if( pRight->flags & EP_ExpCollate ){
73373 pRoot->flags |= EP_ExpCollate;
73374 pRoot->pColl = pRight->pColl;
73377 if( pLeft ){
73378 pRoot->pLeft = pLeft;
73379 if( pLeft->flags & EP_ExpCollate ){
73380 pRoot->flags |= EP_ExpCollate;
73381 pRoot->pColl = pLeft->pColl;
73384 exprSetHeight(pRoot);
73389 ** Allocate a Expr node which joins as many as two subtrees.
73391 ** One or both of the subtrees can be NULL. Return a pointer to the new
73392 ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
73393 ** free the subtrees and return NULL.
73395 SQLITE_PRIVATE Expr *sqlite3PExpr(
73396 Parse *pParse, /* Parsing context */
73397 int op, /* Expression opcode */
73398 Expr *pLeft, /* Left operand */
73399 Expr *pRight, /* Right operand */
73400 const Token *pToken /* Argument token */
73402 Expr *p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
73403 sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
73404 if( p ) {
73405 sqlite3ExprCheckHeight(pParse, p->nHeight);
73407 return p;
73411 ** Join two expressions using an AND operator. If either expression is
73412 ** NULL, then just return the other expression.
73414 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
73415 if( pLeft==0 ){
73416 return pRight;
73417 }else if( pRight==0 ){
73418 return pLeft;
73419 }else{
73420 Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
73421 sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
73422 return pNew;
73427 ** Construct a new expression node for a function with multiple
73428 ** arguments.
73430 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
73431 Expr *pNew;
73432 sqlite3 *db = pParse->db;
73433 assert( pToken );
73434 pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
73435 if( pNew==0 ){
73436 sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
73437 return 0;
73439 pNew->x.pList = pList;
73440 assert( !ExprHasProperty(pNew, EP_xIsSelect) );
73441 sqlite3ExprSetHeight(pParse, pNew);
73442 return pNew;
73446 ** Assign a variable number to an expression that encodes a wildcard
73447 ** in the original SQL statement.
73449 ** Wildcards consisting of a single "?" are assigned the next sequential
73450 ** variable number.
73452 ** Wildcards of the form "?nnn" are assigned the number "nnn". We make
73453 ** sure "nnn" is not too be to avoid a denial of service attack when
73454 ** the SQL statement comes from an external source.
73456 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
73457 ** as the previous instance of the same wildcard. Or if this is the first
73458 ** instance of the wildcard, the next sequenial variable number is
73459 ** assigned.
73461 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
73462 sqlite3 *db = pParse->db;
73463 const char *z;
73465 if( pExpr==0 ) return;
73466 assert( !ExprHasAnyProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
73467 z = pExpr->u.zToken;
73468 assert( z!=0 );
73469 assert( z[0]!=0 );
73470 if( z[1]==0 ){
73471 /* Wildcard of the form "?". Assign the next variable number */
73472 assert( z[0]=='?' );
73473 pExpr->iColumn = (ynVar)(++pParse->nVar);
73474 }else{
73475 ynVar x = 0;
73476 u32 n = sqlite3Strlen30(z);
73477 if( z[0]=='?' ){
73478 /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
73479 ** use it as the variable number */
73480 i64 i;
73481 int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
73482 pExpr->iColumn = x = (ynVar)i;
73483 testcase( i==0 );
73484 testcase( i==1 );
73485 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
73486 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
73487 if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
73488 sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
73489 db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
73490 x = 0;
73492 if( i>pParse->nVar ){
73493 pParse->nVar = (int)i;
73495 }else{
73496 /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
73497 ** number as the prior appearance of the same name, or if the name
73498 ** has never appeared before, reuse the same variable number
73500 ynVar i;
73501 for(i=0; i<pParse->nzVar; i++){
73502 if( pParse->azVar[i] && memcmp(pParse->azVar[i],z,n+1)==0 ){
73503 pExpr->iColumn = x = (ynVar)i+1;
73504 break;
73507 if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
73509 if( x>0 ){
73510 if( x>pParse->nzVar ){
73511 char **a;
73512 a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
73513 if( a==0 ) return; /* Error reported through db->mallocFailed */
73514 pParse->azVar = a;
73515 memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
73516 pParse->nzVar = x;
73518 if( z[0]!='?' || pParse->azVar[x-1]==0 ){
73519 sqlite3DbFree(db, pParse->azVar[x-1]);
73520 pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
73524 if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
73525 sqlite3ErrorMsg(pParse, "too many SQL variables");
73530 ** Recursively delete an expression tree.
73532 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
73533 if( p==0 ) return;
73534 /* Sanity check: Assert that the IntValue is non-negative if it exists */
73535 assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
73536 if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
73537 sqlite3ExprDelete(db, p->pLeft);
73538 sqlite3ExprDelete(db, p->pRight);
73539 if( !ExprHasProperty(p, EP_Reduced) && (p->flags2 & EP2_MallocedToken)!=0 ){
73540 sqlite3DbFree(db, p->u.zToken);
73542 if( ExprHasProperty(p, EP_xIsSelect) ){
73543 sqlite3SelectDelete(db, p->x.pSelect);
73544 }else{
73545 sqlite3ExprListDelete(db, p->x.pList);
73548 if( !ExprHasProperty(p, EP_Static) ){
73549 sqlite3DbFree(db, p);
73554 ** Return the number of bytes allocated for the expression structure
73555 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
73556 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
73558 static int exprStructSize(Expr *p){
73559 if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
73560 if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
73561 return EXPR_FULLSIZE;
73565 ** The dupedExpr*Size() routines each return the number of bytes required
73566 ** to store a copy of an expression or expression tree. They differ in
73567 ** how much of the tree is measured.
73569 ** dupedExprStructSize() Size of only the Expr structure
73570 ** dupedExprNodeSize() Size of Expr + space for token
73571 ** dupedExprSize() Expr + token + subtree components
73573 ***************************************************************************
73575 ** The dupedExprStructSize() function returns two values OR-ed together:
73576 ** (1) the space required for a copy of the Expr structure only and
73577 ** (2) the EP_xxx flags that indicate what the structure size should be.
73578 ** The return values is always one of:
73580 ** EXPR_FULLSIZE
73581 ** EXPR_REDUCEDSIZE | EP_Reduced
73582 ** EXPR_TOKENONLYSIZE | EP_TokenOnly
73584 ** The size of the structure can be found by masking the return value
73585 ** of this routine with 0xfff. The flags can be found by masking the
73586 ** return value with EP_Reduced|EP_TokenOnly.
73588 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
73589 ** (unreduced) Expr objects as they or originally constructed by the parser.
73590 ** During expression analysis, extra information is computed and moved into
73591 ** later parts of teh Expr object and that extra information might get chopped
73592 ** off if the expression is reduced. Note also that it does not work to
73593 ** make a EXPRDUP_REDUCE copy of a reduced expression. It is only legal
73594 ** to reduce a pristine expression tree from the parser. The implementation
73595 ** of dupedExprStructSize() contain multiple assert() statements that attempt
73596 ** to enforce this constraint.
73598 static int dupedExprStructSize(Expr *p, int flags){
73599 int nSize;
73600 assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
73601 if( 0==(flags&EXPRDUP_REDUCE) ){
73602 nSize = EXPR_FULLSIZE;
73603 }else{
73604 assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
73605 assert( !ExprHasProperty(p, EP_FromJoin) );
73606 assert( (p->flags2 & EP2_MallocedToken)==0 );
73607 assert( (p->flags2 & EP2_Irreducible)==0 );
73608 if( p->pLeft || p->pRight || p->pColl || p->x.pList ){
73609 nSize = EXPR_REDUCEDSIZE | EP_Reduced;
73610 }else{
73611 nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
73614 return nSize;
73618 ** This function returns the space in bytes required to store the copy
73619 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
73620 ** string is defined.)
73622 static int dupedExprNodeSize(Expr *p, int flags){
73623 int nByte = dupedExprStructSize(p, flags) & 0xfff;
73624 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
73625 nByte += sqlite3Strlen30(p->u.zToken)+1;
73627 return ROUND8(nByte);
73631 ** Return the number of bytes required to create a duplicate of the
73632 ** expression passed as the first argument. The second argument is a
73633 ** mask containing EXPRDUP_XXX flags.
73635 ** The value returned includes space to create a copy of the Expr struct
73636 ** itself and the buffer referred to by Expr.u.zToken, if any.
73638 ** If the EXPRDUP_REDUCE flag is set, then the return value includes
73639 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
73640 ** and Expr.pRight variables (but not for any structures pointed to or
73641 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
73643 static int dupedExprSize(Expr *p, int flags){
73644 int nByte = 0;
73645 if( p ){
73646 nByte = dupedExprNodeSize(p, flags);
73647 if( flags&EXPRDUP_REDUCE ){
73648 nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
73651 return nByte;
73655 ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
73656 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
73657 ** to store the copy of expression p, the copies of p->u.zToken
73658 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
73659 ** if any. Before returning, *pzBuffer is set to the first byte passed the
73660 ** portion of the buffer copied into by this function.
73662 static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
73663 Expr *pNew = 0; /* Value to return */
73664 if( p ){
73665 const int isReduced = (flags&EXPRDUP_REDUCE);
73666 u8 *zAlloc;
73667 u32 staticFlag = 0;
73669 assert( pzBuffer==0 || isReduced );
73671 /* Figure out where to write the new Expr structure. */
73672 if( pzBuffer ){
73673 zAlloc = *pzBuffer;
73674 staticFlag = EP_Static;
73675 }else{
73676 zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
73678 pNew = (Expr *)zAlloc;
73680 if( pNew ){
73681 /* Set nNewSize to the size allocated for the structure pointed to
73682 ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
73683 ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
73684 ** by the copy of the p->u.zToken string (if any).
73686 const unsigned nStructSize = dupedExprStructSize(p, flags);
73687 const int nNewSize = nStructSize & 0xfff;
73688 int nToken;
73689 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
73690 nToken = sqlite3Strlen30(p->u.zToken) + 1;
73691 }else{
73692 nToken = 0;
73694 if( isReduced ){
73695 assert( ExprHasProperty(p, EP_Reduced)==0 );
73696 memcpy(zAlloc, p, nNewSize);
73697 }else{
73698 int nSize = exprStructSize(p);
73699 memcpy(zAlloc, p, nSize);
73700 memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
73703 /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
73704 pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static);
73705 pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
73706 pNew->flags |= staticFlag;
73708 /* Copy the p->u.zToken string, if any. */
73709 if( nToken ){
73710 char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
73711 memcpy(zToken, p->u.zToken, nToken);
73714 if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
73715 /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
73716 if( ExprHasProperty(p, EP_xIsSelect) ){
73717 pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
73718 }else{
73719 pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
73723 /* Fill in pNew->pLeft and pNew->pRight. */
73724 if( ExprHasAnyProperty(pNew, EP_Reduced|EP_TokenOnly) ){
73725 zAlloc += dupedExprNodeSize(p, flags);
73726 if( ExprHasProperty(pNew, EP_Reduced) ){
73727 pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
73728 pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
73730 if( pzBuffer ){
73731 *pzBuffer = zAlloc;
73733 }else{
73734 pNew->flags2 = 0;
73735 if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
73736 pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
73737 pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
73743 return pNew;
73747 ** The following group of routines make deep copies of expressions,
73748 ** expression lists, ID lists, and select statements. The copies can
73749 ** be deleted (by being passed to their respective ...Delete() routines)
73750 ** without effecting the originals.
73752 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
73753 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
73754 ** by subsequent calls to sqlite*ListAppend() routines.
73756 ** Any tables that the SrcList might point to are not duplicated.
73758 ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
73759 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
73760 ** truncated version of the usual Expr structure that will be stored as
73761 ** part of the in-memory representation of the database schema.
73763 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
73764 return exprDup(db, p, flags, 0);
73766 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
73767 ExprList *pNew;
73768 struct ExprList_item *pItem, *pOldItem;
73769 int i;
73770 if( p==0 ) return 0;
73771 pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
73772 if( pNew==0 ) return 0;
73773 pNew->iECursor = 0;
73774 pNew->nExpr = pNew->nAlloc = p->nExpr;
73775 pNew->a = pItem = sqlite3DbMallocRaw(db, p->nExpr*sizeof(p->a[0]) );
73776 if( pItem==0 ){
73777 sqlite3DbFree(db, pNew);
73778 return 0;
73780 pOldItem = p->a;
73781 for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
73782 Expr *pOldExpr = pOldItem->pExpr;
73783 pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
73784 pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
73785 pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
73786 pItem->sortOrder = pOldItem->sortOrder;
73787 pItem->done = 0;
73788 pItem->iCol = pOldItem->iCol;
73789 pItem->iAlias = pOldItem->iAlias;
73791 return pNew;
73795 ** If cursors, triggers, views and subqueries are all omitted from
73796 ** the build, then none of the following routines, except for
73797 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
73798 ** called with a NULL argument.
73800 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
73801 || !defined(SQLITE_OMIT_SUBQUERY)
73802 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
73803 SrcList *pNew;
73804 int i;
73805 int nByte;
73806 if( p==0 ) return 0;
73807 nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
73808 pNew = sqlite3DbMallocRaw(db, nByte );
73809 if( pNew==0 ) return 0;
73810 pNew->nSrc = pNew->nAlloc = p->nSrc;
73811 for(i=0; i<p->nSrc; i++){
73812 struct SrcList_item *pNewItem = &pNew->a[i];
73813 struct SrcList_item *pOldItem = &p->a[i];
73814 Table *pTab;
73815 pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
73816 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
73817 pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
73818 pNewItem->jointype = pOldItem->jointype;
73819 pNewItem->iCursor = pOldItem->iCursor;
73820 pNewItem->addrFillSub = pOldItem->addrFillSub;
73821 pNewItem->regReturn = pOldItem->regReturn;
73822 pNewItem->isCorrelated = pOldItem->isCorrelated;
73823 pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
73824 pNewItem->notIndexed = pOldItem->notIndexed;
73825 pNewItem->pIndex = pOldItem->pIndex;
73826 pTab = pNewItem->pTab = pOldItem->pTab;
73827 if( pTab ){
73828 pTab->nRef++;
73830 pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
73831 pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
73832 pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
73833 pNewItem->colUsed = pOldItem->colUsed;
73835 return pNew;
73837 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
73838 IdList *pNew;
73839 int i;
73840 if( p==0 ) return 0;
73841 pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
73842 if( pNew==0 ) return 0;
73843 pNew->nId = pNew->nAlloc = p->nId;
73844 pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
73845 if( pNew->a==0 ){
73846 sqlite3DbFree(db, pNew);
73847 return 0;
73849 for(i=0; i<p->nId; i++){
73850 struct IdList_item *pNewItem = &pNew->a[i];
73851 struct IdList_item *pOldItem = &p->a[i];
73852 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
73853 pNewItem->idx = pOldItem->idx;
73855 return pNew;
73857 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
73858 Select *pNew;
73859 if( p==0 ) return 0;
73860 pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
73861 if( pNew==0 ) return 0;
73862 pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
73863 pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
73864 pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
73865 pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
73866 pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
73867 pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
73868 pNew->op = p->op;
73869 pNew->pPrior = sqlite3SelectDup(db, p->pPrior, flags);
73870 pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
73871 pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
73872 pNew->iLimit = 0;
73873 pNew->iOffset = 0;
73874 pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
73875 pNew->pRightmost = 0;
73876 pNew->addrOpenEphm[0] = -1;
73877 pNew->addrOpenEphm[1] = -1;
73878 pNew->addrOpenEphm[2] = -1;
73879 return pNew;
73881 #else
73882 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
73883 assert( p==0 );
73884 return 0;
73886 #endif
73890 ** Add a new element to the end of an expression list. If pList is
73891 ** initially NULL, then create a new expression list.
73893 ** If a memory allocation error occurs, the entire list is freed and
73894 ** NULL is returned. If non-NULL is returned, then it is guaranteed
73895 ** that the new entry was successfully appended.
73897 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
73898 Parse *pParse, /* Parsing context */
73899 ExprList *pList, /* List to which to append. Might be NULL */
73900 Expr *pExpr /* Expression to be appended. Might be NULL */
73902 sqlite3 *db = pParse->db;
73903 if( pList==0 ){
73904 pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
73905 if( pList==0 ){
73906 goto no_mem;
73908 assert( pList->nAlloc==0 );
73910 if( pList->nAlloc<=pList->nExpr ){
73911 struct ExprList_item *a;
73912 int n = pList->nAlloc*2 + 4;
73913 a = sqlite3DbRealloc(db, pList->a, n*sizeof(pList->a[0]));
73914 if( a==0 ){
73915 goto no_mem;
73917 pList->a = a;
73918 pList->nAlloc = sqlite3DbMallocSize(db, a)/sizeof(a[0]);
73920 assert( pList->a!=0 );
73921 if( 1 ){
73922 struct ExprList_item *pItem = &pList->a[pList->nExpr++];
73923 memset(pItem, 0, sizeof(*pItem));
73924 pItem->pExpr = pExpr;
73926 return pList;
73928 no_mem:
73929 /* Avoid leaking memory if malloc has failed. */
73930 sqlite3ExprDelete(db, pExpr);
73931 sqlite3ExprListDelete(db, pList);
73932 return 0;
73936 ** Set the ExprList.a[].zName element of the most recently added item
73937 ** on the expression list.
73939 ** pList might be NULL following an OOM error. But pName should never be
73940 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
73941 ** is set.
73943 SQLITE_PRIVATE void sqlite3ExprListSetName(
73944 Parse *pParse, /* Parsing context */
73945 ExprList *pList, /* List to which to add the span. */
73946 Token *pName, /* Name to be added */
73947 int dequote /* True to cause the name to be dequoted */
73949 assert( pList!=0 || pParse->db->mallocFailed!=0 );
73950 if( pList ){
73951 struct ExprList_item *pItem;
73952 assert( pList->nExpr>0 );
73953 pItem = &pList->a[pList->nExpr-1];
73954 assert( pItem->zName==0 );
73955 pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
73956 if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
73961 ** Set the ExprList.a[].zSpan element of the most recently added item
73962 ** on the expression list.
73964 ** pList might be NULL following an OOM error. But pSpan should never be
73965 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
73966 ** is set.
73968 SQLITE_PRIVATE void sqlite3ExprListSetSpan(
73969 Parse *pParse, /* Parsing context */
73970 ExprList *pList, /* List to which to add the span. */
73971 ExprSpan *pSpan /* The span to be added */
73973 sqlite3 *db = pParse->db;
73974 assert( pList!=0 || db->mallocFailed!=0 );
73975 if( pList ){
73976 struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
73977 assert( pList->nExpr>0 );
73978 assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
73979 sqlite3DbFree(db, pItem->zSpan);
73980 pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
73981 (int)(pSpan->zEnd - pSpan->zStart));
73986 ** If the expression list pEList contains more than iLimit elements,
73987 ** leave an error message in pParse.
73989 SQLITE_PRIVATE void sqlite3ExprListCheckLength(
73990 Parse *pParse,
73991 ExprList *pEList,
73992 const char *zObject
73994 int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
73995 testcase( pEList && pEList->nExpr==mx );
73996 testcase( pEList && pEList->nExpr==mx+1 );
73997 if( pEList && pEList->nExpr>mx ){
73998 sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
74003 ** Delete an entire expression list.
74005 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
74006 int i;
74007 struct ExprList_item *pItem;
74008 if( pList==0 ) return;
74009 assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
74010 assert( pList->nExpr<=pList->nAlloc );
74011 for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
74012 sqlite3ExprDelete(db, pItem->pExpr);
74013 sqlite3DbFree(db, pItem->zName);
74014 sqlite3DbFree(db, pItem->zSpan);
74016 sqlite3DbFree(db, pList->a);
74017 sqlite3DbFree(db, pList);
74021 ** These routines are Walker callbacks. Walker.u.pi is a pointer
74022 ** to an integer. These routines are checking an expression to see
74023 ** if it is a constant. Set *Walker.u.pi to 0 if the expression is
74024 ** not constant.
74026 ** These callback routines are used to implement the following:
74028 ** sqlite3ExprIsConstant()
74029 ** sqlite3ExprIsConstantNotJoin()
74030 ** sqlite3ExprIsConstantOrFunction()
74033 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
74035 /* If pWalker->u.i is 3 then any term of the expression that comes from
74036 ** the ON or USING clauses of a join disqualifies the expression
74037 ** from being considered constant. */
74038 if( pWalker->u.i==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
74039 pWalker->u.i = 0;
74040 return WRC_Abort;
74043 switch( pExpr->op ){
74044 /* Consider functions to be constant if all their arguments are constant
74045 ** and pWalker->u.i==2 */
74046 case TK_FUNCTION:
74047 if( pWalker->u.i==2 ) return 0;
74048 /* Fall through */
74049 case TK_ID:
74050 case TK_COLUMN:
74051 case TK_AGG_FUNCTION:
74052 case TK_AGG_COLUMN:
74053 testcase( pExpr->op==TK_ID );
74054 testcase( pExpr->op==TK_COLUMN );
74055 testcase( pExpr->op==TK_AGG_FUNCTION );
74056 testcase( pExpr->op==TK_AGG_COLUMN );
74057 pWalker->u.i = 0;
74058 return WRC_Abort;
74059 default:
74060 testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
74061 testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
74062 return WRC_Continue;
74065 static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
74066 UNUSED_PARAMETER(NotUsed);
74067 pWalker->u.i = 0;
74068 return WRC_Abort;
74070 static int exprIsConst(Expr *p, int initFlag){
74071 Walker w;
74072 w.u.i = initFlag;
74073 w.xExprCallback = exprNodeIsConstant;
74074 w.xSelectCallback = selectNodeIsConstant;
74075 sqlite3WalkExpr(&w, p);
74076 return w.u.i;
74080 ** Walk an expression tree. Return 1 if the expression is constant
74081 ** and 0 if it involves variables or function calls.
74083 ** For the purposes of this function, a double-quoted string (ex: "abc")
74084 ** is considered a variable but a single-quoted string (ex: 'abc') is
74085 ** a constant.
74087 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
74088 return exprIsConst(p, 1);
74092 ** Walk an expression tree. Return 1 if the expression is constant
74093 ** that does no originate from the ON or USING clauses of a join.
74094 ** Return 0 if it involves variables or function calls or terms from
74095 ** an ON or USING clause.
74097 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
74098 return exprIsConst(p, 3);
74102 ** Walk an expression tree. Return 1 if the expression is constant
74103 ** or a function call with constant arguments. Return and 0 if there
74104 ** are any variables.
74106 ** For the purposes of this function, a double-quoted string (ex: "abc")
74107 ** is considered a variable but a single-quoted string (ex: 'abc') is
74108 ** a constant.
74110 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
74111 return exprIsConst(p, 2);
74115 ** If the expression p codes a constant integer that is small enough
74116 ** to fit in a 32-bit integer, return 1 and put the value of the integer
74117 ** in *pValue. If the expression is not an integer or if it is too big
74118 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
74120 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
74121 int rc = 0;
74123 /* If an expression is an integer literal that fits in a signed 32-bit
74124 ** integer, then the EP_IntValue flag will have already been set */
74125 assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
74126 || sqlite3GetInt32(p->u.zToken, &rc)==0 );
74128 if( p->flags & EP_IntValue ){
74129 *pValue = p->u.iValue;
74130 return 1;
74132 switch( p->op ){
74133 case TK_UPLUS: {
74134 rc = sqlite3ExprIsInteger(p->pLeft, pValue);
74135 break;
74137 case TK_UMINUS: {
74138 int v;
74139 if( sqlite3ExprIsInteger(p->pLeft, &v) ){
74140 *pValue = -v;
74141 rc = 1;
74143 break;
74145 default: break;
74147 return rc;
74151 ** Return FALSE if there is no chance that the expression can be NULL.
74153 ** If the expression might be NULL or if the expression is too complex
74154 ** to tell return TRUE.
74156 ** This routine is used as an optimization, to skip OP_IsNull opcodes
74157 ** when we know that a value cannot be NULL. Hence, a false positive
74158 ** (returning TRUE when in fact the expression can never be NULL) might
74159 ** be a small performance hit but is otherwise harmless. On the other
74160 ** hand, a false negative (returning FALSE when the result could be NULL)
74161 ** will likely result in an incorrect answer. So when in doubt, return
74162 ** TRUE.
74164 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
74165 u8 op;
74166 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
74167 op = p->op;
74168 if( op==TK_REGISTER ) op = p->op2;
74169 switch( op ){
74170 case TK_INTEGER:
74171 case TK_STRING:
74172 case TK_FLOAT:
74173 case TK_BLOB:
74174 return 0;
74175 default:
74176 return 1;
74181 ** Generate an OP_IsNull instruction that tests register iReg and jumps
74182 ** to location iDest if the value in iReg is NULL. The value in iReg
74183 ** was computed by pExpr. If we can look at pExpr at compile-time and
74184 ** determine that it can never generate a NULL, then the OP_IsNull operation
74185 ** can be omitted.
74187 SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(
74188 Vdbe *v, /* The VDBE under construction */
74189 const Expr *pExpr, /* Only generate OP_IsNull if this expr can be NULL */
74190 int iReg, /* Test the value in this register for NULL */
74191 int iDest /* Jump here if the value is null */
74193 if( sqlite3ExprCanBeNull(pExpr) ){
74194 sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iDest);
74199 ** Return TRUE if the given expression is a constant which would be
74200 ** unchanged by OP_Affinity with the affinity given in the second
74201 ** argument.
74203 ** This routine is used to determine if the OP_Affinity operation
74204 ** can be omitted. When in doubt return FALSE. A false negative
74205 ** is harmless. A false positive, however, can result in the wrong
74206 ** answer.
74208 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
74209 u8 op;
74210 if( aff==SQLITE_AFF_NONE ) return 1;
74211 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
74212 op = p->op;
74213 if( op==TK_REGISTER ) op = p->op2;
74214 switch( op ){
74215 case TK_INTEGER: {
74216 return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
74218 case TK_FLOAT: {
74219 return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
74221 case TK_STRING: {
74222 return aff==SQLITE_AFF_TEXT;
74224 case TK_BLOB: {
74225 return 1;
74227 case TK_COLUMN: {
74228 assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */
74229 return p->iColumn<0
74230 && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
74232 default: {
74233 return 0;
74239 ** Return TRUE if the given string is a row-id column name.
74241 SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
74242 if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
74243 if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
74244 if( sqlite3StrICmp(z, "OID")==0 ) return 1;
74245 return 0;
74249 ** Return true if we are able to the IN operator optimization on a
74250 ** query of the form
74252 ** x IN (SELECT ...)
74254 ** Where the SELECT... clause is as specified by the parameter to this
74255 ** routine.
74257 ** The Select object passed in has already been preprocessed and no
74258 ** errors have been found.
74260 #ifndef SQLITE_OMIT_SUBQUERY
74261 static int isCandidateForInOpt(Select *p){
74262 SrcList *pSrc;
74263 ExprList *pEList;
74264 Table *pTab;
74265 if( p==0 ) return 0; /* right-hand side of IN is SELECT */
74266 if( p->pPrior ) return 0; /* Not a compound SELECT */
74267 if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
74268 testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
74269 testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
74270 return 0; /* No DISTINCT keyword and no aggregate functions */
74272 assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */
74273 if( p->pLimit ) return 0; /* Has no LIMIT clause */
74274 assert( p->pOffset==0 ); /* No LIMIT means no OFFSET */
74275 if( p->pWhere ) return 0; /* Has no WHERE clause */
74276 pSrc = p->pSrc;
74277 assert( pSrc!=0 );
74278 if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
74279 if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */
74280 pTab = pSrc->a[0].pTab;
74281 if( NEVER(pTab==0) ) return 0;
74282 assert( pTab->pSelect==0 ); /* FROM clause is not a view */
74283 if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
74284 pEList = p->pEList;
74285 if( pEList->nExpr!=1 ) return 0; /* One column in the result set */
74286 if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
74287 return 1;
74289 #endif /* SQLITE_OMIT_SUBQUERY */
74292 ** This function is used by the implementation of the IN (...) operator.
74293 ** It's job is to find or create a b-tree structure that may be used
74294 ** either to test for membership of the (...) set or to iterate through
74295 ** its members, skipping duplicates.
74297 ** The index of the cursor opened on the b-tree (database table, database index
74298 ** or ephermal table) is stored in pX->iTable before this function returns.
74299 ** The returned value of this function indicates the b-tree type, as follows:
74301 ** IN_INDEX_ROWID - The cursor was opened on a database table.
74302 ** IN_INDEX_INDEX - The cursor was opened on a database index.
74303 ** IN_INDEX_EPH - The cursor was opened on a specially created and
74304 ** populated epheremal table.
74306 ** An existing b-tree may only be used if the SELECT is of the simple
74307 ** form:
74309 ** SELECT <column> FROM <table>
74311 ** If the prNotFound parameter is 0, then the b-tree will be used to iterate
74312 ** through the set members, skipping any duplicates. In this case an
74313 ** epheremal table must be used unless the selected <column> is guaranteed
74314 ** to be unique - either because it is an INTEGER PRIMARY KEY or it
74315 ** has a UNIQUE constraint or UNIQUE index.
74317 ** If the prNotFound parameter is not 0, then the b-tree will be used
74318 ** for fast set membership tests. In this case an epheremal table must
74319 ** be used unless <column> is an INTEGER PRIMARY KEY or an index can
74320 ** be found with <column> as its left-most column.
74322 ** When the b-tree is being used for membership tests, the calling function
74323 ** needs to know whether or not the structure contains an SQL NULL
74324 ** value in order to correctly evaluate expressions like "X IN (Y, Z)".
74325 ** If there is any chance that the (...) might contain a NULL value at
74326 ** runtime, then a register is allocated and the register number written
74327 ** to *prNotFound. If there is no chance that the (...) contains a
74328 ** NULL value, then *prNotFound is left unchanged.
74330 ** If a register is allocated and its location stored in *prNotFound, then
74331 ** its initial value is NULL. If the (...) does not remain constant
74332 ** for the duration of the query (i.e. the SELECT within the (...)
74333 ** is a correlated subquery) then the value of the allocated register is
74334 ** reset to NULL each time the subquery is rerun. This allows the
74335 ** caller to use vdbe code equivalent to the following:
74337 ** if( register==NULL ){
74338 ** has_null = <test if data structure contains null>
74339 ** register = 1
74340 ** }
74342 ** in order to avoid running the <test if data structure contains null>
74343 ** test more often than is necessary.
74345 #ifndef SQLITE_OMIT_SUBQUERY
74346 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
74347 Select *p; /* SELECT to the right of IN operator */
74348 int eType = 0; /* Type of RHS table. IN_INDEX_* */
74349 int iTab = pParse->nTab++; /* Cursor of the RHS table */
74350 int mustBeUnique = (prNotFound==0); /* True if RHS must be unique */
74352 assert( pX->op==TK_IN );
74354 /* Check to see if an existing table or index can be used to
74355 ** satisfy the query. This is preferable to generating a new
74356 ** ephemeral table.
74358 p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
74359 if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
74360 sqlite3 *db = pParse->db; /* Database connection */
74361 Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
74362 Table *pTab; /* Table <table>. */
74363 Expr *pExpr; /* Expression <column> */
74364 int iCol; /* Index of column <column> */
74365 int iDb; /* Database idx for pTab */
74367 assert( p ); /* Because of isCandidateForInOpt(p) */
74368 assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */
74369 assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
74370 assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */
74371 pTab = p->pSrc->a[0].pTab;
74372 pExpr = p->pEList->a[0].pExpr;
74373 iCol = pExpr->iColumn;
74375 /* Code an OP_VerifyCookie and OP_TableLock for <table>. */
74376 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
74377 sqlite3CodeVerifySchema(pParse, iDb);
74378 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
74380 /* This function is only called from two places. In both cases the vdbe
74381 ** has already been allocated. So assume sqlite3GetVdbe() is always
74382 ** successful here.
74384 assert(v);
74385 if( iCol<0 ){
74386 int iMem = ++pParse->nMem;
74387 int iAddr;
74389 iAddr = sqlite3VdbeAddOp1(v, OP_Once, iMem);
74391 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
74392 eType = IN_INDEX_ROWID;
74394 sqlite3VdbeJumpHere(v, iAddr);
74395 }else{
74396 Index *pIdx; /* Iterator variable */
74398 /* The collation sequence used by the comparison. If an index is to
74399 ** be used in place of a temp-table, it must be ordered according
74400 ** to this collation sequence. */
74401 CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
74403 /* Check that the affinity that will be used to perform the
74404 ** comparison is the same as the affinity of the column. If
74405 ** it is not, it is not possible to use any index.
74407 char aff = comparisonAffinity(pX);
74408 int affinity_ok = (pTab->aCol[iCol].affinity==aff||aff==SQLITE_AFF_NONE);
74410 for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
74411 if( (pIdx->aiColumn[0]==iCol)
74412 && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
74413 && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
74415 int iMem = ++pParse->nMem;
74416 int iAddr;
74417 char *pKey;
74419 pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
74420 iAddr = sqlite3VdbeAddOp1(v, OP_Once, iMem);
74422 sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
74423 pKey,P4_KEYINFO_HANDOFF);
74424 VdbeComment((v, "%s", pIdx->zName));
74425 eType = IN_INDEX_INDEX;
74427 sqlite3VdbeJumpHere(v, iAddr);
74428 if( prNotFound && !pTab->aCol[iCol].notNull ){
74429 *prNotFound = ++pParse->nMem;
74436 if( eType==0 ){
74437 /* Could not found an existing table or index to use as the RHS b-tree.
74438 ** We will have to generate an ephemeral table to do the job.
74440 double savedNQueryLoop = pParse->nQueryLoop;
74441 int rMayHaveNull = 0;
74442 eType = IN_INDEX_EPH;
74443 if( prNotFound ){
74444 *prNotFound = rMayHaveNull = ++pParse->nMem;
74445 }else{
74446 testcase( pParse->nQueryLoop>(double)1 );
74447 pParse->nQueryLoop = (double)1;
74448 if( pX->pLeft->iColumn<0 && !ExprHasAnyProperty(pX, EP_xIsSelect) ){
74449 eType = IN_INDEX_ROWID;
74452 sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
74453 pParse->nQueryLoop = savedNQueryLoop;
74454 }else{
74455 pX->iTable = iTab;
74457 return eType;
74459 #endif
74462 ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
74463 ** or IN operators. Examples:
74465 ** (SELECT a FROM b) -- subquery
74466 ** EXISTS (SELECT a FROM b) -- EXISTS subquery
74467 ** x IN (4,5,11) -- IN operator with list on right-hand side
74468 ** x IN (SELECT a FROM b) -- IN operator with subquery on the right
74470 ** The pExpr parameter describes the expression that contains the IN
74471 ** operator or subquery.
74473 ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
74474 ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
74475 ** to some integer key column of a table B-Tree. In this case, use an
74476 ** intkey B-Tree to store the set of IN(...) values instead of the usual
74477 ** (slower) variable length keys B-Tree.
74479 ** If rMayHaveNull is non-zero, that means that the operation is an IN
74480 ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
74481 ** Furthermore, the IN is in a WHERE clause and that we really want
74482 ** to iterate over the RHS of the IN operator in order to quickly locate
74483 ** all corresponding LHS elements. All this routine does is initialize
74484 ** the register given by rMayHaveNull to NULL. Calling routines will take
74485 ** care of changing this register value to non-NULL if the RHS is NULL-free.
74487 ** If rMayHaveNull is zero, that means that the subquery is being used
74488 ** for membership testing only. There is no need to initialize any
74489 ** registers to indicate the presense or absence of NULLs on the RHS.
74491 ** For a SELECT or EXISTS operator, return the register that holds the
74492 ** result. For IN operators or if an error occurs, the return value is 0.
74494 #ifndef SQLITE_OMIT_SUBQUERY
74495 SQLITE_PRIVATE int sqlite3CodeSubselect(
74496 Parse *pParse, /* Parsing context */
74497 Expr *pExpr, /* The IN, SELECT, or EXISTS operator */
74498 int rMayHaveNull, /* Register that records whether NULLs exist in RHS */
74499 int isRowid /* If true, LHS of IN operator is a rowid */
74501 int testAddr = -1; /* One-time test address */
74502 int rReg = 0; /* Register storing resulting */
74503 Vdbe *v = sqlite3GetVdbe(pParse);
74504 if( NEVER(v==0) ) return 0;
74505 sqlite3ExprCachePush(pParse);
74507 /* This code must be run in its entirety every time it is encountered
74508 ** if any of the following is true:
74510 ** * The right-hand side is a correlated subquery
74511 ** * The right-hand side is an expression list containing variables
74512 ** * We are inside a trigger
74514 ** If all of the above are false, then we can run this code just once
74515 ** save the results, and reuse the same result on subsequent invocations.
74517 if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->pTriggerTab ){
74518 int mem = ++pParse->nMem;
74519 testAddr = sqlite3VdbeAddOp1(v, OP_Once, mem);
74522 #ifndef SQLITE_OMIT_EXPLAIN
74523 if( pParse->explain==2 ){
74524 char *zMsg = sqlite3MPrintf(
74525 pParse->db, "EXECUTE %s%s SUBQUERY %d", testAddr>=0?"":"CORRELATED ",
74526 pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId
74528 sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
74530 #endif
74532 switch( pExpr->op ){
74533 case TK_IN: {
74534 char affinity; /* Affinity of the LHS of the IN */
74535 KeyInfo keyInfo; /* Keyinfo for the generated table */
74536 int addr; /* Address of OP_OpenEphemeral instruction */
74537 Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
74539 if( rMayHaveNull ){
74540 sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
74543 affinity = sqlite3ExprAffinity(pLeft);
74545 /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
74546 ** expression it is handled the same way. An ephemeral table is
74547 ** filled with single-field index keys representing the results
74548 ** from the SELECT or the <exprlist>.
74550 ** If the 'x' expression is a column value, or the SELECT...
74551 ** statement returns a column value, then the affinity of that
74552 ** column is used to build the index keys. If both 'x' and the
74553 ** SELECT... statement are columns, then numeric affinity is used
74554 ** if either column has NUMERIC or INTEGER affinity. If neither
74555 ** 'x' nor the SELECT... statement are columns, then numeric affinity
74556 ** is used.
74558 pExpr->iTable = pParse->nTab++;
74559 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
74560 if( rMayHaveNull==0 ) sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
74561 memset(&keyInfo, 0, sizeof(keyInfo));
74562 keyInfo.nField = 1;
74564 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
74565 /* Case 1: expr IN (SELECT ...)
74567 ** Generate code to write the results of the select into the temporary
74568 ** table allocated and opened above.
74570 SelectDest dest;
74571 ExprList *pEList;
74573 assert( !isRowid );
74574 sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
74575 dest.affinity = (u8)affinity;
74576 assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
74577 pExpr->x.pSelect->iLimit = 0;
74578 if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){
74579 return 0;
74581 pEList = pExpr->x.pSelect->pEList;
74582 if( ALWAYS(pEList!=0 && pEList->nExpr>0) ){
74583 keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
74584 pEList->a[0].pExpr);
74586 }else if( ALWAYS(pExpr->x.pList!=0) ){
74587 /* Case 2: expr IN (exprlist)
74589 ** For each expression, build an index key from the evaluation and
74590 ** store it in the temporary table. If <expr> is a column, then use
74591 ** that columns affinity when building index keys. If <expr> is not
74592 ** a column, use numeric affinity.
74594 int i;
74595 ExprList *pList = pExpr->x.pList;
74596 struct ExprList_item *pItem;
74597 int r1, r2, r3;
74599 if( !affinity ){
74600 affinity = SQLITE_AFF_NONE;
74602 keyInfo.aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
74604 /* Loop through each expression in <exprlist>. */
74605 r1 = sqlite3GetTempReg(pParse);
74606 r2 = sqlite3GetTempReg(pParse);
74607 sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
74608 for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
74609 Expr *pE2 = pItem->pExpr;
74610 int iValToIns;
74612 /* If the expression is not constant then we will need to
74613 ** disable the test that was generated above that makes sure
74614 ** this code only executes once. Because for a non-constant
74615 ** expression we need to rerun this code each time.
74617 if( testAddr>=0 && !sqlite3ExprIsConstant(pE2) ){
74618 sqlite3VdbeChangeToNoop(v, testAddr);
74619 testAddr = -1;
74622 /* Evaluate the expression and insert it into the temp table */
74623 if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
74624 sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
74625 }else{
74626 r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
74627 if( isRowid ){
74628 sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
74629 sqlite3VdbeCurrentAddr(v)+2);
74630 sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
74631 }else{
74632 sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
74633 sqlite3ExprCacheAffinityChange(pParse, r3, 1);
74634 sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
74638 sqlite3ReleaseTempReg(pParse, r1);
74639 sqlite3ReleaseTempReg(pParse, r2);
74641 if( !isRowid ){
74642 sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
74644 break;
74647 case TK_EXISTS:
74648 case TK_SELECT:
74649 default: {
74650 /* If this has to be a scalar SELECT. Generate code to put the
74651 ** value of this select in a memory cell and record the number
74652 ** of the memory cell in iColumn. If this is an EXISTS, write
74653 ** an integer 0 (not exists) or 1 (exists) into a memory cell
74654 ** and record that memory cell in iColumn.
74656 Select *pSel; /* SELECT statement to encode */
74657 SelectDest dest; /* How to deal with SELECt result */
74659 testcase( pExpr->op==TK_EXISTS );
74660 testcase( pExpr->op==TK_SELECT );
74661 assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
74663 assert( ExprHasProperty(pExpr, EP_xIsSelect) );
74664 pSel = pExpr->x.pSelect;
74665 sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
74666 if( pExpr->op==TK_SELECT ){
74667 dest.eDest = SRT_Mem;
74668 sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iParm);
74669 VdbeComment((v, "Init subquery result"));
74670 }else{
74671 dest.eDest = SRT_Exists;
74672 sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iParm);
74673 VdbeComment((v, "Init EXISTS result"));
74675 sqlite3ExprDelete(pParse->db, pSel->pLimit);
74676 pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
74677 &sqlite3IntTokens[1]);
74678 pSel->iLimit = 0;
74679 if( sqlite3Select(pParse, pSel, &dest) ){
74680 return 0;
74682 rReg = dest.iParm;
74683 ExprSetIrreducible(pExpr);
74684 break;
74688 if( testAddr>=0 ){
74689 sqlite3VdbeJumpHere(v, testAddr);
74691 sqlite3ExprCachePop(pParse, 1);
74693 return rReg;
74695 #endif /* SQLITE_OMIT_SUBQUERY */
74697 #ifndef SQLITE_OMIT_SUBQUERY
74699 ** Generate code for an IN expression.
74701 ** x IN (SELECT ...)
74702 ** x IN (value, value, ...)
74704 ** The left-hand side (LHS) is a scalar expression. The right-hand side (RHS)
74705 ** is an array of zero or more values. The expression is true if the LHS is
74706 ** contained within the RHS. The value of the expression is unknown (NULL)
74707 ** if the LHS is NULL or if the LHS is not contained within the RHS and the
74708 ** RHS contains one or more NULL values.
74710 ** This routine generates code will jump to destIfFalse if the LHS is not
74711 ** contained within the RHS. If due to NULLs we cannot determine if the LHS
74712 ** is contained in the RHS then jump to destIfNull. If the LHS is contained
74713 ** within the RHS then fall through.
74715 static void sqlite3ExprCodeIN(
74716 Parse *pParse, /* Parsing and code generating context */
74717 Expr *pExpr, /* The IN expression */
74718 int destIfFalse, /* Jump here if LHS is not contained in the RHS */
74719 int destIfNull /* Jump here if the results are unknown due to NULLs */
74721 int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */
74722 char affinity; /* Comparison affinity to use */
74723 int eType; /* Type of the RHS */
74724 int r1; /* Temporary use register */
74725 Vdbe *v; /* Statement under construction */
74727 /* Compute the RHS. After this step, the table with cursor
74728 ** pExpr->iTable will contains the values that make up the RHS.
74730 v = pParse->pVdbe;
74731 assert( v!=0 ); /* OOM detected prior to this routine */
74732 VdbeNoopComment((v, "begin IN expr"));
74733 eType = sqlite3FindInIndex(pParse, pExpr, &rRhsHasNull);
74735 /* Figure out the affinity to use to create a key from the results
74736 ** of the expression. affinityStr stores a static string suitable for
74737 ** P4 of OP_MakeRecord.
74739 affinity = comparisonAffinity(pExpr);
74741 /* Code the LHS, the <expr> from "<expr> IN (...)".
74743 sqlite3ExprCachePush(pParse);
74744 r1 = sqlite3GetTempReg(pParse);
74745 sqlite3ExprCode(pParse, pExpr->pLeft, r1);
74747 /* If the LHS is NULL, then the result is either false or NULL depending
74748 ** on whether the RHS is empty or not, respectively.
74750 if( destIfNull==destIfFalse ){
74751 /* Shortcut for the common case where the false and NULL outcomes are
74752 ** the same. */
74753 sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull);
74754 }else{
74755 int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1);
74756 sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
74757 sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
74758 sqlite3VdbeJumpHere(v, addr1);
74761 if( eType==IN_INDEX_ROWID ){
74762 /* In this case, the RHS is the ROWID of table b-tree
74764 sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse);
74765 sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
74766 }else{
74767 /* In this case, the RHS is an index b-tree.
74769 sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
74771 /* If the set membership test fails, then the result of the
74772 ** "x IN (...)" expression must be either 0 or NULL. If the set
74773 ** contains no NULL values, then the result is 0. If the set
74774 ** contains one or more NULL values, then the result of the
74775 ** expression is also NULL.
74777 if( rRhsHasNull==0 || destIfFalse==destIfNull ){
74778 /* This branch runs if it is known at compile time that the RHS
74779 ** cannot contain NULL values. This happens as the result
74780 ** of a "NOT NULL" constraint in the database schema.
74782 ** Also run this branch if NULL is equivalent to FALSE
74783 ** for this particular IN operator.
74785 sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
74787 }else{
74788 /* In this branch, the RHS of the IN might contain a NULL and
74789 ** the presence of a NULL on the RHS makes a difference in the
74790 ** outcome.
74792 int j1, j2, j3;
74794 /* First check to see if the LHS is contained in the RHS. If so,
74795 ** then the presence of NULLs in the RHS does not matter, so jump
74796 ** over all of the code that follows.
74798 j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
74800 /* Here we begin generating code that runs if the LHS is not
74801 ** contained within the RHS. Generate additional code that
74802 ** tests the RHS for NULLs. If the RHS contains a NULL then
74803 ** jump to destIfNull. If there are no NULLs in the RHS then
74804 ** jump to destIfFalse.
74806 j2 = sqlite3VdbeAddOp1(v, OP_NotNull, rRhsHasNull);
74807 j3 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1);
74808 sqlite3VdbeAddOp2(v, OP_Integer, -1, rRhsHasNull);
74809 sqlite3VdbeJumpHere(v, j3);
74810 sqlite3VdbeAddOp2(v, OP_AddImm, rRhsHasNull, 1);
74811 sqlite3VdbeJumpHere(v, j2);
74813 /* Jump to the appropriate target depending on whether or not
74814 ** the RHS contains a NULL
74816 sqlite3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull);
74817 sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
74819 /* The OP_Found at the top of this branch jumps here when true,
74820 ** causing the overall IN expression evaluation to fall through.
74822 sqlite3VdbeJumpHere(v, j1);
74825 sqlite3ReleaseTempReg(pParse, r1);
74826 sqlite3ExprCachePop(pParse, 1);
74827 VdbeComment((v, "end IN expr"));
74829 #endif /* SQLITE_OMIT_SUBQUERY */
74832 ** Duplicate an 8-byte value
74834 static char *dup8bytes(Vdbe *v, const char *in){
74835 char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
74836 if( out ){
74837 memcpy(out, in, 8);
74839 return out;
74842 #ifndef SQLITE_OMIT_FLOATING_POINT
74844 ** Generate an instruction that will put the floating point
74845 ** value described by z[0..n-1] into register iMem.
74847 ** The z[] string will probably not be zero-terminated. But the
74848 ** z[n] character is guaranteed to be something that does not look
74849 ** like the continuation of the number.
74851 static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
74852 if( ALWAYS(z!=0) ){
74853 double value;
74854 char *zV;
74855 sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
74856 assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
74857 if( negateFlag ) value = -value;
74858 zV = dup8bytes(v, (char*)&value);
74859 sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
74862 #endif
74866 ** Generate an instruction that will put the integer describe by
74867 ** text z[0..n-1] into register iMem.
74869 ** Expr.u.zToken is always UTF8 and zero-terminated.
74871 static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
74872 Vdbe *v = pParse->pVdbe;
74873 if( pExpr->flags & EP_IntValue ){
74874 int i = pExpr->u.iValue;
74875 assert( i>=0 );
74876 if( negFlag ) i = -i;
74877 sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
74878 }else{
74879 int c;
74880 i64 value;
74881 const char *z = pExpr->u.zToken;
74882 assert( z!=0 );
74883 c = sqlite3Atoi64(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
74884 if( c==0 || (c==2 && negFlag) ){
74885 char *zV;
74886 if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
74887 zV = dup8bytes(v, (char*)&value);
74888 sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
74889 }else{
74890 #ifdef SQLITE_OMIT_FLOATING_POINT
74891 sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
74892 #else
74893 codeReal(v, z, negFlag, iMem);
74894 #endif
74900 ** Clear a cache entry.
74902 static void cacheEntryClear(Parse *pParse, struct yColCache *p){
74903 if( p->tempReg ){
74904 if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
74905 pParse->aTempReg[pParse->nTempReg++] = p->iReg;
74907 p->tempReg = 0;
74913 ** Record in the column cache that a particular column from a
74914 ** particular table is stored in a particular register.
74916 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
74917 int i;
74918 int minLru;
74919 int idxLru;
74920 struct yColCache *p;
74922 assert( iReg>0 ); /* Register numbers are always positive */
74923 assert( iCol>=-1 && iCol<32768 ); /* Finite column numbers */
74925 /* The SQLITE_ColumnCache flag disables the column cache. This is used
74926 ** for testing only - to verify that SQLite always gets the same answer
74927 ** with and without the column cache.
74929 if( pParse->db->flags & SQLITE_ColumnCache ) return;
74931 /* First replace any existing entry.
74933 ** Actually, the way the column cache is currently used, we are guaranteed
74934 ** that the object will never already be in cache. Verify this guarantee.
74936 #ifndef NDEBUG
74937 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
74938 #if 0 /* This code wold remove the entry from the cache if it existed */
74939 if( p->iReg && p->iTable==iTab && p->iColumn==iCol ){
74940 cacheEntryClear(pParse, p);
74941 p->iLevel = pParse->iCacheLevel;
74942 p->iReg = iReg;
74943 p->lru = pParse->iCacheCnt++;
74944 return;
74946 #endif
74947 assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
74949 #endif
74951 /* Find an empty slot and replace it */
74952 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
74953 if( p->iReg==0 ){
74954 p->iLevel = pParse->iCacheLevel;
74955 p->iTable = iTab;
74956 p->iColumn = iCol;
74957 p->iReg = iReg;
74958 p->tempReg = 0;
74959 p->lru = pParse->iCacheCnt++;
74960 return;
74964 /* Replace the last recently used */
74965 minLru = 0x7fffffff;
74966 idxLru = -1;
74967 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
74968 if( p->lru<minLru ){
74969 idxLru = i;
74970 minLru = p->lru;
74973 if( ALWAYS(idxLru>=0) ){
74974 p = &pParse->aColCache[idxLru];
74975 p->iLevel = pParse->iCacheLevel;
74976 p->iTable = iTab;
74977 p->iColumn = iCol;
74978 p->iReg = iReg;
74979 p->tempReg = 0;
74980 p->lru = pParse->iCacheCnt++;
74981 return;
74986 ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
74987 ** Purge the range of registers from the column cache.
74989 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
74990 int i;
74991 int iLast = iReg + nReg - 1;
74992 struct yColCache *p;
74993 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
74994 int r = p->iReg;
74995 if( r>=iReg && r<=iLast ){
74996 cacheEntryClear(pParse, p);
74997 p->iReg = 0;
75003 ** Remember the current column cache context. Any new entries added
75004 ** added to the column cache after this call are removed when the
75005 ** corresponding pop occurs.
75007 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
75008 pParse->iCacheLevel++;
75012 ** Remove from the column cache any entries that were added since the
75013 ** the previous N Push operations. In other words, restore the cache
75014 ** to the state it was in N Pushes ago.
75016 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse, int N){
75017 int i;
75018 struct yColCache *p;
75019 assert( N>0 );
75020 assert( pParse->iCacheLevel>=N );
75021 pParse->iCacheLevel -= N;
75022 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
75023 if( p->iReg && p->iLevel>pParse->iCacheLevel ){
75024 cacheEntryClear(pParse, p);
75025 p->iReg = 0;
75031 ** When a cached column is reused, make sure that its register is
75032 ** no longer available as a temp register. ticket #3879: that same
75033 ** register might be in the cache in multiple places, so be sure to
75034 ** get them all.
75036 static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
75037 int i;
75038 struct yColCache *p;
75039 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
75040 if( p->iReg==iReg ){
75041 p->tempReg = 0;
75047 ** Generate code to extract the value of the iCol-th column of a table.
75049 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
75050 Vdbe *v, /* The VDBE under construction */
75051 Table *pTab, /* The table containing the value */
75052 int iTabCur, /* The cursor for this table */
75053 int iCol, /* Index of the column to extract */
75054 int regOut /* Extract the valud into this register */
75056 if( iCol<0 || iCol==pTab->iPKey ){
75057 sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
75058 }else{
75059 int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
75060 sqlite3VdbeAddOp3(v, op, iTabCur, iCol, regOut);
75062 if( iCol>=0 ){
75063 sqlite3ColumnDefault(v, pTab, iCol, regOut);
75068 ** Generate code that will extract the iColumn-th column from
75069 ** table pTab and store the column value in a register. An effort
75070 ** is made to store the column value in register iReg, but this is
75071 ** not guaranteed. The location of the column value is returned.
75073 ** There must be an open cursor to pTab in iTable when this routine
75074 ** is called. If iColumn<0 then code is generated that extracts the rowid.
75076 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
75077 Parse *pParse, /* Parsing and code generating context */
75078 Table *pTab, /* Description of the table we are reading from */
75079 int iColumn, /* Index of the table column */
75080 int iTable, /* The cursor pointing to the table */
75081 int iReg /* Store results here */
75083 Vdbe *v = pParse->pVdbe;
75084 int i;
75085 struct yColCache *p;
75087 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
75088 if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
75089 p->lru = pParse->iCacheCnt++;
75090 sqlite3ExprCachePinRegister(pParse, p->iReg);
75091 return p->iReg;
75094 assert( v!=0 );
75095 sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
75096 sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
75097 return iReg;
75101 ** Clear all column cache entries.
75103 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
75104 int i;
75105 struct yColCache *p;
75107 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
75108 if( p->iReg ){
75109 cacheEntryClear(pParse, p);
75110 p->iReg = 0;
75116 ** Record the fact that an affinity change has occurred on iCount
75117 ** registers starting with iStart.
75119 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
75120 sqlite3ExprCacheRemove(pParse, iStart, iCount);
75124 ** Generate code to move content from registers iFrom...iFrom+nReg-1
75125 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
75127 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
75128 int i;
75129 struct yColCache *p;
75130 if( NEVER(iFrom==iTo) ) return;
75131 sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
75132 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
75133 int x = p->iReg;
75134 if( x>=iFrom && x<iFrom+nReg ){
75135 p->iReg += iTo-iFrom;
75141 ** Generate code to copy content from registers iFrom...iFrom+nReg-1
75142 ** over to iTo..iTo+nReg-1.
75144 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, int iFrom, int iTo, int nReg){
75145 int i;
75146 if( NEVER(iFrom==iTo) ) return;
75147 for(i=0; i<nReg; i++){
75148 sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, iFrom+i, iTo+i);
75152 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
75154 ** Return true if any register in the range iFrom..iTo (inclusive)
75155 ** is used as part of the column cache.
75157 ** This routine is used within assert() and testcase() macros only
75158 ** and does not appear in a normal build.
75160 static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
75161 int i;
75162 struct yColCache *p;
75163 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
75164 int r = p->iReg;
75165 if( r>=iFrom && r<=iTo ) return 1; /*NO_TEST*/
75167 return 0;
75169 #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
75172 ** Generate code into the current Vdbe to evaluate the given
75173 ** expression. Attempt to store the results in register "target".
75174 ** Return the register where results are stored.
75176 ** With this routine, there is no guarantee that results will
75177 ** be stored in target. The result might be stored in some other
75178 ** register if it is convenient to do so. The calling function
75179 ** must check the return code and move the results to the desired
75180 ** register.
75182 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
75183 Vdbe *v = pParse->pVdbe; /* The VM under construction */
75184 int op; /* The opcode being coded */
75185 int inReg = target; /* Results stored in register inReg */
75186 int regFree1 = 0; /* If non-zero free this temporary register */
75187 int regFree2 = 0; /* If non-zero free this temporary register */
75188 int r1, r2, r3, r4; /* Various register numbers */
75189 sqlite3 *db = pParse->db; /* The database connection */
75191 assert( target>0 && target<=pParse->nMem );
75192 if( v==0 ){
75193 assert( pParse->db->mallocFailed );
75194 return 0;
75197 if( pExpr==0 ){
75198 op = TK_NULL;
75199 }else{
75200 op = pExpr->op;
75202 switch( op ){
75203 case TK_AGG_COLUMN: {
75204 AggInfo *pAggInfo = pExpr->pAggInfo;
75205 struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
75206 if( !pAggInfo->directMode ){
75207 assert( pCol->iMem>0 );
75208 inReg = pCol->iMem;
75209 break;
75210 }else if( pAggInfo->useSortingIdx ){
75211 sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
75212 pCol->iSorterColumn, target);
75213 break;
75215 /* Otherwise, fall thru into the TK_COLUMN case */
75217 case TK_COLUMN: {
75218 if( pExpr->iTable<0 ){
75219 /* This only happens when coding check constraints */
75220 assert( pParse->ckBase>0 );
75221 inReg = pExpr->iColumn + pParse->ckBase;
75222 }else{
75223 inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
75224 pExpr->iColumn, pExpr->iTable, target);
75226 break;
75228 case TK_INTEGER: {
75229 codeInteger(pParse, pExpr, 0, target);
75230 break;
75232 #ifndef SQLITE_OMIT_FLOATING_POINT
75233 case TK_FLOAT: {
75234 assert( !ExprHasProperty(pExpr, EP_IntValue) );
75235 codeReal(v, pExpr->u.zToken, 0, target);
75236 break;
75238 #endif
75239 case TK_STRING: {
75240 assert( !ExprHasProperty(pExpr, EP_IntValue) );
75241 sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
75242 break;
75244 case TK_NULL: {
75245 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
75246 break;
75248 #ifndef SQLITE_OMIT_BLOB_LITERAL
75249 case TK_BLOB: {
75250 int n;
75251 const char *z;
75252 char *zBlob;
75253 assert( !ExprHasProperty(pExpr, EP_IntValue) );
75254 assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
75255 assert( pExpr->u.zToken[1]=='\'' );
75256 z = &pExpr->u.zToken[2];
75257 n = sqlite3Strlen30(z) - 1;
75258 assert( z[n]=='\'' );
75259 zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
75260 sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
75261 break;
75263 #endif
75264 case TK_VARIABLE: {
75265 assert( !ExprHasProperty(pExpr, EP_IntValue) );
75266 assert( pExpr->u.zToken!=0 );
75267 assert( pExpr->u.zToken[0]!=0 );
75268 sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
75269 if( pExpr->u.zToken[1]!=0 ){
75270 assert( pExpr->u.zToken[0]=='?'
75271 || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
75272 sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
75274 break;
75276 case TK_REGISTER: {
75277 inReg = pExpr->iTable;
75278 break;
75280 case TK_AS: {
75281 inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
75282 break;
75284 #ifndef SQLITE_OMIT_CAST
75285 case TK_CAST: {
75286 /* Expressions of the form: CAST(pLeft AS token) */
75287 int aff, to_op;
75288 inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
75289 assert( !ExprHasProperty(pExpr, EP_IntValue) );
75290 aff = sqlite3AffinityType(pExpr->u.zToken);
75291 to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
75292 assert( to_op==OP_ToText || aff!=SQLITE_AFF_TEXT );
75293 assert( to_op==OP_ToBlob || aff!=SQLITE_AFF_NONE );
75294 assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
75295 assert( to_op==OP_ToInt || aff!=SQLITE_AFF_INTEGER );
75296 assert( to_op==OP_ToReal || aff!=SQLITE_AFF_REAL );
75297 testcase( to_op==OP_ToText );
75298 testcase( to_op==OP_ToBlob );
75299 testcase( to_op==OP_ToNumeric );
75300 testcase( to_op==OP_ToInt );
75301 testcase( to_op==OP_ToReal );
75302 if( inReg!=target ){
75303 sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
75304 inReg = target;
75306 sqlite3VdbeAddOp1(v, to_op, inReg);
75307 testcase( usedAsColumnCache(pParse, inReg, inReg) );
75308 sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
75309 break;
75311 #endif /* SQLITE_OMIT_CAST */
75312 case TK_LT:
75313 case TK_LE:
75314 case TK_GT:
75315 case TK_GE:
75316 case TK_NE:
75317 case TK_EQ: {
75318 assert( TK_LT==OP_Lt );
75319 assert( TK_LE==OP_Le );
75320 assert( TK_GT==OP_Gt );
75321 assert( TK_GE==OP_Ge );
75322 assert( TK_EQ==OP_Eq );
75323 assert( TK_NE==OP_Ne );
75324 testcase( op==TK_LT );
75325 testcase( op==TK_LE );
75326 testcase( op==TK_GT );
75327 testcase( op==TK_GE );
75328 testcase( op==TK_EQ );
75329 testcase( op==TK_NE );
75330 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
75331 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
75332 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
75333 r1, r2, inReg, SQLITE_STOREP2);
75334 testcase( regFree1==0 );
75335 testcase( regFree2==0 );
75336 break;
75338 case TK_IS:
75339 case TK_ISNOT: {
75340 testcase( op==TK_IS );
75341 testcase( op==TK_ISNOT );
75342 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
75343 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
75344 op = (op==TK_IS) ? TK_EQ : TK_NE;
75345 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
75346 r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
75347 testcase( regFree1==0 );
75348 testcase( regFree2==0 );
75349 break;
75351 case TK_AND:
75352 case TK_OR:
75353 case TK_PLUS:
75354 case TK_STAR:
75355 case TK_MINUS:
75356 case TK_REM:
75357 case TK_BITAND:
75358 case TK_BITOR:
75359 case TK_SLASH:
75360 case TK_LSHIFT:
75361 case TK_RSHIFT:
75362 case TK_CONCAT: {
75363 assert( TK_AND==OP_And );
75364 assert( TK_OR==OP_Or );
75365 assert( TK_PLUS==OP_Add );
75366 assert( TK_MINUS==OP_Subtract );
75367 assert( TK_REM==OP_Remainder );
75368 assert( TK_BITAND==OP_BitAnd );
75369 assert( TK_BITOR==OP_BitOr );
75370 assert( TK_SLASH==OP_Divide );
75371 assert( TK_LSHIFT==OP_ShiftLeft );
75372 assert( TK_RSHIFT==OP_ShiftRight );
75373 assert( TK_CONCAT==OP_Concat );
75374 testcase( op==TK_AND );
75375 testcase( op==TK_OR );
75376 testcase( op==TK_PLUS );
75377 testcase( op==TK_MINUS );
75378 testcase( op==TK_REM );
75379 testcase( op==TK_BITAND );
75380 testcase( op==TK_BITOR );
75381 testcase( op==TK_SLASH );
75382 testcase( op==TK_LSHIFT );
75383 testcase( op==TK_RSHIFT );
75384 testcase( op==TK_CONCAT );
75385 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
75386 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
75387 sqlite3VdbeAddOp3(v, op, r2, r1, target);
75388 testcase( regFree1==0 );
75389 testcase( regFree2==0 );
75390 break;
75392 case TK_UMINUS: {
75393 Expr *pLeft = pExpr->pLeft;
75394 assert( pLeft );
75395 if( pLeft->op==TK_INTEGER ){
75396 codeInteger(pParse, pLeft, 1, target);
75397 #ifndef SQLITE_OMIT_FLOATING_POINT
75398 }else if( pLeft->op==TK_FLOAT ){
75399 assert( !ExprHasProperty(pExpr, EP_IntValue) );
75400 codeReal(v, pLeft->u.zToken, 1, target);
75401 #endif
75402 }else{
75403 regFree1 = r1 = sqlite3GetTempReg(pParse);
75404 sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
75405 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
75406 sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
75407 testcase( regFree2==0 );
75409 inReg = target;
75410 break;
75412 case TK_BITNOT:
75413 case TK_NOT: {
75414 assert( TK_BITNOT==OP_BitNot );
75415 assert( TK_NOT==OP_Not );
75416 testcase( op==TK_BITNOT );
75417 testcase( op==TK_NOT );
75418 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
75419 testcase( regFree1==0 );
75420 inReg = target;
75421 sqlite3VdbeAddOp2(v, op, r1, inReg);
75422 break;
75424 case TK_ISNULL:
75425 case TK_NOTNULL: {
75426 int addr;
75427 assert( TK_ISNULL==OP_IsNull );
75428 assert( TK_NOTNULL==OP_NotNull );
75429 testcase( op==TK_ISNULL );
75430 testcase( op==TK_NOTNULL );
75431 sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
75432 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
75433 testcase( regFree1==0 );
75434 addr = sqlite3VdbeAddOp1(v, op, r1);
75435 sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
75436 sqlite3VdbeJumpHere(v, addr);
75437 break;
75439 case TK_AGG_FUNCTION: {
75440 AggInfo *pInfo = pExpr->pAggInfo;
75441 if( pInfo==0 ){
75442 assert( !ExprHasProperty(pExpr, EP_IntValue) );
75443 sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
75444 }else{
75445 inReg = pInfo->aFunc[pExpr->iAgg].iMem;
75447 break;
75449 case TK_CONST_FUNC:
75450 case TK_FUNCTION: {
75451 ExprList *pFarg; /* List of function arguments */
75452 int nFarg; /* Number of function arguments */
75453 FuncDef *pDef; /* The function definition object */
75454 int nId; /* Length of the function name in bytes */
75455 const char *zId; /* The function name */
75456 int constMask = 0; /* Mask of function arguments that are constant */
75457 int i; /* Loop counter */
75458 u8 enc = ENC(db); /* The text encoding used by this database */
75459 CollSeq *pColl = 0; /* A collating sequence */
75461 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
75462 testcase( op==TK_CONST_FUNC );
75463 testcase( op==TK_FUNCTION );
75464 if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
75465 pFarg = 0;
75466 }else{
75467 pFarg = pExpr->x.pList;
75469 nFarg = pFarg ? pFarg->nExpr : 0;
75470 assert( !ExprHasProperty(pExpr, EP_IntValue) );
75471 zId = pExpr->u.zToken;
75472 nId = sqlite3Strlen30(zId);
75473 pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
75474 if( pDef==0 ){
75475 sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
75476 break;
75479 /* Attempt a direct implementation of the built-in COALESCE() and
75480 ** IFNULL() functions. This avoids unnecessary evalation of
75481 ** arguments past the first non-NULL argument.
75483 if( pDef->flags & SQLITE_FUNC_COALESCE ){
75484 int endCoalesce = sqlite3VdbeMakeLabel(v);
75485 assert( nFarg>=2 );
75486 sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
75487 for(i=1; i<nFarg; i++){
75488 sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
75489 sqlite3ExprCacheRemove(pParse, target, 1);
75490 sqlite3ExprCachePush(pParse);
75491 sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
75492 sqlite3ExprCachePop(pParse, 1);
75494 sqlite3VdbeResolveLabel(v, endCoalesce);
75495 break;
75499 if( pFarg ){
75500 r1 = sqlite3GetTempRange(pParse, nFarg);
75501 sqlite3ExprCachePush(pParse); /* Ticket 2ea2425d34be */
75502 sqlite3ExprCodeExprList(pParse, pFarg, r1, 1);
75503 sqlite3ExprCachePop(pParse, 1); /* Ticket 2ea2425d34be */
75504 }else{
75505 r1 = 0;
75507 #ifndef SQLITE_OMIT_VIRTUALTABLE
75508 /* Possibly overload the function if the first argument is
75509 ** a virtual table column.
75511 ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
75512 ** second argument, not the first, as the argument to test to
75513 ** see if it is a column in a virtual table. This is done because
75514 ** the left operand of infix functions (the operand we want to
75515 ** control overloading) ends up as the second argument to the
75516 ** function. The expression "A glob B" is equivalent to
75517 ** "glob(B,A). We want to use the A in "A glob B" to test
75518 ** for function overloading. But we use the B term in "glob(B,A)".
75520 if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
75521 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
75522 }else if( nFarg>0 ){
75523 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
75525 #endif
75526 for(i=0; i<nFarg; i++){
75527 if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
75528 constMask |= (1<<i);
75530 if( (pDef->flags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
75531 pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
75534 if( pDef->flags & SQLITE_FUNC_NEEDCOLL ){
75535 if( !pColl ) pColl = db->pDfltColl;
75536 sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
75538 sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
75539 (char*)pDef, P4_FUNCDEF);
75540 sqlite3VdbeChangeP5(v, (u8)nFarg);
75541 if( nFarg ){
75542 sqlite3ReleaseTempRange(pParse, r1, nFarg);
75544 break;
75546 #ifndef SQLITE_OMIT_SUBQUERY
75547 case TK_EXISTS:
75548 case TK_SELECT: {
75549 testcase( op==TK_EXISTS );
75550 testcase( op==TK_SELECT );
75551 inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
75552 break;
75554 case TK_IN: {
75555 int destIfFalse = sqlite3VdbeMakeLabel(v);
75556 int destIfNull = sqlite3VdbeMakeLabel(v);
75557 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
75558 sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
75559 sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
75560 sqlite3VdbeResolveLabel(v, destIfFalse);
75561 sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
75562 sqlite3VdbeResolveLabel(v, destIfNull);
75563 break;
75565 #endif /* SQLITE_OMIT_SUBQUERY */
75569 ** x BETWEEN y AND z
75571 ** This is equivalent to
75573 ** x>=y AND x<=z
75575 ** X is stored in pExpr->pLeft.
75576 ** Y is stored in pExpr->pList->a[0].pExpr.
75577 ** Z is stored in pExpr->pList->a[1].pExpr.
75579 case TK_BETWEEN: {
75580 Expr *pLeft = pExpr->pLeft;
75581 struct ExprList_item *pLItem = pExpr->x.pList->a;
75582 Expr *pRight = pLItem->pExpr;
75584 r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
75585 r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
75586 testcase( regFree1==0 );
75587 testcase( regFree2==0 );
75588 r3 = sqlite3GetTempReg(pParse);
75589 r4 = sqlite3GetTempReg(pParse);
75590 codeCompare(pParse, pLeft, pRight, OP_Ge,
75591 r1, r2, r3, SQLITE_STOREP2);
75592 pLItem++;
75593 pRight = pLItem->pExpr;
75594 sqlite3ReleaseTempReg(pParse, regFree2);
75595 r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
75596 testcase( regFree2==0 );
75597 codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
75598 sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
75599 sqlite3ReleaseTempReg(pParse, r3);
75600 sqlite3ReleaseTempReg(pParse, r4);
75601 break;
75603 case TK_UPLUS: {
75604 inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
75605 break;
75608 case TK_TRIGGER: {
75609 /* If the opcode is TK_TRIGGER, then the expression is a reference
75610 ** to a column in the new.* or old.* pseudo-tables available to
75611 ** trigger programs. In this case Expr.iTable is set to 1 for the
75612 ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
75613 ** is set to the column of the pseudo-table to read, or to -1 to
75614 ** read the rowid field.
75616 ** The expression is implemented using an OP_Param opcode. The p1
75617 ** parameter is set to 0 for an old.rowid reference, or to (i+1)
75618 ** to reference another column of the old.* pseudo-table, where
75619 ** i is the index of the column. For a new.rowid reference, p1 is
75620 ** set to (n+1), where n is the number of columns in each pseudo-table.
75621 ** For a reference to any other column in the new.* pseudo-table, p1
75622 ** is set to (n+2+i), where n and i are as defined previously. For
75623 ** example, if the table on which triggers are being fired is
75624 ** declared as:
75626 ** CREATE TABLE t1(a, b);
75628 ** Then p1 is interpreted as follows:
75630 ** p1==0 -> old.rowid p1==3 -> new.rowid
75631 ** p1==1 -> old.a p1==4 -> new.a
75632 ** p1==2 -> old.b p1==5 -> new.b
75634 Table *pTab = pExpr->pTab;
75635 int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
75637 assert( pExpr->iTable==0 || pExpr->iTable==1 );
75638 assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
75639 assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
75640 assert( p1>=0 && p1<(pTab->nCol*2+2) );
75642 sqlite3VdbeAddOp2(v, OP_Param, p1, target);
75643 VdbeComment((v, "%s.%s -> $%d",
75644 (pExpr->iTable ? "new" : "old"),
75645 (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
75646 target
75649 #ifndef SQLITE_OMIT_FLOATING_POINT
75650 /* If the column has REAL affinity, it may currently be stored as an
75651 ** integer. Use OP_RealAffinity to make sure it is really real. */
75652 if( pExpr->iColumn>=0
75653 && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
75655 sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
75657 #endif
75658 break;
75663 ** Form A:
75664 ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
75666 ** Form B:
75667 ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
75669 ** Form A is can be transformed into the equivalent form B as follows:
75670 ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
75671 ** WHEN x=eN THEN rN ELSE y END
75673 ** X (if it exists) is in pExpr->pLeft.
75674 ** Y is in pExpr->pRight. The Y is also optional. If there is no
75675 ** ELSE clause and no other term matches, then the result of the
75676 ** exprssion is NULL.
75677 ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
75679 ** The result of the expression is the Ri for the first matching Ei,
75680 ** or if there is no matching Ei, the ELSE term Y, or if there is
75681 ** no ELSE term, NULL.
75683 default: assert( op==TK_CASE ); {
75684 int endLabel; /* GOTO label for end of CASE stmt */
75685 int nextCase; /* GOTO label for next WHEN clause */
75686 int nExpr; /* 2x number of WHEN terms */
75687 int i; /* Loop counter */
75688 ExprList *pEList; /* List of WHEN terms */
75689 struct ExprList_item *aListelem; /* Array of WHEN terms */
75690 Expr opCompare; /* The X==Ei expression */
75691 Expr cacheX; /* Cached expression X */
75692 Expr *pX; /* The X expression */
75693 Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
75694 VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
75696 assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
75697 assert((pExpr->x.pList->nExpr % 2) == 0);
75698 assert(pExpr->x.pList->nExpr > 0);
75699 pEList = pExpr->x.pList;
75700 aListelem = pEList->a;
75701 nExpr = pEList->nExpr;
75702 endLabel = sqlite3VdbeMakeLabel(v);
75703 if( (pX = pExpr->pLeft)!=0 ){
75704 cacheX = *pX;
75705 testcase( pX->op==TK_COLUMN );
75706 testcase( pX->op==TK_REGISTER );
75707 cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, &regFree1);
75708 testcase( regFree1==0 );
75709 cacheX.op = TK_REGISTER;
75710 opCompare.op = TK_EQ;
75711 opCompare.pLeft = &cacheX;
75712 pTest = &opCompare;
75713 /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
75714 ** The value in regFree1 might get SCopy-ed into the file result.
75715 ** So make sure that the regFree1 register is not reused for other
75716 ** purposes and possibly overwritten. */
75717 regFree1 = 0;
75719 for(i=0; i<nExpr; i=i+2){
75720 sqlite3ExprCachePush(pParse);
75721 if( pX ){
75722 assert( pTest!=0 );
75723 opCompare.pRight = aListelem[i].pExpr;
75724 }else{
75725 pTest = aListelem[i].pExpr;
75727 nextCase = sqlite3VdbeMakeLabel(v);
75728 testcase( pTest->op==TK_COLUMN );
75729 sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
75730 testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
75731 testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
75732 sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
75733 sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
75734 sqlite3ExprCachePop(pParse, 1);
75735 sqlite3VdbeResolveLabel(v, nextCase);
75737 if( pExpr->pRight ){
75738 sqlite3ExprCachePush(pParse);
75739 sqlite3ExprCode(pParse, pExpr->pRight, target);
75740 sqlite3ExprCachePop(pParse, 1);
75741 }else{
75742 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
75744 assert( db->mallocFailed || pParse->nErr>0
75745 || pParse->iCacheLevel==iCacheLevel );
75746 sqlite3VdbeResolveLabel(v, endLabel);
75747 break;
75749 #ifndef SQLITE_OMIT_TRIGGER
75750 case TK_RAISE: {
75751 assert( pExpr->affinity==OE_Rollback
75752 || pExpr->affinity==OE_Abort
75753 || pExpr->affinity==OE_Fail
75754 || pExpr->affinity==OE_Ignore
75756 if( !pParse->pTriggerTab ){
75757 sqlite3ErrorMsg(pParse,
75758 "RAISE() may only be used within a trigger-program");
75759 return 0;
75761 if( pExpr->affinity==OE_Abort ){
75762 sqlite3MayAbort(pParse);
75764 assert( !ExprHasProperty(pExpr, EP_IntValue) );
75765 if( pExpr->affinity==OE_Ignore ){
75766 sqlite3VdbeAddOp4(
75767 v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
75768 }else{
75769 sqlite3HaltConstraint(pParse, pExpr->affinity, pExpr->u.zToken, 0);
75772 break;
75774 #endif
75776 sqlite3ReleaseTempReg(pParse, regFree1);
75777 sqlite3ReleaseTempReg(pParse, regFree2);
75778 return inReg;
75782 ** Generate code to evaluate an expression and store the results
75783 ** into a register. Return the register number where the results
75784 ** are stored.
75786 ** If the register is a temporary register that can be deallocated,
75787 ** then write its number into *pReg. If the result register is not
75788 ** a temporary, then set *pReg to zero.
75790 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
75791 int r1 = sqlite3GetTempReg(pParse);
75792 int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
75793 if( r2==r1 ){
75794 *pReg = r1;
75795 }else{
75796 sqlite3ReleaseTempReg(pParse, r1);
75797 *pReg = 0;
75799 return r2;
75803 ** Generate code that will evaluate expression pExpr and store the
75804 ** results in register target. The results are guaranteed to appear
75805 ** in register target.
75807 SQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
75808 int inReg;
75810 assert( target>0 && target<=pParse->nMem );
75811 if( pExpr && pExpr->op==TK_REGISTER ){
75812 sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
75813 }else{
75814 inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
75815 assert( pParse->pVdbe || pParse->db->mallocFailed );
75816 if( inReg!=target && pParse->pVdbe ){
75817 sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
75820 return target;
75824 ** Generate code that evalutes the given expression and puts the result
75825 ** in register target.
75827 ** Also make a copy of the expression results into another "cache" register
75828 ** and modify the expression so that the next time it is evaluated,
75829 ** the result is a copy of the cache register.
75831 ** This routine is used for expressions that are used multiple
75832 ** times. They are evaluated once and the results of the expression
75833 ** are reused.
75835 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
75836 Vdbe *v = pParse->pVdbe;
75837 int inReg;
75838 inReg = sqlite3ExprCode(pParse, pExpr, target);
75839 assert( target>0 );
75840 /* This routine is called for terms to INSERT or UPDATE. And the only
75841 ** other place where expressions can be converted into TK_REGISTER is
75842 ** in WHERE clause processing. So as currently implemented, there is
75843 ** no way for a TK_REGISTER to exist here. But it seems prudent to
75844 ** keep the ALWAYS() in case the conditions above change with future
75845 ** modifications or enhancements. */
75846 if( ALWAYS(pExpr->op!=TK_REGISTER) ){
75847 int iMem;
75848 iMem = ++pParse->nMem;
75849 sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
75850 pExpr->iTable = iMem;
75851 pExpr->op2 = pExpr->op;
75852 pExpr->op = TK_REGISTER;
75854 return inReg;
75858 ** Return TRUE if pExpr is an constant expression that is appropriate
75859 ** for factoring out of a loop. Appropriate expressions are:
75861 ** * Any expression that evaluates to two or more opcodes.
75863 ** * Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null,
75864 ** or OP_Variable that does not need to be placed in a
75865 ** specific register.
75867 ** There is no point in factoring out single-instruction constant
75868 ** expressions that need to be placed in a particular register.
75869 ** We could factor them out, but then we would end up adding an
75870 ** OP_SCopy instruction to move the value into the correct register
75871 ** later. We might as well just use the original instruction and
75872 ** avoid the OP_SCopy.
75874 static int isAppropriateForFactoring(Expr *p){
75875 if( !sqlite3ExprIsConstantNotJoin(p) ){
75876 return 0; /* Only constant expressions are appropriate for factoring */
75878 if( (p->flags & EP_FixedDest)==0 ){
75879 return 1; /* Any constant without a fixed destination is appropriate */
75881 while( p->op==TK_UPLUS ) p = p->pLeft;
75882 switch( p->op ){
75883 #ifndef SQLITE_OMIT_BLOB_LITERAL
75884 case TK_BLOB:
75885 #endif
75886 case TK_VARIABLE:
75887 case TK_INTEGER:
75888 case TK_FLOAT:
75889 case TK_NULL:
75890 case TK_STRING: {
75891 testcase( p->op==TK_BLOB );
75892 testcase( p->op==TK_VARIABLE );
75893 testcase( p->op==TK_INTEGER );
75894 testcase( p->op==TK_FLOAT );
75895 testcase( p->op==TK_NULL );
75896 testcase( p->op==TK_STRING );
75897 /* Single-instruction constants with a fixed destination are
75898 ** better done in-line. If we factor them, they will just end
75899 ** up generating an OP_SCopy to move the value to the destination
75900 ** register. */
75901 return 0;
75903 case TK_UMINUS: {
75904 if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
75905 return 0;
75907 break;
75909 default: {
75910 break;
75913 return 1;
75917 ** If pExpr is a constant expression that is appropriate for
75918 ** factoring out of a loop, then evaluate the expression
75919 ** into a register and convert the expression into a TK_REGISTER
75920 ** expression.
75922 static int evalConstExpr(Walker *pWalker, Expr *pExpr){
75923 Parse *pParse = pWalker->pParse;
75924 switch( pExpr->op ){
75925 case TK_IN:
75926 case TK_REGISTER: {
75927 return WRC_Prune;
75929 case TK_FUNCTION:
75930 case TK_AGG_FUNCTION:
75931 case TK_CONST_FUNC: {
75932 /* The arguments to a function have a fixed destination.
75933 ** Mark them this way to avoid generated unneeded OP_SCopy
75934 ** instructions.
75936 ExprList *pList = pExpr->x.pList;
75937 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
75938 if( pList ){
75939 int i = pList->nExpr;
75940 struct ExprList_item *pItem = pList->a;
75941 for(; i>0; i--, pItem++){
75942 if( ALWAYS(pItem->pExpr) ) pItem->pExpr->flags |= EP_FixedDest;
75945 break;
75948 if( isAppropriateForFactoring(pExpr) ){
75949 int r1 = ++pParse->nMem;
75950 int r2;
75951 r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
75952 if( NEVER(r1!=r2) ) sqlite3ReleaseTempReg(pParse, r1);
75953 pExpr->op2 = pExpr->op;
75954 pExpr->op = TK_REGISTER;
75955 pExpr->iTable = r2;
75956 return WRC_Prune;
75958 return WRC_Continue;
75962 ** Preevaluate constant subexpressions within pExpr and store the
75963 ** results in registers. Modify pExpr so that the constant subexpresions
75964 ** are TK_REGISTER opcodes that refer to the precomputed values.
75966 ** This routine is a no-op if the jump to the cookie-check code has
75967 ** already occur. Since the cookie-check jump is generated prior to
75968 ** any other serious processing, this check ensures that there is no
75969 ** way to accidently bypass the constant initializations.
75971 ** This routine is also a no-op if the SQLITE_FactorOutConst optimization
75972 ** is disabled via the sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS)
75973 ** interface. This allows test logic to verify that the same answer is
75974 ** obtained for queries regardless of whether or not constants are
75975 ** precomputed into registers or if they are inserted in-line.
75977 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
75978 Walker w;
75979 if( pParse->cookieGoto ) return;
75980 if( (pParse->db->flags & SQLITE_FactorOutConst)!=0 ) return;
75981 w.xExprCallback = evalConstExpr;
75982 w.xSelectCallback = 0;
75983 w.pParse = pParse;
75984 sqlite3WalkExpr(&w, pExpr);
75989 ** Generate code that pushes the value of every element of the given
75990 ** expression list into a sequence of registers beginning at target.
75992 ** Return the number of elements evaluated.
75994 SQLITE_PRIVATE int sqlite3ExprCodeExprList(
75995 Parse *pParse, /* Parsing context */
75996 ExprList *pList, /* The expression list to be coded */
75997 int target, /* Where to write results */
75998 int doHardCopy /* Make a hard copy of every element */
76000 struct ExprList_item *pItem;
76001 int i, n;
76002 assert( pList!=0 );
76003 assert( target>0 );
76004 assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
76005 n = pList->nExpr;
76006 for(pItem=pList->a, i=0; i<n; i++, pItem++){
76007 Expr *pExpr = pItem->pExpr;
76008 int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
76009 if( inReg!=target+i ){
76010 sqlite3VdbeAddOp2(pParse->pVdbe, doHardCopy ? OP_Copy : OP_SCopy,
76011 inReg, target+i);
76014 return n;
76018 ** Generate code for a BETWEEN operator.
76020 ** x BETWEEN y AND z
76022 ** The above is equivalent to
76024 ** x>=y AND x<=z
76026 ** Code it as such, taking care to do the common subexpression
76027 ** elementation of x.
76029 static void exprCodeBetween(
76030 Parse *pParse, /* Parsing and code generating context */
76031 Expr *pExpr, /* The BETWEEN expression */
76032 int dest, /* Jump here if the jump is taken */
76033 int jumpIfTrue, /* Take the jump if the BETWEEN is true */
76034 int jumpIfNull /* Take the jump if the BETWEEN is NULL */
76036 Expr exprAnd; /* The AND operator in x>=y AND x<=z */
76037 Expr compLeft; /* The x>=y term */
76038 Expr compRight; /* The x<=z term */
76039 Expr exprX; /* The x subexpression */
76040 int regFree1 = 0; /* Temporary use register */
76042 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
76043 exprX = *pExpr->pLeft;
76044 exprAnd.op = TK_AND;
76045 exprAnd.pLeft = &compLeft;
76046 exprAnd.pRight = &compRight;
76047 compLeft.op = TK_GE;
76048 compLeft.pLeft = &exprX;
76049 compLeft.pRight = pExpr->x.pList->a[0].pExpr;
76050 compRight.op = TK_LE;
76051 compRight.pLeft = &exprX;
76052 compRight.pRight = pExpr->x.pList->a[1].pExpr;
76053 exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
76054 exprX.op = TK_REGISTER;
76055 if( jumpIfTrue ){
76056 sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
76057 }else{
76058 sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
76060 sqlite3ReleaseTempReg(pParse, regFree1);
76062 /* Ensure adequate test coverage */
76063 testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
76064 testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
76065 testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
76066 testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
76067 testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
76068 testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
76069 testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
76070 testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
76074 ** Generate code for a boolean expression such that a jump is made
76075 ** to the label "dest" if the expression is true but execution
76076 ** continues straight thru if the expression is false.
76078 ** If the expression evaluates to NULL (neither true nor false), then
76079 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
76081 ** This code depends on the fact that certain token values (ex: TK_EQ)
76082 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
76083 ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
76084 ** the make process cause these values to align. Assert()s in the code
76085 ** below verify that the numbers are aligned correctly.
76087 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
76088 Vdbe *v = pParse->pVdbe;
76089 int op = 0;
76090 int regFree1 = 0;
76091 int regFree2 = 0;
76092 int r1, r2;
76094 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
76095 if( NEVER(v==0) ) return; /* Existance of VDBE checked by caller */
76096 if( NEVER(pExpr==0) ) return; /* No way this can happen */
76097 op = pExpr->op;
76098 switch( op ){
76099 case TK_AND: {
76100 int d2 = sqlite3VdbeMakeLabel(v);
76101 testcase( jumpIfNull==0 );
76102 sqlite3ExprCachePush(pParse);
76103 sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
76104 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
76105 sqlite3VdbeResolveLabel(v, d2);
76106 sqlite3ExprCachePop(pParse, 1);
76107 break;
76109 case TK_OR: {
76110 testcase( jumpIfNull==0 );
76111 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
76112 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
76113 break;
76115 case TK_NOT: {
76116 testcase( jumpIfNull==0 );
76117 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
76118 break;
76120 case TK_LT:
76121 case TK_LE:
76122 case TK_GT:
76123 case TK_GE:
76124 case TK_NE:
76125 case TK_EQ: {
76126 assert( TK_LT==OP_Lt );
76127 assert( TK_LE==OP_Le );
76128 assert( TK_GT==OP_Gt );
76129 assert( TK_GE==OP_Ge );
76130 assert( TK_EQ==OP_Eq );
76131 assert( TK_NE==OP_Ne );
76132 testcase( op==TK_LT );
76133 testcase( op==TK_LE );
76134 testcase( op==TK_GT );
76135 testcase( op==TK_GE );
76136 testcase( op==TK_EQ );
76137 testcase( op==TK_NE );
76138 testcase( jumpIfNull==0 );
76139 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
76140 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
76141 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
76142 r1, r2, dest, jumpIfNull);
76143 testcase( regFree1==0 );
76144 testcase( regFree2==0 );
76145 break;
76147 case TK_IS:
76148 case TK_ISNOT: {
76149 testcase( op==TK_IS );
76150 testcase( op==TK_ISNOT );
76151 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
76152 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
76153 op = (op==TK_IS) ? TK_EQ : TK_NE;
76154 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
76155 r1, r2, dest, SQLITE_NULLEQ);
76156 testcase( regFree1==0 );
76157 testcase( regFree2==0 );
76158 break;
76160 case TK_ISNULL:
76161 case TK_NOTNULL: {
76162 assert( TK_ISNULL==OP_IsNull );
76163 assert( TK_NOTNULL==OP_NotNull );
76164 testcase( op==TK_ISNULL );
76165 testcase( op==TK_NOTNULL );
76166 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
76167 sqlite3VdbeAddOp2(v, op, r1, dest);
76168 testcase( regFree1==0 );
76169 break;
76171 case TK_BETWEEN: {
76172 testcase( jumpIfNull==0 );
76173 exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
76174 break;
76176 #ifndef SQLITE_OMIT_SUBQUERY
76177 case TK_IN: {
76178 int destIfFalse = sqlite3VdbeMakeLabel(v);
76179 int destIfNull = jumpIfNull ? dest : destIfFalse;
76180 sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
76181 sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
76182 sqlite3VdbeResolveLabel(v, destIfFalse);
76183 break;
76185 #endif
76186 default: {
76187 r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
76188 sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
76189 testcase( regFree1==0 );
76190 testcase( jumpIfNull==0 );
76191 break;
76194 sqlite3ReleaseTempReg(pParse, regFree1);
76195 sqlite3ReleaseTempReg(pParse, regFree2);
76199 ** Generate code for a boolean expression such that a jump is made
76200 ** to the label "dest" if the expression is false but execution
76201 ** continues straight thru if the expression is true.
76203 ** If the expression evaluates to NULL (neither true nor false) then
76204 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
76205 ** is 0.
76207 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
76208 Vdbe *v = pParse->pVdbe;
76209 int op = 0;
76210 int regFree1 = 0;
76211 int regFree2 = 0;
76212 int r1, r2;
76214 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
76215 if( NEVER(v==0) ) return; /* Existance of VDBE checked by caller */
76216 if( pExpr==0 ) return;
76218 /* The value of pExpr->op and op are related as follows:
76220 ** pExpr->op op
76221 ** --------- ----------
76222 ** TK_ISNULL OP_NotNull
76223 ** TK_NOTNULL OP_IsNull
76224 ** TK_NE OP_Eq
76225 ** TK_EQ OP_Ne
76226 ** TK_GT OP_Le
76227 ** TK_LE OP_Gt
76228 ** TK_GE OP_Lt
76229 ** TK_LT OP_Ge
76231 ** For other values of pExpr->op, op is undefined and unused.
76232 ** The value of TK_ and OP_ constants are arranged such that we
76233 ** can compute the mapping above using the following expression.
76234 ** Assert()s verify that the computation is correct.
76236 op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
76238 /* Verify correct alignment of TK_ and OP_ constants
76240 assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
76241 assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
76242 assert( pExpr->op!=TK_NE || op==OP_Eq );
76243 assert( pExpr->op!=TK_EQ || op==OP_Ne );
76244 assert( pExpr->op!=TK_LT || op==OP_Ge );
76245 assert( pExpr->op!=TK_LE || op==OP_Gt );
76246 assert( pExpr->op!=TK_GT || op==OP_Le );
76247 assert( pExpr->op!=TK_GE || op==OP_Lt );
76249 switch( pExpr->op ){
76250 case TK_AND: {
76251 testcase( jumpIfNull==0 );
76252 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
76253 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
76254 break;
76256 case TK_OR: {
76257 int d2 = sqlite3VdbeMakeLabel(v);
76258 testcase( jumpIfNull==0 );
76259 sqlite3ExprCachePush(pParse);
76260 sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
76261 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
76262 sqlite3VdbeResolveLabel(v, d2);
76263 sqlite3ExprCachePop(pParse, 1);
76264 break;
76266 case TK_NOT: {
76267 testcase( jumpIfNull==0 );
76268 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
76269 break;
76271 case TK_LT:
76272 case TK_LE:
76273 case TK_GT:
76274 case TK_GE:
76275 case TK_NE:
76276 case TK_EQ: {
76277 testcase( op==TK_LT );
76278 testcase( op==TK_LE );
76279 testcase( op==TK_GT );
76280 testcase( op==TK_GE );
76281 testcase( op==TK_EQ );
76282 testcase( op==TK_NE );
76283 testcase( jumpIfNull==0 );
76284 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
76285 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
76286 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
76287 r1, r2, dest, jumpIfNull);
76288 testcase( regFree1==0 );
76289 testcase( regFree2==0 );
76290 break;
76292 case TK_IS:
76293 case TK_ISNOT: {
76294 testcase( pExpr->op==TK_IS );
76295 testcase( pExpr->op==TK_ISNOT );
76296 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
76297 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
76298 op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
76299 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
76300 r1, r2, dest, SQLITE_NULLEQ);
76301 testcase( regFree1==0 );
76302 testcase( regFree2==0 );
76303 break;
76305 case TK_ISNULL:
76306 case TK_NOTNULL: {
76307 testcase( op==TK_ISNULL );
76308 testcase( op==TK_NOTNULL );
76309 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
76310 sqlite3VdbeAddOp2(v, op, r1, dest);
76311 testcase( regFree1==0 );
76312 break;
76314 case TK_BETWEEN: {
76315 testcase( jumpIfNull==0 );
76316 exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
76317 break;
76319 #ifndef SQLITE_OMIT_SUBQUERY
76320 case TK_IN: {
76321 if( jumpIfNull ){
76322 sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
76323 }else{
76324 int destIfNull = sqlite3VdbeMakeLabel(v);
76325 sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
76326 sqlite3VdbeResolveLabel(v, destIfNull);
76328 break;
76330 #endif
76331 default: {
76332 r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
76333 sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
76334 testcase( regFree1==0 );
76335 testcase( jumpIfNull==0 );
76336 break;
76339 sqlite3ReleaseTempReg(pParse, regFree1);
76340 sqlite3ReleaseTempReg(pParse, regFree2);
76344 ** Do a deep comparison of two expression trees. Return 0 if the two
76345 ** expressions are completely identical. Return 1 if they differ only
76346 ** by a COLLATE operator at the top level. Return 2 if there are differences
76347 ** other than the top-level COLLATE operator.
76349 ** Sometimes this routine will return 2 even if the two expressions
76350 ** really are equivalent. If we cannot prove that the expressions are
76351 ** identical, we return 2 just to be safe. So if this routine
76352 ** returns 2, then you do not really know for certain if the two
76353 ** expressions are the same. But if you get a 0 or 1 return, then you
76354 ** can be sure the expressions are the same. In the places where
76355 ** this routine is used, it does not hurt to get an extra 2 - that
76356 ** just might result in some slightly slower code. But returning
76357 ** an incorrect 0 or 1 could lead to a malfunction.
76359 SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB){
76360 if( pA==0||pB==0 ){
76361 return pB==pA ? 0 : 2;
76363 assert( !ExprHasAnyProperty(pA, EP_TokenOnly|EP_Reduced) );
76364 assert( !ExprHasAnyProperty(pB, EP_TokenOnly|EP_Reduced) );
76365 if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){
76366 return 2;
76368 if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
76369 if( pA->op!=pB->op ) return 2;
76370 if( sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 2;
76371 if( sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 2;
76372 if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList) ) return 2;
76373 if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 2;
76374 if( ExprHasProperty(pA, EP_IntValue) ){
76375 if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){
76376 return 2;
76378 }else if( pA->op!=TK_COLUMN && pA->u.zToken ){
76379 if( ExprHasProperty(pB, EP_IntValue) || NEVER(pB->u.zToken==0) ) return 2;
76380 if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
76381 return 2;
76384 if( (pA->flags & EP_ExpCollate)!=(pB->flags & EP_ExpCollate) ) return 1;
76385 if( (pA->flags & EP_ExpCollate)!=0 && pA->pColl!=pB->pColl ) return 2;
76386 return 0;
76390 ** Compare two ExprList objects. Return 0 if they are identical and
76391 ** non-zero if they differ in any way.
76393 ** This routine might return non-zero for equivalent ExprLists. The
76394 ** only consequence will be disabled optimizations. But this routine
76395 ** must never return 0 if the two ExprList objects are different, or
76396 ** a malfunction will result.
76398 ** Two NULL pointers are considered to be the same. But a NULL pointer
76399 ** always differs from a non-NULL pointer.
76401 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB){
76402 int i;
76403 if( pA==0 && pB==0 ) return 0;
76404 if( pA==0 || pB==0 ) return 1;
76405 if( pA->nExpr!=pB->nExpr ) return 1;
76406 for(i=0; i<pA->nExpr; i++){
76407 Expr *pExprA = pA->a[i].pExpr;
76408 Expr *pExprB = pB->a[i].pExpr;
76409 if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
76410 if( sqlite3ExprCompare(pExprA, pExprB) ) return 1;
76412 return 0;
76416 ** Add a new element to the pAggInfo->aCol[] array. Return the index of
76417 ** the new element. Return a negative number if malloc fails.
76419 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
76420 int i;
76421 pInfo->aCol = sqlite3ArrayAllocate(
76423 pInfo->aCol,
76424 sizeof(pInfo->aCol[0]),
76426 &pInfo->nColumn,
76427 &pInfo->nColumnAlloc,
76430 return i;
76434 ** Add a new element to the pAggInfo->aFunc[] array. Return the index of
76435 ** the new element. Return a negative number if malloc fails.
76437 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
76438 int i;
76439 pInfo->aFunc = sqlite3ArrayAllocate(
76440 db,
76441 pInfo->aFunc,
76442 sizeof(pInfo->aFunc[0]),
76444 &pInfo->nFunc,
76445 &pInfo->nFuncAlloc,
76448 return i;
76452 ** This is the xExprCallback for a tree walker. It is used to
76453 ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
76454 ** for additional information.
76456 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
76457 int i;
76458 NameContext *pNC = pWalker->u.pNC;
76459 Parse *pParse = pNC->pParse;
76460 SrcList *pSrcList = pNC->pSrcList;
76461 AggInfo *pAggInfo = pNC->pAggInfo;
76463 switch( pExpr->op ){
76464 case TK_AGG_COLUMN:
76465 case TK_COLUMN: {
76466 testcase( pExpr->op==TK_AGG_COLUMN );
76467 testcase( pExpr->op==TK_COLUMN );
76468 /* Check to see if the column is in one of the tables in the FROM
76469 ** clause of the aggregate query */
76470 if( ALWAYS(pSrcList!=0) ){
76471 struct SrcList_item *pItem = pSrcList->a;
76472 for(i=0; i<pSrcList->nSrc; i++, pItem++){
76473 struct AggInfo_col *pCol;
76474 assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
76475 if( pExpr->iTable==pItem->iCursor ){
76476 /* If we reach this point, it means that pExpr refers to a table
76477 ** that is in the FROM clause of the aggregate query.
76479 ** Make an entry for the column in pAggInfo->aCol[] if there
76480 ** is not an entry there already.
76482 int k;
76483 pCol = pAggInfo->aCol;
76484 for(k=0; k<pAggInfo->nColumn; k++, pCol++){
76485 if( pCol->iTable==pExpr->iTable &&
76486 pCol->iColumn==pExpr->iColumn ){
76487 break;
76490 if( (k>=pAggInfo->nColumn)
76491 && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
76493 pCol = &pAggInfo->aCol[k];
76494 pCol->pTab = pExpr->pTab;
76495 pCol->iTable = pExpr->iTable;
76496 pCol->iColumn = pExpr->iColumn;
76497 pCol->iMem = ++pParse->nMem;
76498 pCol->iSorterColumn = -1;
76499 pCol->pExpr = pExpr;
76500 if( pAggInfo->pGroupBy ){
76501 int j, n;
76502 ExprList *pGB = pAggInfo->pGroupBy;
76503 struct ExprList_item *pTerm = pGB->a;
76504 n = pGB->nExpr;
76505 for(j=0; j<n; j++, pTerm++){
76506 Expr *pE = pTerm->pExpr;
76507 if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
76508 pE->iColumn==pExpr->iColumn ){
76509 pCol->iSorterColumn = j;
76510 break;
76514 if( pCol->iSorterColumn<0 ){
76515 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
76518 /* There is now an entry for pExpr in pAggInfo->aCol[] (either
76519 ** because it was there before or because we just created it).
76520 ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
76521 ** pAggInfo->aCol[] entry.
76523 ExprSetIrreducible(pExpr);
76524 pExpr->pAggInfo = pAggInfo;
76525 pExpr->op = TK_AGG_COLUMN;
76526 pExpr->iAgg = (i16)k;
76527 break;
76528 } /* endif pExpr->iTable==pItem->iCursor */
76529 } /* end loop over pSrcList */
76531 return WRC_Prune;
76533 case TK_AGG_FUNCTION: {
76534 /* The pNC->nDepth==0 test causes aggregate functions in subqueries
76535 ** to be ignored */
76536 if( pNC->nDepth==0 ){
76537 /* Check to see if pExpr is a duplicate of another aggregate
76538 ** function that is already in the pAggInfo structure
76540 struct AggInfo_func *pItem = pAggInfo->aFunc;
76541 for(i=0; i<pAggInfo->nFunc; i++, pItem++){
76542 if( sqlite3ExprCompare(pItem->pExpr, pExpr)==0 ){
76543 break;
76546 if( i>=pAggInfo->nFunc ){
76547 /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
76549 u8 enc = ENC(pParse->db);
76550 i = addAggInfoFunc(pParse->db, pAggInfo);
76551 if( i>=0 ){
76552 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
76553 pItem = &pAggInfo->aFunc[i];
76554 pItem->pExpr = pExpr;
76555 pItem->iMem = ++pParse->nMem;
76556 assert( !ExprHasProperty(pExpr, EP_IntValue) );
76557 pItem->pFunc = sqlite3FindFunction(pParse->db,
76558 pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
76559 pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
76560 if( pExpr->flags & EP_Distinct ){
76561 pItem->iDistinct = pParse->nTab++;
76562 }else{
76563 pItem->iDistinct = -1;
76567 /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
76569 assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
76570 ExprSetIrreducible(pExpr);
76571 pExpr->iAgg = (i16)i;
76572 pExpr->pAggInfo = pAggInfo;
76573 return WRC_Prune;
76577 return WRC_Continue;
76579 static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
76580 NameContext *pNC = pWalker->u.pNC;
76581 if( pNC->nDepth==0 ){
76582 pNC->nDepth++;
76583 sqlite3WalkSelect(pWalker, pSelect);
76584 pNC->nDepth--;
76585 return WRC_Prune;
76586 }else{
76587 return WRC_Continue;
76592 ** Analyze the given expression looking for aggregate functions and
76593 ** for variables that need to be added to the pParse->aAgg[] array.
76594 ** Make additional entries to the pParse->aAgg[] array as necessary.
76596 ** This routine should only be called after the expression has been
76597 ** analyzed by sqlite3ResolveExprNames().
76599 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
76600 Walker w;
76601 w.xExprCallback = analyzeAggregate;
76602 w.xSelectCallback = analyzeAggregatesInSelect;
76603 w.u.pNC = pNC;
76604 assert( pNC->pSrcList!=0 );
76605 sqlite3WalkExpr(&w, pExpr);
76609 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
76610 ** expression list. Return the number of errors.
76612 ** If an error is found, the analysis is cut short.
76614 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
76615 struct ExprList_item *pItem;
76616 int i;
76617 if( pList ){
76618 for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
76619 sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
76625 ** Allocate a single new register for use to hold some intermediate result.
76627 SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
76628 if( pParse->nTempReg==0 ){
76629 return ++pParse->nMem;
76631 return pParse->aTempReg[--pParse->nTempReg];
76635 ** Deallocate a register, making available for reuse for some other
76636 ** purpose.
76638 ** If a register is currently being used by the column cache, then
76639 ** the dallocation is deferred until the column cache line that uses
76640 ** the register becomes stale.
76642 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
76643 if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
76644 int i;
76645 struct yColCache *p;
76646 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
76647 if( p->iReg==iReg ){
76648 p->tempReg = 1;
76649 return;
76652 pParse->aTempReg[pParse->nTempReg++] = iReg;
76657 ** Allocate or deallocate a block of nReg consecutive registers
76659 SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
76660 int i, n;
76661 i = pParse->iRangeReg;
76662 n = pParse->nRangeReg;
76663 if( nReg<=n ){
76664 assert( !usedAsColumnCache(pParse, i, i+n-1) );
76665 pParse->iRangeReg += nReg;
76666 pParse->nRangeReg -= nReg;
76667 }else{
76668 i = pParse->nMem+1;
76669 pParse->nMem += nReg;
76671 return i;
76673 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
76674 sqlite3ExprCacheRemove(pParse, iReg, nReg);
76675 if( nReg>pParse->nRangeReg ){
76676 pParse->nRangeReg = nReg;
76677 pParse->iRangeReg = iReg;
76681 /************** End of expr.c ************************************************/
76682 /************** Begin file alter.c *******************************************/
76684 ** 2005 February 15
76686 ** The author disclaims copyright to this source code. In place of
76687 ** a legal notice, here is a blessing:
76689 ** May you do good and not evil.
76690 ** May you find forgiveness for yourself and forgive others.
76691 ** May you share freely, never taking more than you give.
76693 *************************************************************************
76694 ** This file contains C code routines that used to generate VDBE code
76695 ** that implements the ALTER TABLE command.
76699 ** The code in this file only exists if we are not omitting the
76700 ** ALTER TABLE logic from the build.
76702 #ifndef SQLITE_OMIT_ALTERTABLE
76706 ** This function is used by SQL generated to implement the
76707 ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
76708 ** CREATE INDEX command. The second is a table name. The table name in
76709 ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
76710 ** argument and the result returned. Examples:
76712 ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
76713 ** -> 'CREATE TABLE def(a, b, c)'
76715 ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
76716 ** -> 'CREATE INDEX i ON def(a, b, c)'
76718 static void renameTableFunc(
76719 sqlite3_context *context,
76720 int NotUsed,
76721 sqlite3_value **argv
76723 unsigned char const *zSql = sqlite3_value_text(argv[0]);
76724 unsigned char const *zTableName = sqlite3_value_text(argv[1]);
76726 int token;
76727 Token tname;
76728 unsigned char const *zCsr = zSql;
76729 int len = 0;
76730 char *zRet;
76732 sqlite3 *db = sqlite3_context_db_handle(context);
76734 UNUSED_PARAMETER(NotUsed);
76736 /* The principle used to locate the table name in the CREATE TABLE
76737 ** statement is that the table name is the first non-space token that
76738 ** is immediately followed by a TK_LP or TK_USING token.
76740 if( zSql ){
76741 do {
76742 if( !*zCsr ){
76743 /* Ran out of input before finding an opening bracket. Return NULL. */
76744 return;
76747 /* Store the token that zCsr points to in tname. */
76748 tname.z = (char*)zCsr;
76749 tname.n = len;
76751 /* Advance zCsr to the next token. Store that token type in 'token',
76752 ** and its length in 'len' (to be used next iteration of this loop).
76754 do {
76755 zCsr += len;
76756 len = sqlite3GetToken(zCsr, &token);
76757 } while( token==TK_SPACE );
76758 assert( len>0 );
76759 } while( token!=TK_LP && token!=TK_USING );
76761 zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
76762 zTableName, tname.z+tname.n);
76763 sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
76768 ** This C function implements an SQL user function that is used by SQL code
76769 ** generated by the ALTER TABLE ... RENAME command to modify the definition
76770 ** of any foreign key constraints that use the table being renamed as the
76771 ** parent table. It is passed three arguments:
76773 ** 1) The complete text of the CREATE TABLE statement being modified,
76774 ** 2) The old name of the table being renamed, and
76775 ** 3) The new name of the table being renamed.
76777 ** It returns the new CREATE TABLE statement. For example:
76779 ** sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
76780 ** -> 'CREATE TABLE t1(a REFERENCES t3)'
76782 #ifndef SQLITE_OMIT_FOREIGN_KEY
76783 static void renameParentFunc(
76784 sqlite3_context *context,
76785 int NotUsed,
76786 sqlite3_value **argv
76788 sqlite3 *db = sqlite3_context_db_handle(context);
76789 char *zOutput = 0;
76790 char *zResult;
76791 unsigned char const *zInput = sqlite3_value_text(argv[0]);
76792 unsigned char const *zOld = sqlite3_value_text(argv[1]);
76793 unsigned char const *zNew = sqlite3_value_text(argv[2]);
76795 unsigned const char *z; /* Pointer to token */
76796 int n; /* Length of token z */
76797 int token; /* Type of token */
76799 UNUSED_PARAMETER(NotUsed);
76800 for(z=zInput; *z; z=z+n){
76801 n = sqlite3GetToken(z, &token);
76802 if( token==TK_REFERENCES ){
76803 char *zParent;
76804 do {
76805 z += n;
76806 n = sqlite3GetToken(z, &token);
76807 }while( token==TK_SPACE );
76809 zParent = sqlite3DbStrNDup(db, (const char *)z, n);
76810 if( zParent==0 ) break;
76811 sqlite3Dequote(zParent);
76812 if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
76813 char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
76814 (zOutput?zOutput:""), z-zInput, zInput, (const char *)zNew
76816 sqlite3DbFree(db, zOutput);
76817 zOutput = zOut;
76818 zInput = &z[n];
76820 sqlite3DbFree(db, zParent);
76824 zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
76825 sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
76826 sqlite3DbFree(db, zOutput);
76828 #endif
76830 #ifndef SQLITE_OMIT_TRIGGER
76831 /* This function is used by SQL generated to implement the
76832 ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
76833 ** statement. The second is a table name. The table name in the CREATE
76834 ** TRIGGER statement is replaced with the third argument and the result
76835 ** returned. This is analagous to renameTableFunc() above, except for CREATE
76836 ** TRIGGER, not CREATE INDEX and CREATE TABLE.
76838 static void renameTriggerFunc(
76839 sqlite3_context *context,
76840 int NotUsed,
76841 sqlite3_value **argv
76843 unsigned char const *zSql = sqlite3_value_text(argv[0]);
76844 unsigned char const *zTableName = sqlite3_value_text(argv[1]);
76846 int token;
76847 Token tname;
76848 int dist = 3;
76849 unsigned char const *zCsr = zSql;
76850 int len = 0;
76851 char *zRet;
76852 sqlite3 *db = sqlite3_context_db_handle(context);
76854 UNUSED_PARAMETER(NotUsed);
76856 /* The principle used to locate the table name in the CREATE TRIGGER
76857 ** statement is that the table name is the first token that is immediatedly
76858 ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
76859 ** of TK_WHEN, TK_BEGIN or TK_FOR.
76861 if( zSql ){
76862 do {
76864 if( !*zCsr ){
76865 /* Ran out of input before finding the table name. Return NULL. */
76866 return;
76869 /* Store the token that zCsr points to in tname. */
76870 tname.z = (char*)zCsr;
76871 tname.n = len;
76873 /* Advance zCsr to the next token. Store that token type in 'token',
76874 ** and its length in 'len' (to be used next iteration of this loop).
76876 do {
76877 zCsr += len;
76878 len = sqlite3GetToken(zCsr, &token);
76879 }while( token==TK_SPACE );
76880 assert( len>0 );
76882 /* Variable 'dist' stores the number of tokens read since the most
76883 ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
76884 ** token is read and 'dist' equals 2, the condition stated above
76885 ** to be met.
76887 ** Note that ON cannot be a database, table or column name, so
76888 ** there is no need to worry about syntax like
76889 ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
76891 dist++;
76892 if( token==TK_DOT || token==TK_ON ){
76893 dist = 0;
76895 } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
76897 /* Variable tname now contains the token that is the old table-name
76898 ** in the CREATE TRIGGER statement.
76900 zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
76901 zTableName, tname.z+tname.n);
76902 sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
76905 #endif /* !SQLITE_OMIT_TRIGGER */
76908 ** Register built-in functions used to help implement ALTER TABLE
76910 SQLITE_PRIVATE void sqlite3AlterFunctions(void){
76911 static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
76912 FUNCTION(sqlite_rename_table, 2, 0, 0, renameTableFunc),
76913 #ifndef SQLITE_OMIT_TRIGGER
76914 FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
76915 #endif
76916 #ifndef SQLITE_OMIT_FOREIGN_KEY
76917 FUNCTION(sqlite_rename_parent, 3, 0, 0, renameParentFunc),
76918 #endif
76920 int i;
76921 FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
76922 FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
76924 for(i=0; i<ArraySize(aAlterTableFuncs); i++){
76925 sqlite3FuncDefInsert(pHash, &aFunc[i]);
76930 ** This function is used to create the text of expressions of the form:
76932 ** name=<constant1> OR name=<constant2> OR ...
76934 ** If argument zWhere is NULL, then a pointer string containing the text
76935 ** "name=<constant>" is returned, where <constant> is the quoted version
76936 ** of the string passed as argument zConstant. The returned buffer is
76937 ** allocated using sqlite3DbMalloc(). It is the responsibility of the
76938 ** caller to ensure that it is eventually freed.
76940 ** If argument zWhere is not NULL, then the string returned is
76941 ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
76942 ** In this case zWhere is passed to sqlite3DbFree() before returning.
76945 static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
76946 char *zNew;
76947 if( !zWhere ){
76948 zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
76949 }else{
76950 zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
76951 sqlite3DbFree(db, zWhere);
76953 return zNew;
76956 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
76958 ** Generate the text of a WHERE expression which can be used to select all
76959 ** tables that have foreign key constraints that refer to table pTab (i.e.
76960 ** constraints for which pTab is the parent table) from the sqlite_master
76961 ** table.
76963 static char *whereForeignKeys(Parse *pParse, Table *pTab){
76964 FKey *p;
76965 char *zWhere = 0;
76966 for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
76967 zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
76969 return zWhere;
76971 #endif
76974 ** Generate the text of a WHERE expression which can be used to select all
76975 ** temporary triggers on table pTab from the sqlite_temp_master table. If
76976 ** table pTab has no temporary triggers, or is itself stored in the
76977 ** temporary database, NULL is returned.
76979 static char *whereTempTriggers(Parse *pParse, Table *pTab){
76980 Trigger *pTrig;
76981 char *zWhere = 0;
76982 const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
76984 /* If the table is not located in the temp-db (in which case NULL is
76985 ** returned, loop through the tables list of triggers. For each trigger
76986 ** that is not part of the temp-db schema, add a clause to the WHERE
76987 ** expression being built up in zWhere.
76989 if( pTab->pSchema!=pTempSchema ){
76990 sqlite3 *db = pParse->db;
76991 for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
76992 if( pTrig->pSchema==pTempSchema ){
76993 zWhere = whereOrName(db, zWhere, pTrig->zName);
76997 if( zWhere ){
76998 char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
76999 sqlite3DbFree(pParse->db, zWhere);
77000 zWhere = zNew;
77002 return zWhere;
77006 ** Generate code to drop and reload the internal representation of table
77007 ** pTab from the database, including triggers and temporary triggers.
77008 ** Argument zName is the name of the table in the database schema at
77009 ** the time the generated code is executed. This can be different from
77010 ** pTab->zName if this function is being called to code part of an
77011 ** "ALTER TABLE RENAME TO" statement.
77013 static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
77014 Vdbe *v;
77015 char *zWhere;
77016 int iDb; /* Index of database containing pTab */
77017 #ifndef SQLITE_OMIT_TRIGGER
77018 Trigger *pTrig;
77019 #endif
77021 v = sqlite3GetVdbe(pParse);
77022 if( NEVER(v==0) ) return;
77023 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
77024 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
77025 assert( iDb>=0 );
77027 #ifndef SQLITE_OMIT_TRIGGER
77028 /* Drop any table triggers from the internal schema. */
77029 for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
77030 int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
77031 assert( iTrigDb==iDb || iTrigDb==1 );
77032 sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
77034 #endif
77036 /* Drop the table and index from the internal schema. */
77037 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
77039 /* Reload the table, index and permanent trigger schemas. */
77040 zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
77041 if( !zWhere ) return;
77042 sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
77044 #ifndef SQLITE_OMIT_TRIGGER
77045 /* Now, if the table is not stored in the temp database, reload any temp
77046 ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
77048 if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
77049 sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
77051 #endif
77055 ** Parameter zName is the name of a table that is about to be altered
77056 ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
77057 ** If the table is a system table, this function leaves an error message
77058 ** in pParse->zErr (system tables may not be altered) and returns non-zero.
77060 ** Or, if zName is not a system table, zero is returned.
77062 static int isSystemTable(Parse *pParse, const char *zName){
77063 if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
77064 sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
77065 return 1;
77067 return 0;
77071 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
77072 ** command.
77074 SQLITE_PRIVATE void sqlite3AlterRenameTable(
77075 Parse *pParse, /* Parser context. */
77076 SrcList *pSrc, /* The table to rename. */
77077 Token *pName /* The new table name. */
77079 int iDb; /* Database that contains the table */
77080 char *zDb; /* Name of database iDb */
77081 Table *pTab; /* Table being renamed */
77082 char *zName = 0; /* NULL-terminated version of pName */
77083 sqlite3 *db = pParse->db; /* Database connection */
77084 int nTabName; /* Number of UTF-8 characters in zTabName */
77085 const char *zTabName; /* Original name of the table */
77086 Vdbe *v;
77087 #ifndef SQLITE_OMIT_TRIGGER
77088 char *zWhere = 0; /* Where clause to locate temp triggers */
77089 #endif
77090 VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */
77091 int savedDbFlags; /* Saved value of db->flags */
77093 savedDbFlags = db->flags;
77094 if( NEVER(db->mallocFailed) ) goto exit_rename_table;
77095 assert( pSrc->nSrc==1 );
77096 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
77098 pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
77099 if( !pTab ) goto exit_rename_table;
77100 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
77101 zDb = db->aDb[iDb].zName;
77102 db->flags |= SQLITE_PreferBuiltin;
77104 /* Get a NULL terminated version of the new table name. */
77105 zName = sqlite3NameFromToken(db, pName);
77106 if( !zName ) goto exit_rename_table;
77108 /* Check that a table or index named 'zName' does not already exist
77109 ** in database iDb. If so, this is an error.
77111 if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
77112 sqlite3ErrorMsg(pParse,
77113 "there is already another table or index with this name: %s", zName);
77114 goto exit_rename_table;
77117 /* Make sure it is not a system table being altered, or a reserved name
77118 ** that the table is being renamed to.
77120 if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
77121 goto exit_rename_table;
77123 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
77124 exit_rename_table;
77127 #ifndef SQLITE_OMIT_VIEW
77128 if( pTab->pSelect ){
77129 sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
77130 goto exit_rename_table;
77132 #endif
77134 #ifndef SQLITE_OMIT_AUTHORIZATION
77135 /* Invoke the authorization callback. */
77136 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
77137 goto exit_rename_table;
77139 #endif
77141 #ifndef SQLITE_OMIT_VIRTUALTABLE
77142 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
77143 goto exit_rename_table;
77145 if( IsVirtual(pTab) ){
77146 pVTab = sqlite3GetVTable(db, pTab);
77147 if( pVTab->pVtab->pModule->xRename==0 ){
77148 pVTab = 0;
77151 #endif
77153 /* Begin a transaction and code the VerifyCookie for database iDb.
77154 ** Then modify the schema cookie (since the ALTER TABLE modifies the
77155 ** schema). Open a statement transaction if the table is a virtual
77156 ** table.
77158 v = sqlite3GetVdbe(pParse);
77159 if( v==0 ){
77160 goto exit_rename_table;
77162 sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
77163 sqlite3ChangeCookie(pParse, iDb);
77165 /* If this is a virtual table, invoke the xRename() function if
77166 ** one is defined. The xRename() callback will modify the names
77167 ** of any resources used by the v-table implementation (including other
77168 ** SQLite tables) that are identified by the name of the virtual table.
77170 #ifndef SQLITE_OMIT_VIRTUALTABLE
77171 if( pVTab ){
77172 int i = ++pParse->nMem;
77173 sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
77174 sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
77175 sqlite3MayAbort(pParse);
77177 #endif
77179 /* figure out how many UTF-8 characters are in zName */
77180 zTabName = pTab->zName;
77181 nTabName = sqlite3Utf8CharLen(zTabName, -1);
77183 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
77184 if( db->flags&SQLITE_ForeignKeys ){
77185 /* If foreign-key support is enabled, rewrite the CREATE TABLE
77186 ** statements corresponding to all child tables of foreign key constraints
77187 ** for which the renamed table is the parent table. */
77188 if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
77189 sqlite3NestedParse(pParse,
77190 "UPDATE \"%w\".%s SET "
77191 "sql = sqlite_rename_parent(sql, %Q, %Q) "
77192 "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
77193 sqlite3DbFree(db, zWhere);
77196 #endif
77198 /* Modify the sqlite_master table to use the new table name. */
77199 sqlite3NestedParse(pParse,
77200 "UPDATE %Q.%s SET "
77201 #ifdef SQLITE_OMIT_TRIGGER
77202 "sql = sqlite_rename_table(sql, %Q), "
77203 #else
77204 "sql = CASE "
77205 "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
77206 "ELSE sqlite_rename_table(sql, %Q) END, "
77207 #endif
77208 "tbl_name = %Q, "
77209 "name = CASE "
77210 "WHEN type='table' THEN %Q "
77211 "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
77212 "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
77213 "ELSE name END "
77214 "WHERE tbl_name=%Q AND "
77215 "(type='table' OR type='index' OR type='trigger');",
77216 zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
77217 #ifndef SQLITE_OMIT_TRIGGER
77218 zName,
77219 #endif
77220 zName, nTabName, zTabName
77223 #ifndef SQLITE_OMIT_AUTOINCREMENT
77224 /* If the sqlite_sequence table exists in this database, then update
77225 ** it with the new table name.
77227 if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
77228 sqlite3NestedParse(pParse,
77229 "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
77230 zDb, zName, pTab->zName);
77232 #endif
77234 #ifndef SQLITE_OMIT_TRIGGER
77235 /* If there are TEMP triggers on this table, modify the sqlite_temp_master
77236 ** table. Don't do this if the table being ALTERed is itself located in
77237 ** the temp database.
77239 if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
77240 sqlite3NestedParse(pParse,
77241 "UPDATE sqlite_temp_master SET "
77242 "sql = sqlite_rename_trigger(sql, %Q), "
77243 "tbl_name = %Q "
77244 "WHERE %s;", zName, zName, zWhere);
77245 sqlite3DbFree(db, zWhere);
77247 #endif
77249 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
77250 if( db->flags&SQLITE_ForeignKeys ){
77251 FKey *p;
77252 for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
77253 Table *pFrom = p->pFrom;
77254 if( pFrom!=pTab ){
77255 reloadTableSchema(pParse, p->pFrom, pFrom->zName);
77259 #endif
77261 /* Drop and reload the internal table schema. */
77262 reloadTableSchema(pParse, pTab, zName);
77264 exit_rename_table:
77265 sqlite3SrcListDelete(db, pSrc);
77266 sqlite3DbFree(db, zName);
77267 db->flags = savedDbFlags;
77272 ** Generate code to make sure the file format number is at least minFormat.
77273 ** The generated code will increase the file format number if necessary.
77275 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
77276 Vdbe *v;
77277 v = sqlite3GetVdbe(pParse);
77278 /* The VDBE should have been allocated before this routine is called.
77279 ** If that allocation failed, we would have quit before reaching this
77280 ** point */
77281 if( ALWAYS(v) ){
77282 int r1 = sqlite3GetTempReg(pParse);
77283 int r2 = sqlite3GetTempReg(pParse);
77284 int j1;
77285 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
77286 sqlite3VdbeUsesBtree(v, iDb);
77287 sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
77288 j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
77289 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
77290 sqlite3VdbeJumpHere(v, j1);
77291 sqlite3ReleaseTempReg(pParse, r1);
77292 sqlite3ReleaseTempReg(pParse, r2);
77297 ** This function is called after an "ALTER TABLE ... ADD" statement
77298 ** has been parsed. Argument pColDef contains the text of the new
77299 ** column definition.
77301 ** The Table structure pParse->pNewTable was extended to include
77302 ** the new column during parsing.
77304 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
77305 Table *pNew; /* Copy of pParse->pNewTable */
77306 Table *pTab; /* Table being altered */
77307 int iDb; /* Database number */
77308 const char *zDb; /* Database name */
77309 const char *zTab; /* Table name */
77310 char *zCol; /* Null-terminated column definition */
77311 Column *pCol; /* The new column */
77312 Expr *pDflt; /* Default value for the new column */
77313 sqlite3 *db; /* The database connection; */
77315 db = pParse->db;
77316 if( pParse->nErr || db->mallocFailed ) return;
77317 pNew = pParse->pNewTable;
77318 assert( pNew );
77320 assert( sqlite3BtreeHoldsAllMutexes(db) );
77321 iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
77322 zDb = db->aDb[iDb].zName;
77323 zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */
77324 pCol = &pNew->aCol[pNew->nCol-1];
77325 pDflt = pCol->pDflt;
77326 pTab = sqlite3FindTable(db, zTab, zDb);
77327 assert( pTab );
77329 #ifndef SQLITE_OMIT_AUTHORIZATION
77330 /* Invoke the authorization callback. */
77331 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
77332 return;
77334 #endif
77336 /* If the default value for the new column was specified with a
77337 ** literal NULL, then set pDflt to 0. This simplifies checking
77338 ** for an SQL NULL default below.
77340 if( pDflt && pDflt->op==TK_NULL ){
77341 pDflt = 0;
77344 /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
77345 ** If there is a NOT NULL constraint, then the default value for the
77346 ** column must not be NULL.
77348 if( pCol->isPrimKey ){
77349 sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
77350 return;
77352 if( pNew->pIndex ){
77353 sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
77354 return;
77356 if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
77357 sqlite3ErrorMsg(pParse,
77358 "Cannot add a REFERENCES column with non-NULL default value");
77359 return;
77361 if( pCol->notNull && !pDflt ){
77362 sqlite3ErrorMsg(pParse,
77363 "Cannot add a NOT NULL column with default value NULL");
77364 return;
77367 /* Ensure the default expression is something that sqlite3ValueFromExpr()
77368 ** can handle (i.e. not CURRENT_TIME etc.)
77370 if( pDflt ){
77371 sqlite3_value *pVal;
77372 if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
77373 db->mallocFailed = 1;
77374 return;
77376 if( !pVal ){
77377 sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
77378 return;
77380 sqlite3ValueFree(pVal);
77383 /* Modify the CREATE TABLE statement. */
77384 zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
77385 if( zCol ){
77386 char *zEnd = &zCol[pColDef->n-1];
77387 int savedDbFlags = db->flags;
77388 while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
77389 *zEnd-- = '\0';
77391 db->flags |= SQLITE_PreferBuiltin;
77392 sqlite3NestedParse(pParse,
77393 "UPDATE \"%w\".%s SET "
77394 "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
77395 "WHERE type = 'table' AND name = %Q",
77396 zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
77397 zTab
77399 sqlite3DbFree(db, zCol);
77400 db->flags = savedDbFlags;
77403 /* If the default value of the new column is NULL, then set the file
77404 ** format to 2. If the default value of the new column is not NULL,
77405 ** the file format becomes 3.
77407 sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
77409 /* Reload the schema of the modified table. */
77410 reloadTableSchema(pParse, pTab, pTab->zName);
77414 ** This function is called by the parser after the table-name in
77415 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
77416 ** pSrc is the full-name of the table being altered.
77418 ** This routine makes a (partial) copy of the Table structure
77419 ** for the table being altered and sets Parse.pNewTable to point
77420 ** to it. Routines called by the parser as the column definition
77421 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
77422 ** the copy. The copy of the Table structure is deleted by tokenize.c
77423 ** after parsing is finished.
77425 ** Routine sqlite3AlterFinishAddColumn() will be called to complete
77426 ** coding the "ALTER TABLE ... ADD" statement.
77428 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
77429 Table *pNew;
77430 Table *pTab;
77431 Vdbe *v;
77432 int iDb;
77433 int i;
77434 int nAlloc;
77435 sqlite3 *db = pParse->db;
77437 /* Look up the table being altered. */
77438 assert( pParse->pNewTable==0 );
77439 assert( sqlite3BtreeHoldsAllMutexes(db) );
77440 if( db->mallocFailed ) goto exit_begin_add_column;
77441 pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
77442 if( !pTab ) goto exit_begin_add_column;
77444 #ifndef SQLITE_OMIT_VIRTUALTABLE
77445 if( IsVirtual(pTab) ){
77446 sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
77447 goto exit_begin_add_column;
77449 #endif
77451 /* Make sure this is not an attempt to ALTER a view. */
77452 if( pTab->pSelect ){
77453 sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
77454 goto exit_begin_add_column;
77456 if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
77457 goto exit_begin_add_column;
77460 assert( pTab->addColOffset>0 );
77461 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
77463 /* Put a copy of the Table struct in Parse.pNewTable for the
77464 ** sqlite3AddColumn() function and friends to modify. But modify
77465 ** the name by adding an "sqlite_altertab_" prefix. By adding this
77466 ** prefix, we insure that the name will not collide with an existing
77467 ** table because user table are not allowed to have the "sqlite_"
77468 ** prefix on their name.
77470 pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
77471 if( !pNew ) goto exit_begin_add_column;
77472 pParse->pNewTable = pNew;
77473 pNew->nRef = 1;
77474 pNew->nCol = pTab->nCol;
77475 assert( pNew->nCol>0 );
77476 nAlloc = (((pNew->nCol-1)/8)*8)+8;
77477 assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
77478 pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
77479 pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
77480 if( !pNew->aCol || !pNew->zName ){
77481 db->mallocFailed = 1;
77482 goto exit_begin_add_column;
77484 memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
77485 for(i=0; i<pNew->nCol; i++){
77486 Column *pCol = &pNew->aCol[i];
77487 pCol->zName = sqlite3DbStrDup(db, pCol->zName);
77488 pCol->zColl = 0;
77489 pCol->zType = 0;
77490 pCol->pDflt = 0;
77491 pCol->zDflt = 0;
77493 pNew->pSchema = db->aDb[iDb].pSchema;
77494 pNew->addColOffset = pTab->addColOffset;
77495 pNew->nRef = 1;
77497 /* Begin a transaction and increment the schema cookie. */
77498 sqlite3BeginWriteOperation(pParse, 0, iDb);
77499 v = sqlite3GetVdbe(pParse);
77500 if( !v ) goto exit_begin_add_column;
77501 sqlite3ChangeCookie(pParse, iDb);
77503 exit_begin_add_column:
77504 sqlite3SrcListDelete(db, pSrc);
77505 return;
77507 #endif /* SQLITE_ALTER_TABLE */
77509 /************** End of alter.c ***********************************************/
77510 /************** Begin file analyze.c *****************************************/
77512 ** 2005 July 8
77514 ** The author disclaims copyright to this source code. In place of
77515 ** a legal notice, here is a blessing:
77517 ** May you do good and not evil.
77518 ** May you find forgiveness for yourself and forgive others.
77519 ** May you share freely, never taking more than you give.
77521 *************************************************************************
77522 ** This file contains code associated with the ANALYZE command.
77524 ** The ANALYZE command gather statistics about the content of tables
77525 ** and indices. These statistics are made available to the query planner
77526 ** to help it make better decisions about how to perform queries.
77528 ** The following system tables are or have been supported:
77530 ** CREATE TABLE sqlite_stat1(tbl, idx, stat);
77531 ** CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
77532 ** CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
77534 ** Additional tables might be added in future releases of SQLite.
77535 ** The sqlite_stat2 table is not created or used unless the SQLite version
77536 ** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
77537 ** with SQLITE_ENABLE_STAT2. The sqlite_stat2 table is deprecated.
77538 ** The sqlite_stat2 table is superceded by sqlite_stat3, which is only
77539 ** created and used by SQLite versions 3.7.9 and later and with
77540 ** SQLITE_ENABLE_STAT3 defined. The fucntionality of sqlite_stat3
77541 ** is a superset of sqlite_stat2.
77543 ** Format of sqlite_stat1:
77545 ** There is normally one row per index, with the index identified by the
77546 ** name in the idx column. The tbl column is the name of the table to
77547 ** which the index belongs. In each such row, the stat column will be
77548 ** a string consisting of a list of integers. The first integer in this
77549 ** list is the number of rows in the index and in the table. The second
77550 ** integer is the average number of rows in the index that have the same
77551 ** value in the first column of the index. The third integer is the average
77552 ** number of rows in the index that have the same value for the first two
77553 ** columns. The N-th integer (for N>1) is the average number of rows in
77554 ** the index which have the same value for the first N-1 columns. For
77555 ** a K-column index, there will be K+1 integers in the stat column. If
77556 ** the index is unique, then the last integer will be 1.
77558 ** The list of integers in the stat column can optionally be followed
77559 ** by the keyword "unordered". The "unordered" keyword, if it is present,
77560 ** must be separated from the last integer by a single space. If the
77561 ** "unordered" keyword is present, then the query planner assumes that
77562 ** the index is unordered and will not use the index for a range query.
77564 ** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
77565 ** column contains a single integer which is the (estimated) number of
77566 ** rows in the table identified by sqlite_stat1.tbl.
77568 ** Format of sqlite_stat2:
77570 ** The sqlite_stat2 is only created and is only used if SQLite is compiled
77571 ** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
77572 ** 3.6.18 and 3.7.8. The "stat2" table contains additional information
77573 ** about the distribution of keys within an index. The index is identified by
77574 ** the "idx" column and the "tbl" column is the name of the table to which
77575 ** the index belongs. There are usually 10 rows in the sqlite_stat2
77576 ** table for each index.
77578 ** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
77579 ** inclusive are samples of the left-most key value in the index taken at
77580 ** evenly spaced points along the index. Let the number of samples be S
77581 ** (10 in the standard build) and let C be the number of rows in the index.
77582 ** Then the sampled rows are given by:
77584 ** rownumber = (i*C*2 + C)/(S*2)
77586 ** For i between 0 and S-1. Conceptually, the index space is divided into
77587 ** S uniform buckets and the samples are the middle row from each bucket.
77589 ** The format for sqlite_stat2 is recorded here for legacy reference. This
77590 ** version of SQLite does not support sqlite_stat2. It neither reads nor
77591 ** writes the sqlite_stat2 table. This version of SQLite only supports
77592 ** sqlite_stat3.
77594 ** Format for sqlite_stat3:
77596 ** The sqlite_stat3 is an enhancement to sqlite_stat2. A new name is
77597 ** used to avoid compatibility problems.
77599 ** The format of the sqlite_stat3 table is similar to the format of
77600 ** the sqlite_stat2 table. There are multiple entries for each index.
77601 ** The idx column names the index and the tbl column is the table of the
77602 ** index. If the idx and tbl columns are the same, then the sample is
77603 ** of the INTEGER PRIMARY KEY. The sample column is a value taken from
77604 ** the left-most column of the index. The nEq column is the approximate
77605 ** number of entires in the index whose left-most column exactly matches
77606 ** the sample. nLt is the approximate number of entires whose left-most
77607 ** column is less than the sample. The nDLt column is the approximate
77608 ** number of distinct left-most entries in the index that are less than
77609 ** the sample.
77611 ** Future versions of SQLite might change to store a string containing
77612 ** multiple integers values in the nDLt column of sqlite_stat3. The first
77613 ** integer will be the number of prior index entires that are distinct in
77614 ** the left-most column. The second integer will be the number of prior index
77615 ** entries that are distinct in the first two columns. The third integer
77616 ** will be the number of prior index entries that are distinct in the first
77617 ** three columns. And so forth. With that extension, the nDLt field is
77618 ** similar in function to the sqlite_stat1.stat field.
77620 ** There can be an arbitrary number of sqlite_stat3 entries per index.
77621 ** The ANALYZE command will typically generate sqlite_stat3 tables
77622 ** that contain between 10 and 40 samples which are distributed across
77623 ** the key space, though not uniformly, and which include samples with
77624 ** largest possible nEq values.
77626 #ifndef SQLITE_OMIT_ANALYZE
77629 ** This routine generates code that opens the sqlite_stat1 table for
77630 ** writing with cursor iStatCur. If the library was built with the
77631 ** SQLITE_ENABLE_STAT3 macro defined, then the sqlite_stat3 table is
77632 ** opened for writing using cursor (iStatCur+1)
77634 ** If the sqlite_stat1 tables does not previously exist, it is created.
77635 ** Similarly, if the sqlite_stat3 table does not exist and the library
77636 ** is compiled with SQLITE_ENABLE_STAT3 defined, it is created.
77638 ** Argument zWhere may be a pointer to a buffer containing a table name,
77639 ** or it may be a NULL pointer. If it is not NULL, then all entries in
77640 ** the sqlite_stat1 and (if applicable) sqlite_stat3 tables associated
77641 ** with the named table are deleted. If zWhere==0, then code is generated
77642 ** to delete all stat table entries.
77644 static void openStatTable(
77645 Parse *pParse, /* Parsing context */
77646 int iDb, /* The database we are looking in */
77647 int iStatCur, /* Open the sqlite_stat1 table on this cursor */
77648 const char *zWhere, /* Delete entries for this table or index */
77649 const char *zWhereType /* Either "tbl" or "idx" */
77651 static const struct {
77652 const char *zName;
77653 const char *zCols;
77654 } aTable[] = {
77655 { "sqlite_stat1", "tbl,idx,stat" },
77656 #ifdef SQLITE_ENABLE_STAT3
77657 { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
77658 #endif
77661 int aRoot[] = {0, 0};
77662 u8 aCreateTbl[] = {0, 0};
77664 int i;
77665 sqlite3 *db = pParse->db;
77666 Db *pDb;
77667 Vdbe *v = sqlite3GetVdbe(pParse);
77668 if( v==0 ) return;
77669 assert( sqlite3BtreeHoldsAllMutexes(db) );
77670 assert( sqlite3VdbeDb(v)==db );
77671 pDb = &db->aDb[iDb];
77673 /* Create new statistic tables if they do not exist, or clear them
77674 ** if they do already exist.
77676 for(i=0; i<ArraySize(aTable); i++){
77677 const char *zTab = aTable[i].zName;
77678 Table *pStat;
77679 if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
77680 /* The sqlite_stat[12] table does not exist. Create it. Note that a
77681 ** side-effect of the CREATE TABLE statement is to leave the rootpage
77682 ** of the new table in register pParse->regRoot. This is important
77683 ** because the OpenWrite opcode below will be needing it. */
77684 sqlite3NestedParse(pParse,
77685 "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
77687 aRoot[i] = pParse->regRoot;
77688 aCreateTbl[i] = 1;
77689 }else{
77690 /* The table already exists. If zWhere is not NULL, delete all entries
77691 ** associated with the table zWhere. If zWhere is NULL, delete the
77692 ** entire contents of the table. */
77693 aRoot[i] = pStat->tnum;
77694 sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
77695 if( zWhere ){
77696 sqlite3NestedParse(pParse,
77697 "DELETE FROM %Q.%s WHERE %s=%Q", pDb->zName, zTab, zWhereType, zWhere
77699 }else{
77700 /* The sqlite_stat[12] table already exists. Delete all rows. */
77701 sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
77706 /* Open the sqlite_stat[13] tables for writing. */
77707 for(i=0; i<ArraySize(aTable); i++){
77708 sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb);
77709 sqlite3VdbeChangeP4(v, -1, (char *)3, P4_INT32);
77710 sqlite3VdbeChangeP5(v, aCreateTbl[i]);
77715 ** Recommended number of samples for sqlite_stat3
77717 #ifndef SQLITE_STAT3_SAMPLES
77718 # define SQLITE_STAT3_SAMPLES 24
77719 #endif
77722 ** Three SQL functions - stat3_init(), stat3_push(), and stat3_pop() -
77723 ** share an instance of the following structure to hold their state
77724 ** information.
77726 typedef struct Stat3Accum Stat3Accum;
77727 struct Stat3Accum {
77728 tRowcnt nRow; /* Number of rows in the entire table */
77729 tRowcnt nPSample; /* How often to do a periodic sample */
77730 int iMin; /* Index of entry with minimum nEq and hash */
77731 int mxSample; /* Maximum number of samples to accumulate */
77732 int nSample; /* Current number of samples */
77733 u32 iPrn; /* Pseudo-random number used for sampling */
77734 struct Stat3Sample {
77735 i64 iRowid; /* Rowid in main table of the key */
77736 tRowcnt nEq; /* sqlite_stat3.nEq */
77737 tRowcnt nLt; /* sqlite_stat3.nLt */
77738 tRowcnt nDLt; /* sqlite_stat3.nDLt */
77739 u8 isPSample; /* True if a periodic sample */
77740 u32 iHash; /* Tiebreaker hash */
77741 } *a; /* An array of samples */
77744 #ifdef SQLITE_ENABLE_STAT3
77746 ** Implementation of the stat3_init(C,S) SQL function. The two parameters
77747 ** are the number of rows in the table or index (C) and the number of samples
77748 ** to accumulate (S).
77750 ** This routine allocates the Stat3Accum object.
77752 ** The return value is the Stat3Accum object (P).
77754 static void stat3Init(
77755 sqlite3_context *context,
77756 int argc,
77757 sqlite3_value **argv
77759 Stat3Accum *p;
77760 tRowcnt nRow;
77761 int mxSample;
77762 int n;
77764 UNUSED_PARAMETER(argc);
77765 nRow = (tRowcnt)sqlite3_value_int64(argv[0]);
77766 mxSample = sqlite3_value_int(argv[1]);
77767 n = sizeof(*p) + sizeof(p->a[0])*mxSample;
77768 p = sqlite3_malloc( n );
77769 if( p==0 ){
77770 sqlite3_result_error_nomem(context);
77771 return;
77773 memset(p, 0, n);
77774 p->a = (struct Stat3Sample*)&p[1];
77775 p->nRow = nRow;
77776 p->mxSample = mxSample;
77777 p->nPSample = p->nRow/(mxSample/3+1) + 1;
77778 sqlite3_randomness(sizeof(p->iPrn), &p->iPrn);
77779 sqlite3_result_blob(context, p, sizeof(p), sqlite3_free);
77781 static const FuncDef stat3InitFuncdef = {
77782 2, /* nArg */
77783 SQLITE_UTF8, /* iPrefEnc */
77784 0, /* flags */
77785 0, /* pUserData */
77786 0, /* pNext */
77787 stat3Init, /* xFunc */
77788 0, /* xStep */
77789 0, /* xFinalize */
77790 "stat3_init", /* zName */
77791 0, /* pHash */
77792 0 /* pDestructor */
77797 ** Implementation of the stat3_push(nEq,nLt,nDLt,rowid,P) SQL function. The
77798 ** arguments describe a single key instance. This routine makes the
77799 ** decision about whether or not to retain this key for the sqlite_stat3
77800 ** table.
77802 ** The return value is NULL.
77804 static void stat3Push(
77805 sqlite3_context *context,
77806 int argc,
77807 sqlite3_value **argv
77809 Stat3Accum *p = (Stat3Accum*)sqlite3_value_blob(argv[4]);
77810 tRowcnt nEq = sqlite3_value_int64(argv[0]);
77811 tRowcnt nLt = sqlite3_value_int64(argv[1]);
77812 tRowcnt nDLt = sqlite3_value_int64(argv[2]);
77813 i64 rowid = sqlite3_value_int64(argv[3]);
77814 u8 isPSample = 0;
77815 u8 doInsert = 0;
77816 int iMin = p->iMin;
77817 struct Stat3Sample *pSample;
77818 int i;
77819 u32 h;
77821 UNUSED_PARAMETER(context);
77822 UNUSED_PARAMETER(argc);
77823 if( nEq==0 ) return;
77824 h = p->iPrn = p->iPrn*1103515245 + 12345;
77825 if( (nLt/p->nPSample)!=((nEq+nLt)/p->nPSample) ){
77826 doInsert = isPSample = 1;
77827 }else if( p->nSample<p->mxSample ){
77828 doInsert = 1;
77829 }else{
77830 if( nEq>p->a[iMin].nEq || (nEq==p->a[iMin].nEq && h>p->a[iMin].iHash) ){
77831 doInsert = 1;
77834 if( !doInsert ) return;
77835 if( p->nSample==p->mxSample ){
77836 assert( p->nSample - iMin - 1 >= 0 );
77837 memmove(&p->a[iMin], &p->a[iMin+1], sizeof(p->a[0])*(p->nSample-iMin-1));
77838 pSample = &p->a[p->nSample-1];
77839 }else{
77840 pSample = &p->a[p->nSample++];
77842 pSample->iRowid = rowid;
77843 pSample->nEq = nEq;
77844 pSample->nLt = nLt;
77845 pSample->nDLt = nDLt;
77846 pSample->iHash = h;
77847 pSample->isPSample = isPSample;
77849 /* Find the new minimum */
77850 if( p->nSample==p->mxSample ){
77851 pSample = p->a;
77852 i = 0;
77853 while( pSample->isPSample ){
77854 i++;
77855 pSample++;
77856 assert( i<p->nSample );
77858 nEq = pSample->nEq;
77859 h = pSample->iHash;
77860 iMin = i;
77861 for(i++, pSample++; i<p->nSample; i++, pSample++){
77862 if( pSample->isPSample ) continue;
77863 if( pSample->nEq<nEq
77864 || (pSample->nEq==nEq && pSample->iHash<h)
77866 iMin = i;
77867 nEq = pSample->nEq;
77868 h = pSample->iHash;
77871 p->iMin = iMin;
77874 static const FuncDef stat3PushFuncdef = {
77875 5, /* nArg */
77876 SQLITE_UTF8, /* iPrefEnc */
77877 0, /* flags */
77878 0, /* pUserData */
77879 0, /* pNext */
77880 stat3Push, /* xFunc */
77881 0, /* xStep */
77882 0, /* xFinalize */
77883 "stat3_push", /* zName */
77884 0, /* pHash */
77885 0 /* pDestructor */
77889 ** Implementation of the stat3_get(P,N,...) SQL function. This routine is
77890 ** used to query the results. Content is returned for the Nth sqlite_stat3
77891 ** row where N is between 0 and S-1 and S is the number of samples. The
77892 ** value returned depends on the number of arguments.
77894 ** argc==2 result: rowid
77895 ** argc==3 result: nEq
77896 ** argc==4 result: nLt
77897 ** argc==5 result: nDLt
77899 static void stat3Get(
77900 sqlite3_context *context,
77901 int argc,
77902 sqlite3_value **argv
77904 int n = sqlite3_value_int(argv[1]);
77905 Stat3Accum *p = (Stat3Accum*)sqlite3_value_blob(argv[0]);
77907 assert( p!=0 );
77908 if( p->nSample<=n ) return;
77909 switch( argc ){
77910 case 2: sqlite3_result_int64(context, p->a[n].iRowid); break;
77911 case 3: sqlite3_result_int64(context, p->a[n].nEq); break;
77912 case 4: sqlite3_result_int64(context, p->a[n].nLt); break;
77913 default: sqlite3_result_int64(context, p->a[n].nDLt); break;
77916 static const FuncDef stat3GetFuncdef = {
77917 -1, /* nArg */
77918 SQLITE_UTF8, /* iPrefEnc */
77919 0, /* flags */
77920 0, /* pUserData */
77921 0, /* pNext */
77922 stat3Get, /* xFunc */
77923 0, /* xStep */
77924 0, /* xFinalize */
77925 "stat3_get", /* zName */
77926 0, /* pHash */
77927 0 /* pDestructor */
77929 #endif /* SQLITE_ENABLE_STAT3 */
77935 ** Generate code to do an analysis of all indices associated with
77936 ** a single table.
77938 static void analyzeOneTable(
77939 Parse *pParse, /* Parser context */
77940 Table *pTab, /* Table whose indices are to be analyzed */
77941 Index *pOnlyIdx, /* If not NULL, only analyze this one index */
77942 int iStatCur, /* Index of VdbeCursor that writes the sqlite_stat1 table */
77943 int iMem /* Available memory locations begin here */
77945 sqlite3 *db = pParse->db; /* Database handle */
77946 Index *pIdx; /* An index to being analyzed */
77947 int iIdxCur; /* Cursor open on index being analyzed */
77948 Vdbe *v; /* The virtual machine being built up */
77949 int i; /* Loop counter */
77950 int topOfLoop; /* The top of the loop */
77951 int endOfLoop; /* The end of the loop */
77952 int jZeroRows = -1; /* Jump from here if number of rows is zero */
77953 int iDb; /* Index of database containing pTab */
77954 int regTabname = iMem++; /* Register containing table name */
77955 int regIdxname = iMem++; /* Register containing index name */
77956 int regStat1 = iMem++; /* The stat column of sqlite_stat1 */
77957 #ifdef SQLITE_ENABLE_STAT3
77958 int regNumEq = regStat1; /* Number of instances. Same as regStat1 */
77959 int regNumLt = iMem++; /* Number of keys less than regSample */
77960 int regNumDLt = iMem++; /* Number of distinct keys less than regSample */
77961 int regSample = iMem++; /* The next sample value */
77962 int regRowid = regSample; /* Rowid of a sample */
77963 int regAccum = iMem++; /* Register to hold Stat3Accum object */
77964 int regLoop = iMem++; /* Loop counter */
77965 int regCount = iMem++; /* Number of rows in the table or index */
77966 int regTemp1 = iMem++; /* Intermediate register */
77967 int regTemp2 = iMem++; /* Intermediate register */
77968 int once = 1; /* One-time initialization */
77969 int shortJump = 0; /* Instruction address */
77970 int iTabCur = pParse->nTab++; /* Table cursor */
77971 #endif
77972 int regCol = iMem++; /* Content of a column in analyzed table */
77973 int regRec = iMem++; /* Register holding completed record */
77974 int regTemp = iMem++; /* Temporary use register */
77975 int regNewRowid = iMem++; /* Rowid for the inserted record */
77978 v = sqlite3GetVdbe(pParse);
77979 if( v==0 || NEVER(pTab==0) ){
77980 return;
77982 if( pTab->tnum==0 ){
77983 /* Do not gather statistics on views or virtual tables */
77984 return;
77986 if( memcmp(pTab->zName, "sqlite_", 7)==0 ){
77987 /* Do not gather statistics on system tables */
77988 return;
77990 assert( sqlite3BtreeHoldsAllMutexes(db) );
77991 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
77992 assert( iDb>=0 );
77993 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
77994 #ifndef SQLITE_OMIT_AUTHORIZATION
77995 if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
77996 db->aDb[iDb].zName ) ){
77997 return;
77999 #endif
78001 /* Establish a read-lock on the table at the shared-cache level. */
78002 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
78004 iIdxCur = pParse->nTab++;
78005 sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
78006 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
78007 int nCol;
78008 KeyInfo *pKey;
78009 int addrIfNot = 0; /* address of OP_IfNot */
78010 int *aChngAddr; /* Array of jump instruction addresses */
78012 if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
78013 VdbeNoopComment((v, "Begin analysis of %s", pIdx->zName));
78014 nCol = pIdx->nColumn;
78015 aChngAddr = sqlite3DbMallocRaw(db, sizeof(int)*nCol);
78016 if( aChngAddr==0 ) continue;
78017 pKey = sqlite3IndexKeyinfo(pParse, pIdx);
78018 if( iMem+1+(nCol*2)>pParse->nMem ){
78019 pParse->nMem = iMem+1+(nCol*2);
78022 /* Open a cursor to the index to be analyzed. */
78023 assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
78024 sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb,
78025 (char *)pKey, P4_KEYINFO_HANDOFF);
78026 VdbeComment((v, "%s", pIdx->zName));
78028 /* Populate the register containing the index name. */
78029 sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, pIdx->zName, 0);
78031 #ifdef SQLITE_ENABLE_STAT3
78032 if( once ){
78033 once = 0;
78034 sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
78036 sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regCount);
78037 sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_STAT3_SAMPLES, regTemp1);
78038 sqlite3VdbeAddOp2(v, OP_Integer, 0, regNumEq);
78039 sqlite3VdbeAddOp2(v, OP_Integer, 0, regNumLt);
78040 sqlite3VdbeAddOp2(v, OP_Integer, -1, regNumDLt);
78041 sqlite3VdbeAddOp4(v, OP_Function, 1, regCount, regAccum,
78042 (char*)&stat3InitFuncdef, P4_FUNCDEF);
78043 sqlite3VdbeChangeP5(v, 2);
78044 #endif /* SQLITE_ENABLE_STAT3 */
78046 /* The block of memory cells initialized here is used as follows.
78048 ** iMem:
78049 ** The total number of rows in the table.
78051 ** iMem+1 .. iMem+nCol:
78052 ** Number of distinct entries in index considering the
78053 ** left-most N columns only, where N is between 1 and nCol,
78054 ** inclusive.
78056 ** iMem+nCol+1 .. Mem+2*nCol:
78057 ** Previous value of indexed columns, from left to right.
78059 ** Cells iMem through iMem+nCol are initialized to 0. The others are
78060 ** initialized to contain an SQL NULL.
78062 for(i=0; i<=nCol; i++){
78063 sqlite3VdbeAddOp2(v, OP_Integer, 0, iMem+i);
78065 for(i=0; i<nCol; i++){
78066 sqlite3VdbeAddOp2(v, OP_Null, 0, iMem+nCol+i+1);
78069 /* Start the analysis loop. This loop runs through all the entries in
78070 ** the index b-tree. */
78071 endOfLoop = sqlite3VdbeMakeLabel(v);
78072 sqlite3VdbeAddOp2(v, OP_Rewind, iIdxCur, endOfLoop);
78073 topOfLoop = sqlite3VdbeCurrentAddr(v);
78074 sqlite3VdbeAddOp2(v, OP_AddImm, iMem, 1); /* Increment row counter */
78076 for(i=0; i<nCol; i++){
78077 CollSeq *pColl;
78078 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regCol);
78079 if( i==0 ){
78080 /* Always record the very first row */
78081 addrIfNot = sqlite3VdbeAddOp1(v, OP_IfNot, iMem+1);
78083 assert( pIdx->azColl!=0 );
78084 assert( pIdx->azColl[i]!=0 );
78085 pColl = sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
78086 aChngAddr[i] = sqlite3VdbeAddOp4(v, OP_Ne, regCol, 0, iMem+nCol+i+1,
78087 (char*)pColl, P4_COLLSEQ);
78088 sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
78089 VdbeComment((v, "jump if column %d changed", i));
78090 #ifdef SQLITE_ENABLE_STAT3
78091 if( i==0 ){
78092 sqlite3VdbeAddOp2(v, OP_AddImm, regNumEq, 1);
78093 VdbeComment((v, "incr repeat count"));
78095 #endif
78097 sqlite3VdbeAddOp2(v, OP_Goto, 0, endOfLoop);
78098 for(i=0; i<nCol; i++){
78099 sqlite3VdbeJumpHere(v, aChngAddr[i]); /* Set jump dest for the OP_Ne */
78100 if( i==0 ){
78101 sqlite3VdbeJumpHere(v, addrIfNot); /* Jump dest for OP_IfNot */
78102 #ifdef SQLITE_ENABLE_STAT3
78103 sqlite3VdbeAddOp4(v, OP_Function, 1, regNumEq, regTemp2,
78104 (char*)&stat3PushFuncdef, P4_FUNCDEF);
78105 sqlite3VdbeChangeP5(v, 5);
78106 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, pIdx->nColumn, regRowid);
78107 sqlite3VdbeAddOp3(v, OP_Add, regNumEq, regNumLt, regNumLt);
78108 sqlite3VdbeAddOp2(v, OP_AddImm, regNumDLt, 1);
78109 sqlite3VdbeAddOp2(v, OP_Integer, 1, regNumEq);
78110 #endif
78112 sqlite3VdbeAddOp2(v, OP_AddImm, iMem+i+1, 1);
78113 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, iMem+nCol+i+1);
78115 sqlite3DbFree(db, aChngAddr);
78117 /* Always jump here after updating the iMem+1...iMem+1+nCol counters */
78118 sqlite3VdbeResolveLabel(v, endOfLoop);
78120 sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, topOfLoop);
78121 sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
78122 #ifdef SQLITE_ENABLE_STAT3
78123 sqlite3VdbeAddOp4(v, OP_Function, 1, regNumEq, regTemp2,
78124 (char*)&stat3PushFuncdef, P4_FUNCDEF);
78125 sqlite3VdbeChangeP5(v, 5);
78126 sqlite3VdbeAddOp2(v, OP_Integer, -1, regLoop);
78127 shortJump =
78128 sqlite3VdbeAddOp2(v, OP_AddImm, regLoop, 1);
78129 sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regTemp1,
78130 (char*)&stat3GetFuncdef, P4_FUNCDEF);
78131 sqlite3VdbeChangeP5(v, 2);
78132 sqlite3VdbeAddOp1(v, OP_IsNull, regTemp1);
78133 sqlite3VdbeAddOp3(v, OP_NotExists, iTabCur, shortJump, regTemp1);
78134 sqlite3VdbeAddOp3(v, OP_Column, iTabCur, pIdx->aiColumn[0], regSample);
78135 sqlite3ColumnDefault(v, pTab, pIdx->aiColumn[0], regSample);
78136 sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regNumEq,
78137 (char*)&stat3GetFuncdef, P4_FUNCDEF);
78138 sqlite3VdbeChangeP5(v, 3);
78139 sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regNumLt,
78140 (char*)&stat3GetFuncdef, P4_FUNCDEF);
78141 sqlite3VdbeChangeP5(v, 4);
78142 sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regNumDLt,
78143 (char*)&stat3GetFuncdef, P4_FUNCDEF);
78144 sqlite3VdbeChangeP5(v, 5);
78145 sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 6, regRec, "bbbbbb", 0);
78146 sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
78147 sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regRec, regNewRowid);
78148 sqlite3VdbeAddOp2(v, OP_Goto, 0, shortJump);
78149 sqlite3VdbeJumpHere(v, shortJump+2);
78150 #endif
78152 /* Store the results in sqlite_stat1.
78154 ** The result is a single row of the sqlite_stat1 table. The first
78155 ** two columns are the names of the table and index. The third column
78156 ** is a string composed of a list of integer statistics about the
78157 ** index. The first integer in the list is the total number of entries
78158 ** in the index. There is one additional integer in the list for each
78159 ** column of the table. This additional integer is a guess of how many
78160 ** rows of the table the index will select. If D is the count of distinct
78161 ** values and K is the total number of rows, then the integer is computed
78162 ** as:
78164 ** I = (K+D-1)/D
78166 ** If K==0 then no entry is made into the sqlite_stat1 table.
78167 ** If K>0 then it is always the case the D>0 so division by zero
78168 ** is never possible.
78170 sqlite3VdbeAddOp2(v, OP_SCopy, iMem, regStat1);
78171 if( jZeroRows<0 ){
78172 jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);
78174 for(i=0; i<nCol; i++){
78175 sqlite3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, " ", 0);
78176 sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regStat1, regStat1);
78177 sqlite3VdbeAddOp3(v, OP_Add, iMem, iMem+i+1, regTemp);
78178 sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
78179 sqlite3VdbeAddOp3(v, OP_Divide, iMem+i+1, regTemp, regTemp);
78180 sqlite3VdbeAddOp1(v, OP_ToInt, regTemp);
78181 sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regStat1, regStat1);
78183 sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
78184 sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
78185 sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regNewRowid);
78186 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
78189 /* If the table has no indices, create a single sqlite_stat1 entry
78190 ** containing NULL as the index name and the row count as the content.
78192 if( pTab->pIndex==0 ){
78193 sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pTab->tnum, iDb);
78194 VdbeComment((v, "%s", pTab->zName));
78195 sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat1);
78196 sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
78197 jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1);
78198 }else{
78199 sqlite3VdbeJumpHere(v, jZeroRows);
78200 jZeroRows = sqlite3VdbeAddOp0(v, OP_Goto);
78202 sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
78203 sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
78204 sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
78205 sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regNewRowid);
78206 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
78207 if( pParse->nMem<regRec ) pParse->nMem = regRec;
78208 sqlite3VdbeJumpHere(v, jZeroRows);
78213 ** Generate code that will cause the most recent index analysis to
78214 ** be loaded into internal hash tables where is can be used.
78216 static void loadAnalysis(Parse *pParse, int iDb){
78217 Vdbe *v = sqlite3GetVdbe(pParse);
78218 if( v ){
78219 sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
78224 ** Generate code that will do an analysis of an entire database
78226 static void analyzeDatabase(Parse *pParse, int iDb){
78227 sqlite3 *db = pParse->db;
78228 Schema *pSchema = db->aDb[iDb].pSchema; /* Schema of database iDb */
78229 HashElem *k;
78230 int iStatCur;
78231 int iMem;
78233 sqlite3BeginWriteOperation(pParse, 0, iDb);
78234 iStatCur = pParse->nTab;
78235 pParse->nTab += 3;
78236 openStatTable(pParse, iDb, iStatCur, 0, 0);
78237 iMem = pParse->nMem+1;
78238 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
78239 for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
78240 Table *pTab = (Table*)sqliteHashData(k);
78241 analyzeOneTable(pParse, pTab, 0, iStatCur, iMem);
78243 loadAnalysis(pParse, iDb);
78247 ** Generate code that will do an analysis of a single table in
78248 ** a database. If pOnlyIdx is not NULL then it is a single index
78249 ** in pTab that should be analyzed.
78251 static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
78252 int iDb;
78253 int iStatCur;
78255 assert( pTab!=0 );
78256 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
78257 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
78258 sqlite3BeginWriteOperation(pParse, 0, iDb);
78259 iStatCur = pParse->nTab;
78260 pParse->nTab += 3;
78261 if( pOnlyIdx ){
78262 openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
78263 }else{
78264 openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
78266 analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur, pParse->nMem+1);
78267 loadAnalysis(pParse, iDb);
78271 ** Generate code for the ANALYZE command. The parser calls this routine
78272 ** when it recognizes an ANALYZE command.
78274 ** ANALYZE -- 1
78275 ** ANALYZE <database> -- 2
78276 ** ANALYZE ?<database>.?<tablename> -- 3
78278 ** Form 1 causes all indices in all attached databases to be analyzed.
78279 ** Form 2 analyzes all indices the single database named.
78280 ** Form 3 analyzes all indices associated with the named table.
78282 SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
78283 sqlite3 *db = pParse->db;
78284 int iDb;
78285 int i;
78286 char *z, *zDb;
78287 Table *pTab;
78288 Index *pIdx;
78289 Token *pTableName;
78291 /* Read the database schema. If an error occurs, leave an error message
78292 ** and code in pParse and return NULL. */
78293 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
78294 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
78295 return;
78298 assert( pName2!=0 || pName1==0 );
78299 if( pName1==0 ){
78300 /* Form 1: Analyze everything */
78301 for(i=0; i<db->nDb; i++){
78302 if( i==1 ) continue; /* Do not analyze the TEMP database */
78303 analyzeDatabase(pParse, i);
78305 }else if( pName2->n==0 ){
78306 /* Form 2: Analyze the database or table named */
78307 iDb = sqlite3FindDb(db, pName1);
78308 if( iDb>=0 ){
78309 analyzeDatabase(pParse, iDb);
78310 }else{
78311 z = sqlite3NameFromToken(db, pName1);
78312 if( z ){
78313 if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){
78314 analyzeTable(pParse, pIdx->pTable, pIdx);
78315 }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){
78316 analyzeTable(pParse, pTab, 0);
78318 sqlite3DbFree(db, z);
78321 }else{
78322 /* Form 3: Analyze the fully qualified table name */
78323 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
78324 if( iDb>=0 ){
78325 zDb = db->aDb[iDb].zName;
78326 z = sqlite3NameFromToken(db, pTableName);
78327 if( z ){
78328 if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
78329 analyzeTable(pParse, pIdx->pTable, pIdx);
78330 }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
78331 analyzeTable(pParse, pTab, 0);
78333 sqlite3DbFree(db, z);
78340 ** Used to pass information from the analyzer reader through to the
78341 ** callback routine.
78343 typedef struct analysisInfo analysisInfo;
78344 struct analysisInfo {
78345 sqlite3 *db;
78346 const char *zDatabase;
78350 ** This callback is invoked once for each index when reading the
78351 ** sqlite_stat1 table.
78353 ** argv[0] = name of the table
78354 ** argv[1] = name of the index (might be NULL)
78355 ** argv[2] = results of analysis - on integer for each column
78357 ** Entries for which argv[1]==NULL simply record the number of rows in
78358 ** the table.
78360 static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
78361 analysisInfo *pInfo = (analysisInfo*)pData;
78362 Index *pIndex;
78363 Table *pTable;
78364 int i, c, n;
78365 tRowcnt v;
78366 const char *z;
78368 assert( argc==3 );
78369 UNUSED_PARAMETER2(NotUsed, argc);
78371 if( argv==0 || argv[0]==0 || argv[2]==0 ){
78372 return 0;
78374 pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
78375 if( pTable==0 ){
78376 return 0;
78378 if( argv[1] ){
78379 pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
78380 }else{
78381 pIndex = 0;
78383 n = pIndex ? pIndex->nColumn : 0;
78384 z = argv[2];
78385 for(i=0; *z && i<=n; i++){
78386 v = 0;
78387 while( (c=z[0])>='0' && c<='9' ){
78388 v = v*10 + c - '0';
78389 z++;
78391 if( i==0 ) pTable->nRowEst = v;
78392 if( pIndex==0 ) break;
78393 pIndex->aiRowEst[i] = v;
78394 if( *z==' ' ) z++;
78395 if( memcmp(z, "unordered", 10)==0 ){
78396 pIndex->bUnordered = 1;
78397 break;
78400 return 0;
78404 ** If the Index.aSample variable is not NULL, delete the aSample[] array
78405 ** and its contents.
78407 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
78408 #ifdef SQLITE_ENABLE_STAT3
78409 if( pIdx->aSample ){
78410 int j;
78411 for(j=0; j<pIdx->nSample; j++){
78412 IndexSample *p = &pIdx->aSample[j];
78413 if( p->eType==SQLITE_TEXT || p->eType==SQLITE_BLOB ){
78414 sqlite3DbFree(db, p->u.z);
78417 sqlite3DbFree(db, pIdx->aSample);
78419 if( db && db->pnBytesFreed==0 ){
78420 pIdx->nSample = 0;
78421 pIdx->aSample = 0;
78423 #else
78424 UNUSED_PARAMETER(db);
78425 UNUSED_PARAMETER(pIdx);
78426 #endif
78429 #ifdef SQLITE_ENABLE_STAT3
78431 ** Load content from the sqlite_stat3 table into the Index.aSample[]
78432 ** arrays of all indices.
78434 static int loadStat3(sqlite3 *db, const char *zDb){
78435 int rc; /* Result codes from subroutines */
78436 sqlite3_stmt *pStmt = 0; /* An SQL statement being run */
78437 char *zSql; /* Text of the SQL statement */
78438 Index *pPrevIdx = 0; /* Previous index in the loop */
78439 int idx = 0; /* slot in pIdx->aSample[] for next sample */
78440 int eType; /* Datatype of a sample */
78441 IndexSample *pSample; /* A slot in pIdx->aSample[] */
78443 if( !sqlite3FindTable(db, "sqlite_stat3", zDb) ){
78444 return SQLITE_OK;
78447 zSql = sqlite3MPrintf(db,
78448 "SELECT idx,count(*) FROM %Q.sqlite_stat3"
78449 " GROUP BY idx", zDb);
78450 if( !zSql ){
78451 return SQLITE_NOMEM;
78453 rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
78454 sqlite3DbFree(db, zSql);
78455 if( rc ) return rc;
78457 while( sqlite3_step(pStmt)==SQLITE_ROW ){
78458 char *zIndex; /* Index name */
78459 Index *pIdx; /* Pointer to the index object */
78460 int nSample; /* Number of samples */
78462 zIndex = (char *)sqlite3_column_text(pStmt, 0);
78463 if( zIndex==0 ) continue;
78464 nSample = sqlite3_column_int(pStmt, 1);
78465 pIdx = sqlite3FindIndex(db, zIndex, zDb);
78466 if( pIdx==0 ) continue;
78467 assert( pIdx->nSample==0 );
78468 pIdx->nSample = nSample;
78469 pIdx->aSample = sqlite3MallocZero( nSample*sizeof(IndexSample) );
78470 pIdx->avgEq = pIdx->aiRowEst[1];
78471 if( pIdx->aSample==0 ){
78472 db->mallocFailed = 1;
78473 sqlite3_finalize(pStmt);
78474 return SQLITE_NOMEM;
78477 rc = sqlite3_finalize(pStmt);
78478 if( rc ) return rc;
78480 zSql = sqlite3MPrintf(db,
78481 "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat3", zDb);
78482 if( !zSql ){
78483 return SQLITE_NOMEM;
78485 rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
78486 sqlite3DbFree(db, zSql);
78487 if( rc ) return rc;
78489 while( sqlite3_step(pStmt)==SQLITE_ROW ){
78490 char *zIndex; /* Index name */
78491 Index *pIdx; /* Pointer to the index object */
78492 int i; /* Loop counter */
78493 tRowcnt sumEq; /* Sum of the nEq values */
78495 zIndex = (char *)sqlite3_column_text(pStmt, 0);
78496 if( zIndex==0 ) continue;
78497 pIdx = sqlite3FindIndex(db, zIndex, zDb);
78498 if( pIdx==0 ) continue;
78499 if( pIdx==pPrevIdx ){
78500 idx++;
78501 }else{
78502 pPrevIdx = pIdx;
78503 idx = 0;
78505 assert( idx<pIdx->nSample );
78506 pSample = &pIdx->aSample[idx];
78507 pSample->nEq = (tRowcnt)sqlite3_column_int64(pStmt, 1);
78508 pSample->nLt = (tRowcnt)sqlite3_column_int64(pStmt, 2);
78509 pSample->nDLt = (tRowcnt)sqlite3_column_int64(pStmt, 3);
78510 if( idx==pIdx->nSample-1 ){
78511 if( pSample->nDLt>0 ){
78512 for(i=0, sumEq=0; i<=idx-1; i++) sumEq += pIdx->aSample[i].nEq;
78513 pIdx->avgEq = (pSample->nLt - sumEq)/pSample->nDLt;
78515 if( pIdx->avgEq<=0 ) pIdx->avgEq = 1;
78517 eType = sqlite3_column_type(pStmt, 4);
78518 pSample->eType = (u8)eType;
78519 switch( eType ){
78520 case SQLITE_INTEGER: {
78521 pSample->u.i = sqlite3_column_int64(pStmt, 4);
78522 break;
78524 case SQLITE_FLOAT: {
78525 pSample->u.r = sqlite3_column_double(pStmt, 4);
78526 break;
78528 case SQLITE_NULL: {
78529 break;
78531 default: assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB ); {
78532 const char *z = (const char *)(
78533 (eType==SQLITE_BLOB) ?
78534 sqlite3_column_blob(pStmt, 4):
78535 sqlite3_column_text(pStmt, 4)
78537 int n = z ? sqlite3_column_bytes(pStmt, 4) : 0;
78538 pSample->nByte = n;
78539 if( n < 1){
78540 pSample->u.z = 0;
78541 }else{
78542 pSample->u.z = sqlite3Malloc(n);
78543 if( pSample->u.z==0 ){
78544 db->mallocFailed = 1;
78545 sqlite3_finalize(pStmt);
78546 return SQLITE_NOMEM;
78548 memcpy(pSample->u.z, z, n);
78553 return sqlite3_finalize(pStmt);
78555 #endif /* SQLITE_ENABLE_STAT3 */
78558 ** Load the content of the sqlite_stat1 and sqlite_stat3 tables. The
78559 ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
78560 ** arrays. The contents of sqlite_stat3 are used to populate the
78561 ** Index.aSample[] arrays.
78563 ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
78564 ** is returned. In this case, even if SQLITE_ENABLE_STAT3 was defined
78565 ** during compilation and the sqlite_stat3 table is present, no data is
78566 ** read from it.
78568 ** If SQLITE_ENABLE_STAT3 was defined during compilation and the
78569 ** sqlite_stat3 table is not present in the database, SQLITE_ERROR is
78570 ** returned. However, in this case, data is read from the sqlite_stat1
78571 ** table (if it is present) before returning.
78573 ** If an OOM error occurs, this function always sets db->mallocFailed.
78574 ** This means if the caller does not care about other errors, the return
78575 ** code may be ignored.
78577 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
78578 analysisInfo sInfo;
78579 HashElem *i;
78580 char *zSql;
78581 int rc;
78583 assert( iDb>=0 && iDb<db->nDb );
78584 assert( db->aDb[iDb].pBt!=0 );
78586 /* Clear any prior statistics */
78587 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
78588 for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
78589 Index *pIdx = sqliteHashData(i);
78590 sqlite3DefaultRowEst(pIdx);
78591 #ifdef SQLITE_ENABLE_STAT3
78592 sqlite3DeleteIndexSamples(db, pIdx);
78593 pIdx->aSample = 0;
78594 #endif
78597 /* Check to make sure the sqlite_stat1 table exists */
78598 sInfo.db = db;
78599 sInfo.zDatabase = db->aDb[iDb].zName;
78600 if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
78601 return SQLITE_ERROR;
78604 /* Load new statistics out of the sqlite_stat1 table */
78605 zSql = sqlite3MPrintf(db,
78606 "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
78607 if( zSql==0 ){
78608 rc = SQLITE_NOMEM;
78609 }else{
78610 rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
78611 sqlite3DbFree(db, zSql);
78615 /* Load the statistics from the sqlite_stat3 table. */
78616 #ifdef SQLITE_ENABLE_STAT3
78617 if( rc==SQLITE_OK ){
78618 rc = loadStat3(db, sInfo.zDatabase);
78620 #endif
78622 if( rc==SQLITE_NOMEM ){
78623 db->mallocFailed = 1;
78625 return rc;
78629 #endif /* SQLITE_OMIT_ANALYZE */
78631 /************** End of analyze.c *********************************************/
78632 /************** Begin file attach.c ******************************************/
78634 ** 2003 April 6
78636 ** The author disclaims copyright to this source code. In place of
78637 ** a legal notice, here is a blessing:
78639 ** May you do good and not evil.
78640 ** May you find forgiveness for yourself and forgive others.
78641 ** May you share freely, never taking more than you give.
78643 *************************************************************************
78644 ** This file contains code used to implement the ATTACH and DETACH commands.
78647 #ifndef SQLITE_OMIT_ATTACH
78649 ** Resolve an expression that was part of an ATTACH or DETACH statement. This
78650 ** is slightly different from resolving a normal SQL expression, because simple
78651 ** identifiers are treated as strings, not possible column names or aliases.
78653 ** i.e. if the parser sees:
78655 ** ATTACH DATABASE abc AS def
78657 ** it treats the two expressions as literal strings 'abc' and 'def' instead of
78658 ** looking for columns of the same name.
78660 ** This only applies to the root node of pExpr, so the statement:
78662 ** ATTACH DATABASE abc||def AS 'db2'
78664 ** will fail because neither abc or def can be resolved.
78666 static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
78668 int rc = SQLITE_OK;
78669 if( pExpr ){
78670 if( pExpr->op!=TK_ID ){
78671 rc = sqlite3ResolveExprNames(pName, pExpr);
78672 if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
78673 sqlite3ErrorMsg(pName->pParse, "invalid name: \"%s\"", pExpr->u.zToken);
78674 return SQLITE_ERROR;
78676 }else{
78677 pExpr->op = TK_STRING;
78680 return rc;
78684 ** An SQL user-function registered to do the work of an ATTACH statement. The
78685 ** three arguments to the function come directly from an attach statement:
78687 ** ATTACH DATABASE x AS y KEY z
78689 ** SELECT sqlite_attach(x, y, z)
78691 ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
78692 ** third argument.
78694 static void attachFunc(
78695 sqlite3_context *context,
78696 int NotUsed,
78697 sqlite3_value **argv
78699 int i;
78700 int rc = 0;
78701 sqlite3 *db = sqlite3_context_db_handle(context);
78702 const char *zName;
78703 const char *zFile;
78704 char *zPath = 0;
78705 char *zErr = 0;
78706 unsigned int flags;
78707 Db *aNew;
78708 char *zErrDyn = 0;
78709 sqlite3_vfs *pVfs;
78711 UNUSED_PARAMETER(NotUsed);
78713 zFile = (const char *)sqlite3_value_text(argv[0]);
78714 zName = (const char *)sqlite3_value_text(argv[1]);
78715 if( zFile==0 ) zFile = "";
78716 if( zName==0 ) zName = "";
78718 /* Check for the following errors:
78720 ** * Too many attached databases,
78721 ** * Transaction currently open
78722 ** * Specified database name already being used.
78724 if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
78725 zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
78726 db->aLimit[SQLITE_LIMIT_ATTACHED]
78728 goto attach_error;
78730 if( !db->autoCommit ){
78731 zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
78732 goto attach_error;
78734 for(i=0; i<db->nDb; i++){
78735 char *z = db->aDb[i].zName;
78736 assert( z && zName );
78737 if( sqlite3StrICmp(z, zName)==0 ){
78738 zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
78739 goto attach_error;
78743 /* Allocate the new entry in the db->aDb[] array and initialise the schema
78744 ** hash tables.
78746 if( db->aDb==db->aDbStatic ){
78747 aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
78748 if( aNew==0 ) return;
78749 memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
78750 }else{
78751 aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
78752 if( aNew==0 ) return;
78754 db->aDb = aNew;
78755 aNew = &db->aDb[db->nDb];
78756 memset(aNew, 0, sizeof(*aNew));
78758 /* Open the database file. If the btree is successfully opened, use
78759 ** it to obtain the database schema. At this point the schema may
78760 ** or may not be initialised.
78762 flags = db->openFlags;
78763 rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
78764 if( rc!=SQLITE_OK ){
78765 if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
78766 sqlite3_result_error(context, zErr, -1);
78767 sqlite3_free(zErr);
78768 return;
78770 assert( pVfs );
78771 flags |= SQLITE_OPEN_MAIN_DB;
78772 rc = sqlite3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags);
78773 sqlite3_free( zPath );
78774 db->nDb++;
78775 if( rc==SQLITE_CONSTRAINT ){
78776 rc = SQLITE_ERROR;
78777 zErrDyn = sqlite3MPrintf(db, "database is already attached");
78778 }else if( rc==SQLITE_OK ){
78779 Pager *pPager;
78780 aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
78781 if( !aNew->pSchema ){
78782 rc = SQLITE_NOMEM;
78783 }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
78784 zErrDyn = sqlite3MPrintf(db,
78785 "attached databases must use the same text encoding as main database");
78786 rc = SQLITE_ERROR;
78788 pPager = sqlite3BtreePager(aNew->pBt);
78789 sqlite3PagerLockingMode(pPager, db->dfltLockMode);
78790 sqlite3BtreeSecureDelete(aNew->pBt,
78791 sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
78793 aNew->safety_level = 3;
78794 aNew->zName = sqlite3DbStrDup(db, zName);
78795 if( rc==SQLITE_OK && aNew->zName==0 ){
78796 rc = SQLITE_NOMEM;
78800 #ifdef SQLITE_HAS_CODEC
78801 if( rc==SQLITE_OK ){
78802 extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
78803 extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
78804 int nKey;
78805 char *zKey;
78806 int t = sqlite3_value_type(argv[2]);
78807 switch( t ){
78808 case SQLITE_INTEGER:
78809 case SQLITE_FLOAT:
78810 zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
78811 rc = SQLITE_ERROR;
78812 break;
78814 case SQLITE_TEXT:
78815 case SQLITE_BLOB:
78816 nKey = sqlite3_value_bytes(argv[2]);
78817 zKey = (char *)sqlite3_value_blob(argv[2]);
78818 rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
78819 break;
78821 case SQLITE_NULL:
78822 /* No key specified. Use the key from the main database */
78823 sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
78824 if( nKey>0 || sqlite3BtreeGetReserve(db->aDb[0].pBt)>0 ){
78825 rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
78827 break;
78830 #endif
78832 /* If the file was opened successfully, read the schema for the new database.
78833 ** If this fails, or if opening the file failed, then close the file and
78834 ** remove the entry from the db->aDb[] array. i.e. put everything back the way
78835 ** we found it.
78837 if( rc==SQLITE_OK ){
78838 sqlite3BtreeEnterAll(db);
78839 rc = sqlite3Init(db, &zErrDyn);
78840 sqlite3BtreeLeaveAll(db);
78842 if( rc ){
78843 int iDb = db->nDb - 1;
78844 assert( iDb>=2 );
78845 if( db->aDb[iDb].pBt ){
78846 sqlite3BtreeClose(db->aDb[iDb].pBt);
78847 db->aDb[iDb].pBt = 0;
78848 db->aDb[iDb].pSchema = 0;
78850 sqlite3ResetInternalSchema(db, -1);
78851 db->nDb = iDb;
78852 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
78853 db->mallocFailed = 1;
78854 sqlite3DbFree(db, zErrDyn);
78855 zErrDyn = sqlite3MPrintf(db, "out of memory");
78856 }else if( zErrDyn==0 ){
78857 zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
78859 goto attach_error;
78862 return;
78864 attach_error:
78865 /* Return an error if we get here */
78866 if( zErrDyn ){
78867 sqlite3_result_error(context, zErrDyn, -1);
78868 sqlite3DbFree(db, zErrDyn);
78870 if( rc ) sqlite3_result_error_code(context, rc);
78874 ** An SQL user-function registered to do the work of an DETACH statement. The
78875 ** three arguments to the function come directly from a detach statement:
78877 ** DETACH DATABASE x
78879 ** SELECT sqlite_detach(x)
78881 static void detachFunc(
78882 sqlite3_context *context,
78883 int NotUsed,
78884 sqlite3_value **argv
78886 const char *zName = (const char *)sqlite3_value_text(argv[0]);
78887 sqlite3 *db = sqlite3_context_db_handle(context);
78888 int i;
78889 Db *pDb = 0;
78890 char zErr[128];
78892 UNUSED_PARAMETER(NotUsed);
78894 if( zName==0 ) zName = "";
78895 for(i=0; i<db->nDb; i++){
78896 pDb = &db->aDb[i];
78897 if( pDb->pBt==0 ) continue;
78898 if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
78901 if( i>=db->nDb ){
78902 sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
78903 goto detach_error;
78905 if( i<2 ){
78906 sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
78907 goto detach_error;
78909 if( !db->autoCommit ){
78910 sqlite3_snprintf(sizeof(zErr), zErr,
78911 "cannot DETACH database within transaction");
78912 goto detach_error;
78914 if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
78915 sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
78916 goto detach_error;
78919 sqlite3BtreeClose(pDb->pBt);
78920 pDb->pBt = 0;
78921 pDb->pSchema = 0;
78922 sqlite3ResetInternalSchema(db, -1);
78923 return;
78925 detach_error:
78926 sqlite3_result_error(context, zErr, -1);
78930 ** This procedure generates VDBE code for a single invocation of either the
78931 ** sqlite_detach() or sqlite_attach() SQL user functions.
78933 static void codeAttach(
78934 Parse *pParse, /* The parser context */
78935 int type, /* Either SQLITE_ATTACH or SQLITE_DETACH */
78936 FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
78937 Expr *pAuthArg, /* Expression to pass to authorization callback */
78938 Expr *pFilename, /* Name of database file */
78939 Expr *pDbname, /* Name of the database to use internally */
78940 Expr *pKey /* Database key for encryption extension */
78942 int rc;
78943 NameContext sName;
78944 Vdbe *v;
78945 sqlite3* db = pParse->db;
78946 int regArgs;
78948 memset(&sName, 0, sizeof(NameContext));
78949 sName.pParse = pParse;
78951 if(
78952 SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
78953 SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
78954 SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
78956 pParse->nErr++;
78957 goto attach_end;
78960 #ifndef SQLITE_OMIT_AUTHORIZATION
78961 if( pAuthArg ){
78962 char *zAuthArg;
78963 if( pAuthArg->op==TK_STRING ){
78964 zAuthArg = pAuthArg->u.zToken;
78965 }else{
78966 zAuthArg = 0;
78968 rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
78969 if(rc!=SQLITE_OK ){
78970 goto attach_end;
78973 #endif /* SQLITE_OMIT_AUTHORIZATION */
78976 v = sqlite3GetVdbe(pParse);
78977 regArgs = sqlite3GetTempRange(pParse, 4);
78978 sqlite3ExprCode(pParse, pFilename, regArgs);
78979 sqlite3ExprCode(pParse, pDbname, regArgs+1);
78980 sqlite3ExprCode(pParse, pKey, regArgs+2);
78982 assert( v || db->mallocFailed );
78983 if( v ){
78984 sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
78985 assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
78986 sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
78987 sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
78989 /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
78990 ** statement only). For DETACH, set it to false (expire all existing
78991 ** statements).
78993 sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
78996 attach_end:
78997 sqlite3ExprDelete(db, pFilename);
78998 sqlite3ExprDelete(db, pDbname);
78999 sqlite3ExprDelete(db, pKey);
79003 ** Called by the parser to compile a DETACH statement.
79005 ** DETACH pDbname
79007 SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
79008 static const FuncDef detach_func = {
79009 1, /* nArg */
79010 SQLITE_UTF8, /* iPrefEnc */
79011 0, /* flags */
79012 0, /* pUserData */
79013 0, /* pNext */
79014 detachFunc, /* xFunc */
79015 0, /* xStep */
79016 0, /* xFinalize */
79017 "sqlite_detach", /* zName */
79018 0, /* pHash */
79019 0 /* pDestructor */
79021 codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
79025 ** Called by the parser to compile an ATTACH statement.
79027 ** ATTACH p AS pDbname KEY pKey
79029 SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
79030 static const FuncDef attach_func = {
79031 3, /* nArg */
79032 SQLITE_UTF8, /* iPrefEnc */
79033 0, /* flags */
79034 0, /* pUserData */
79035 0, /* pNext */
79036 attachFunc, /* xFunc */
79037 0, /* xStep */
79038 0, /* xFinalize */
79039 "sqlite_attach", /* zName */
79040 0, /* pHash */
79041 0 /* pDestructor */
79043 codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
79045 #endif /* SQLITE_OMIT_ATTACH */
79048 ** Initialize a DbFixer structure. This routine must be called prior
79049 ** to passing the structure to one of the sqliteFixAAAA() routines below.
79051 ** The return value indicates whether or not fixation is required. TRUE
79052 ** means we do need to fix the database references, FALSE means we do not.
79054 SQLITE_PRIVATE int sqlite3FixInit(
79055 DbFixer *pFix, /* The fixer to be initialized */
79056 Parse *pParse, /* Error messages will be written here */
79057 int iDb, /* This is the database that must be used */
79058 const char *zType, /* "view", "trigger", or "index" */
79059 const Token *pName /* Name of the view, trigger, or index */
79061 sqlite3 *db;
79063 if( NEVER(iDb<0) || iDb==1 ) return 0;
79064 db = pParse->db;
79065 assert( db->nDb>iDb );
79066 pFix->pParse = pParse;
79067 pFix->zDb = db->aDb[iDb].zName;
79068 pFix->zType = zType;
79069 pFix->pName = pName;
79070 return 1;
79074 ** The following set of routines walk through the parse tree and assign
79075 ** a specific database to all table references where the database name
79076 ** was left unspecified in the original SQL statement. The pFix structure
79077 ** must have been initialized by a prior call to sqlite3FixInit().
79079 ** These routines are used to make sure that an index, trigger, or
79080 ** view in one database does not refer to objects in a different database.
79081 ** (Exception: indices, triggers, and views in the TEMP database are
79082 ** allowed to refer to anything.) If a reference is explicitly made
79083 ** to an object in a different database, an error message is added to
79084 ** pParse->zErrMsg and these routines return non-zero. If everything
79085 ** checks out, these routines return 0.
79087 SQLITE_PRIVATE int sqlite3FixSrcList(
79088 DbFixer *pFix, /* Context of the fixation */
79089 SrcList *pList /* The Source list to check and modify */
79091 int i;
79092 const char *zDb;
79093 struct SrcList_item *pItem;
79095 if( NEVER(pList==0) ) return 0;
79096 zDb = pFix->zDb;
79097 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
79098 if( pItem->zDatabase==0 ){
79099 pItem->zDatabase = sqlite3DbStrDup(pFix->pParse->db, zDb);
79100 }else if( sqlite3StrICmp(pItem->zDatabase,zDb)!=0 ){
79101 sqlite3ErrorMsg(pFix->pParse,
79102 "%s %T cannot reference objects in database %s",
79103 pFix->zType, pFix->pName, pItem->zDatabase);
79104 return 1;
79106 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
79107 if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
79108 if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
79109 #endif
79111 return 0;
79113 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
79114 SQLITE_PRIVATE int sqlite3FixSelect(
79115 DbFixer *pFix, /* Context of the fixation */
79116 Select *pSelect /* The SELECT statement to be fixed to one database */
79118 while( pSelect ){
79119 if( sqlite3FixExprList(pFix, pSelect->pEList) ){
79120 return 1;
79122 if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
79123 return 1;
79125 if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
79126 return 1;
79128 if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
79129 return 1;
79131 pSelect = pSelect->pPrior;
79133 return 0;
79135 SQLITE_PRIVATE int sqlite3FixExpr(
79136 DbFixer *pFix, /* Context of the fixation */
79137 Expr *pExpr /* The expression to be fixed to one database */
79139 while( pExpr ){
79140 if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ) break;
79141 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
79142 if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
79143 }else{
79144 if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
79146 if( sqlite3FixExpr(pFix, pExpr->pRight) ){
79147 return 1;
79149 pExpr = pExpr->pLeft;
79151 return 0;
79153 SQLITE_PRIVATE int sqlite3FixExprList(
79154 DbFixer *pFix, /* Context of the fixation */
79155 ExprList *pList /* The expression to be fixed to one database */
79157 int i;
79158 struct ExprList_item *pItem;
79159 if( pList==0 ) return 0;
79160 for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
79161 if( sqlite3FixExpr(pFix, pItem->pExpr) ){
79162 return 1;
79165 return 0;
79167 #endif
79169 #ifndef SQLITE_OMIT_TRIGGER
79170 SQLITE_PRIVATE int sqlite3FixTriggerStep(
79171 DbFixer *pFix, /* Context of the fixation */
79172 TriggerStep *pStep /* The trigger step be fixed to one database */
79174 while( pStep ){
79175 if( sqlite3FixSelect(pFix, pStep->pSelect) ){
79176 return 1;
79178 if( sqlite3FixExpr(pFix, pStep->pWhere) ){
79179 return 1;
79181 if( sqlite3FixExprList(pFix, pStep->pExprList) ){
79182 return 1;
79184 pStep = pStep->pNext;
79186 return 0;
79188 #endif
79190 /************** End of attach.c **********************************************/
79191 /************** Begin file auth.c ********************************************/
79193 ** 2003 January 11
79195 ** The author disclaims copyright to this source code. In place of
79196 ** a legal notice, here is a blessing:
79198 ** May you do good and not evil.
79199 ** May you find forgiveness for yourself and forgive others.
79200 ** May you share freely, never taking more than you give.
79202 *************************************************************************
79203 ** This file contains code used to implement the sqlite3_set_authorizer()
79204 ** API. This facility is an optional feature of the library. Embedded
79205 ** systems that do not need this facility may omit it by recompiling
79206 ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
79210 ** All of the code in this file may be omitted by defining a single
79211 ** macro.
79213 #ifndef SQLITE_OMIT_AUTHORIZATION
79216 ** Set or clear the access authorization function.
79218 ** The access authorization function is be called during the compilation
79219 ** phase to verify that the user has read and/or write access permission on
79220 ** various fields of the database. The first argument to the auth function
79221 ** is a copy of the 3rd argument to this routine. The second argument
79222 ** to the auth function is one of these constants:
79224 ** SQLITE_CREATE_INDEX
79225 ** SQLITE_CREATE_TABLE
79226 ** SQLITE_CREATE_TEMP_INDEX
79227 ** SQLITE_CREATE_TEMP_TABLE
79228 ** SQLITE_CREATE_TEMP_TRIGGER
79229 ** SQLITE_CREATE_TEMP_VIEW
79230 ** SQLITE_CREATE_TRIGGER
79231 ** SQLITE_CREATE_VIEW
79232 ** SQLITE_DELETE
79233 ** SQLITE_DROP_INDEX
79234 ** SQLITE_DROP_TABLE
79235 ** SQLITE_DROP_TEMP_INDEX
79236 ** SQLITE_DROP_TEMP_TABLE
79237 ** SQLITE_DROP_TEMP_TRIGGER
79238 ** SQLITE_DROP_TEMP_VIEW
79239 ** SQLITE_DROP_TRIGGER
79240 ** SQLITE_DROP_VIEW
79241 ** SQLITE_INSERT
79242 ** SQLITE_PRAGMA
79243 ** SQLITE_READ
79244 ** SQLITE_SELECT
79245 ** SQLITE_TRANSACTION
79246 ** SQLITE_UPDATE
79248 ** The third and fourth arguments to the auth function are the name of
79249 ** the table and the column that are being accessed. The auth function
79250 ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE. If
79251 ** SQLITE_OK is returned, it means that access is allowed. SQLITE_DENY
79252 ** means that the SQL statement will never-run - the sqlite3_exec() call
79253 ** will return with an error. SQLITE_IGNORE means that the SQL statement
79254 ** should run but attempts to read the specified column will return NULL
79255 ** and attempts to write the column will be ignored.
79257 ** Setting the auth function to NULL disables this hook. The default
79258 ** setting of the auth function is NULL.
79260 SQLITE_API int sqlite3_set_authorizer(
79261 sqlite3 *db,
79262 int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
79263 void *pArg
79265 sqlite3_mutex_enter(db->mutex);
79266 db->xAuth = xAuth;
79267 db->pAuthArg = pArg;
79268 sqlite3ExpirePreparedStatements(db);
79269 sqlite3_mutex_leave(db->mutex);
79270 return SQLITE_OK;
79274 ** Write an error message into pParse->zErrMsg that explains that the
79275 ** user-supplied authorization function returned an illegal value.
79277 static void sqliteAuthBadReturnCode(Parse *pParse){
79278 sqlite3ErrorMsg(pParse, "authorizer malfunction");
79279 pParse->rc = SQLITE_ERROR;
79283 ** Invoke the authorization callback for permission to read column zCol from
79284 ** table zTab in database zDb. This function assumes that an authorization
79285 ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
79287 ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
79288 ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
79289 ** is treated as SQLITE_DENY. In this case an error is left in pParse.
79291 SQLITE_PRIVATE int sqlite3AuthReadCol(
79292 Parse *pParse, /* The parser context */
79293 const char *zTab, /* Table name */
79294 const char *zCol, /* Column name */
79295 int iDb /* Index of containing database. */
79297 sqlite3 *db = pParse->db; /* Database handle */
79298 char *zDb = db->aDb[iDb].zName; /* Name of attached database */
79299 int rc; /* Auth callback return code */
79301 rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext);
79302 if( rc==SQLITE_DENY ){
79303 if( db->nDb>2 || iDb!=0 ){
79304 sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
79305 }else{
79306 sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
79308 pParse->rc = SQLITE_AUTH;
79309 }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
79310 sqliteAuthBadReturnCode(pParse);
79312 return rc;
79316 ** The pExpr should be a TK_COLUMN expression. The table referred to
79317 ** is in pTabList or else it is the NEW or OLD table of a trigger.
79318 ** Check to see if it is OK to read this particular column.
79320 ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
79321 ** instruction into a TK_NULL. If the auth function returns SQLITE_DENY,
79322 ** then generate an error.
79324 SQLITE_PRIVATE void sqlite3AuthRead(
79325 Parse *pParse, /* The parser context */
79326 Expr *pExpr, /* The expression to check authorization on */
79327 Schema *pSchema, /* The schema of the expression */
79328 SrcList *pTabList /* All table that pExpr might refer to */
79330 sqlite3 *db = pParse->db;
79331 Table *pTab = 0; /* The table being read */
79332 const char *zCol; /* Name of the column of the table */
79333 int iSrc; /* Index in pTabList->a[] of table being read */
79334 int iDb; /* The index of the database the expression refers to */
79335 int iCol; /* Index of column in table */
79337 if( db->xAuth==0 ) return;
79338 iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
79339 if( iDb<0 ){
79340 /* An attempt to read a column out of a subquery or other
79341 ** temporary table. */
79342 return;
79345 assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
79346 if( pExpr->op==TK_TRIGGER ){
79347 pTab = pParse->pTriggerTab;
79348 }else{
79349 assert( pTabList );
79350 for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
79351 if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
79352 pTab = pTabList->a[iSrc].pTab;
79353 break;
79357 iCol = pExpr->iColumn;
79358 if( NEVER(pTab==0) ) return;
79360 if( iCol>=0 ){
79361 assert( iCol<pTab->nCol );
79362 zCol = pTab->aCol[iCol].zName;
79363 }else if( pTab->iPKey>=0 ){
79364 assert( pTab->iPKey<pTab->nCol );
79365 zCol = pTab->aCol[pTab->iPKey].zName;
79366 }else{
79367 zCol = "ROWID";
79369 assert( iDb>=0 && iDb<db->nDb );
79370 if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
79371 pExpr->op = TK_NULL;
79376 ** Do an authorization check using the code and arguments given. Return
79377 ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY. If SQLITE_DENY
79378 ** is returned, then the error count and error message in pParse are
79379 ** modified appropriately.
79381 SQLITE_PRIVATE int sqlite3AuthCheck(
79382 Parse *pParse,
79383 int code,
79384 const char *zArg1,
79385 const char *zArg2,
79386 const char *zArg3
79388 sqlite3 *db = pParse->db;
79389 int rc;
79391 /* Don't do any authorization checks if the database is initialising
79392 ** or if the parser is being invoked from within sqlite3_declare_vtab.
79394 if( db->init.busy || IN_DECLARE_VTAB ){
79395 return SQLITE_OK;
79398 if( db->xAuth==0 ){
79399 return SQLITE_OK;
79401 rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
79402 if( rc==SQLITE_DENY ){
79403 sqlite3ErrorMsg(pParse, "not authorized");
79404 pParse->rc = SQLITE_AUTH;
79405 }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
79406 rc = SQLITE_DENY;
79407 sqliteAuthBadReturnCode(pParse);
79409 return rc;
79413 ** Push an authorization context. After this routine is called, the
79414 ** zArg3 argument to authorization callbacks will be zContext until
79415 ** popped. Or if pParse==0, this routine is a no-op.
79417 SQLITE_PRIVATE void sqlite3AuthContextPush(
79418 Parse *pParse,
79419 AuthContext *pContext,
79420 const char *zContext
79422 assert( pParse );
79423 pContext->pParse = pParse;
79424 pContext->zAuthContext = pParse->zAuthContext;
79425 pParse->zAuthContext = zContext;
79429 ** Pop an authorization context that was previously pushed
79430 ** by sqlite3AuthContextPush
79432 SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
79433 if( pContext->pParse ){
79434 pContext->pParse->zAuthContext = pContext->zAuthContext;
79435 pContext->pParse = 0;
79439 #endif /* SQLITE_OMIT_AUTHORIZATION */
79441 /************** End of auth.c ************************************************/
79442 /************** Begin file build.c *******************************************/
79444 ** 2001 September 15
79446 ** The author disclaims copyright to this source code. In place of
79447 ** a legal notice, here is a blessing:
79449 ** May you do good and not evil.
79450 ** May you find forgiveness for yourself and forgive others.
79451 ** May you share freely, never taking more than you give.
79453 *************************************************************************
79454 ** This file contains C code routines that are called by the SQLite parser
79455 ** when syntax rules are reduced. The routines in this file handle the
79456 ** following kinds of SQL syntax:
79458 ** CREATE TABLE
79459 ** DROP TABLE
79460 ** CREATE INDEX
79461 ** DROP INDEX
79462 ** creating ID lists
79463 ** BEGIN TRANSACTION
79464 ** COMMIT
79465 ** ROLLBACK
79469 ** This routine is called when a new SQL statement is beginning to
79470 ** be parsed. Initialize the pParse structure as needed.
79472 SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
79473 pParse->explain = (u8)explainFlag;
79474 pParse->nVar = 0;
79477 #ifndef SQLITE_OMIT_SHARED_CACHE
79479 ** The TableLock structure is only used by the sqlite3TableLock() and
79480 ** codeTableLocks() functions.
79482 struct TableLock {
79483 int iDb; /* The database containing the table to be locked */
79484 int iTab; /* The root page of the table to be locked */
79485 u8 isWriteLock; /* True for write lock. False for a read lock */
79486 const char *zName; /* Name of the table */
79490 ** Record the fact that we want to lock a table at run-time.
79492 ** The table to be locked has root page iTab and is found in database iDb.
79493 ** A read or a write lock can be taken depending on isWritelock.
79495 ** This routine just records the fact that the lock is desired. The
79496 ** code to make the lock occur is generated by a later call to
79497 ** codeTableLocks() which occurs during sqlite3FinishCoding().
79499 SQLITE_PRIVATE void sqlite3TableLock(
79500 Parse *pParse, /* Parsing context */
79501 int iDb, /* Index of the database containing the table to lock */
79502 int iTab, /* Root page number of the table to be locked */
79503 u8 isWriteLock, /* True for a write lock */
79504 const char *zName /* Name of the table to be locked */
79506 Parse *pToplevel = sqlite3ParseToplevel(pParse);
79507 int i;
79508 int nBytes;
79509 TableLock *p;
79510 assert( iDb>=0 );
79512 for(i=0; i<pToplevel->nTableLock; i++){
79513 p = &pToplevel->aTableLock[i];
79514 if( p->iDb==iDb && p->iTab==iTab ){
79515 p->isWriteLock = (p->isWriteLock || isWriteLock);
79516 return;
79520 nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
79521 pToplevel->aTableLock =
79522 sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
79523 if( pToplevel->aTableLock ){
79524 p = &pToplevel->aTableLock[pToplevel->nTableLock++];
79525 p->iDb = iDb;
79526 p->iTab = iTab;
79527 p->isWriteLock = isWriteLock;
79528 p->zName = zName;
79529 }else{
79530 pToplevel->nTableLock = 0;
79531 pToplevel->db->mallocFailed = 1;
79536 ** Code an OP_TableLock instruction for each table locked by the
79537 ** statement (configured by calls to sqlite3TableLock()).
79539 static void codeTableLocks(Parse *pParse){
79540 int i;
79541 Vdbe *pVdbe;
79543 pVdbe = sqlite3GetVdbe(pParse);
79544 assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
79546 for(i=0; i<pParse->nTableLock; i++){
79547 TableLock *p = &pParse->aTableLock[i];
79548 int p1 = p->iDb;
79549 sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
79550 p->zName, P4_STATIC);
79553 #else
79554 #define codeTableLocks(x)
79555 #endif
79558 ** This routine is called after a single SQL statement has been
79559 ** parsed and a VDBE program to execute that statement has been
79560 ** prepared. This routine puts the finishing touches on the
79561 ** VDBE program and resets the pParse structure for the next
79562 ** parse.
79564 ** Note that if an error occurred, it might be the case that
79565 ** no VDBE code was generated.
79567 SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
79568 sqlite3 *db;
79569 Vdbe *v;
79571 db = pParse->db;
79572 if( db->mallocFailed ) return;
79573 if( pParse->nested ) return;
79574 if( pParse->nErr ) return;
79576 /* Begin by generating some termination code at the end of the
79577 ** vdbe program
79579 v = sqlite3GetVdbe(pParse);
79580 assert( !pParse->isMultiWrite
79581 || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
79582 if( v ){
79583 sqlite3VdbeAddOp0(v, OP_Halt);
79585 /* The cookie mask contains one bit for each database file open.
79586 ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
79587 ** set for each database that is used. Generate code to start a
79588 ** transaction on each used database and to verify the schema cookie
79589 ** on each used database.
79591 if( pParse->cookieGoto>0 ){
79592 yDbMask mask;
79593 int iDb;
79594 sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
79595 for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
79596 if( (mask & pParse->cookieMask)==0 ) continue;
79597 sqlite3VdbeUsesBtree(v, iDb);
79598 sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
79599 if( db->init.busy==0 ){
79600 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
79601 sqlite3VdbeAddOp3(v, OP_VerifyCookie,
79602 iDb, pParse->cookieValue[iDb],
79603 db->aDb[iDb].pSchema->iGeneration);
79606 #ifndef SQLITE_OMIT_VIRTUALTABLE
79608 int i;
79609 for(i=0; i<pParse->nVtabLock; i++){
79610 char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
79611 sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
79613 pParse->nVtabLock = 0;
79615 #endif
79617 /* Once all the cookies have been verified and transactions opened,
79618 ** obtain the required table-locks. This is a no-op unless the
79619 ** shared-cache feature is enabled.
79621 codeTableLocks(pParse);
79623 /* Initialize any AUTOINCREMENT data structures required.
79625 sqlite3AutoincrementBegin(pParse);
79627 /* Finally, jump back to the beginning of the executable code. */
79628 sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
79633 /* Get the VDBE program ready for execution
79635 if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
79636 #ifdef SQLITE_DEBUG
79637 FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
79638 sqlite3VdbeTrace(v, trace);
79639 #endif
79640 assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */
79641 /* A minimum of one cursor is required if autoincrement is used
79642 * See ticket [a696379c1f08866] */
79643 if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
79644 sqlite3VdbeMakeReady(v, pParse);
79645 pParse->rc = SQLITE_DONE;
79646 pParse->colNamesSet = 0;
79647 }else{
79648 pParse->rc = SQLITE_ERROR;
79650 pParse->nTab = 0;
79651 pParse->nMem = 0;
79652 pParse->nSet = 0;
79653 pParse->nVar = 0;
79654 pParse->cookieMask = 0;
79655 pParse->cookieGoto = 0;
79659 ** Run the parser and code generator recursively in order to generate
79660 ** code for the SQL statement given onto the end of the pParse context
79661 ** currently under construction. When the parser is run recursively
79662 ** this way, the final OP_Halt is not appended and other initialization
79663 ** and finalization steps are omitted because those are handling by the
79664 ** outermost parser.
79666 ** Not everything is nestable. This facility is designed to permit
79667 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
79668 ** care if you decide to try to use this routine for some other purposes.
79670 SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
79671 va_list ap;
79672 char *zSql;
79673 char *zErrMsg = 0;
79674 sqlite3 *db = pParse->db;
79675 # define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar))
79676 char saveBuf[SAVE_SZ];
79678 if( pParse->nErr ) return;
79679 assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
79680 va_start(ap, zFormat);
79681 zSql = sqlite3VMPrintf(db, zFormat, ap);
79682 va_end(ap);
79683 if( zSql==0 ){
79684 return; /* A malloc must have failed */
79686 pParse->nested++;
79687 memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
79688 memset(&pParse->nVar, 0, SAVE_SZ);
79689 sqlite3RunParser(pParse, zSql, &zErrMsg);
79690 sqlite3DbFree(db, zErrMsg);
79691 sqlite3DbFree(db, zSql);
79692 memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
79693 pParse->nested--;
79697 ** Locate the in-memory structure that describes a particular database
79698 ** table given the name of that table and (optionally) the name of the
79699 ** database containing the table. Return NULL if not found.
79701 ** If zDatabase is 0, all databases are searched for the table and the
79702 ** first matching table is returned. (No checking for duplicate table
79703 ** names is done.) The search order is TEMP first, then MAIN, then any
79704 ** auxiliary databases added using the ATTACH command.
79706 ** See also sqlite3LocateTable().
79708 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
79709 Table *p = 0;
79710 int i;
79711 int nName;
79712 assert( zName!=0 );
79713 nName = sqlite3Strlen30(zName);
79714 /* All mutexes are required for schema access. Make sure we hold them. */
79715 assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
79716 for(i=OMIT_TEMPDB; i<db->nDb; i++){
79717 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
79718 if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
79719 assert( sqlite3SchemaMutexHeld(db, j, 0) );
79720 p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
79721 if( p ) break;
79723 return p;
79727 ** Locate the in-memory structure that describes a particular database
79728 ** table given the name of that table and (optionally) the name of the
79729 ** database containing the table. Return NULL if not found. Also leave an
79730 ** error message in pParse->zErrMsg.
79732 ** The difference between this routine and sqlite3FindTable() is that this
79733 ** routine leaves an error message in pParse->zErrMsg where
79734 ** sqlite3FindTable() does not.
79736 SQLITE_PRIVATE Table *sqlite3LocateTable(
79737 Parse *pParse, /* context in which to report errors */
79738 int isView, /* True if looking for a VIEW rather than a TABLE */
79739 const char *zName, /* Name of the table we are looking for */
79740 const char *zDbase /* Name of the database. Might be NULL */
79742 Table *p;
79744 /* Read the database schema. If an error occurs, leave an error message
79745 ** and code in pParse and return NULL. */
79746 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
79747 return 0;
79750 p = sqlite3FindTable(pParse->db, zName, zDbase);
79751 if( p==0 ){
79752 const char *zMsg = isView ? "no such view" : "no such table";
79753 if( zDbase ){
79754 sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
79755 }else{
79756 sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
79758 pParse->checkSchema = 1;
79760 return p;
79764 ** Locate the in-memory structure that describes
79765 ** a particular index given the name of that index
79766 ** and the name of the database that contains the index.
79767 ** Return NULL if not found.
79769 ** If zDatabase is 0, all databases are searched for the
79770 ** table and the first matching index is returned. (No checking
79771 ** for duplicate index names is done.) The search order is
79772 ** TEMP first, then MAIN, then any auxiliary databases added
79773 ** using the ATTACH command.
79775 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
79776 Index *p = 0;
79777 int i;
79778 int nName = sqlite3Strlen30(zName);
79779 /* All mutexes are required for schema access. Make sure we hold them. */
79780 assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
79781 for(i=OMIT_TEMPDB; i<db->nDb; i++){
79782 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
79783 Schema *pSchema = db->aDb[j].pSchema;
79784 assert( pSchema );
79785 if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
79786 assert( sqlite3SchemaMutexHeld(db, j, 0) );
79787 p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
79788 if( p ) break;
79790 return p;
79794 ** Reclaim the memory used by an index
79796 static void freeIndex(sqlite3 *db, Index *p){
79797 #ifndef SQLITE_OMIT_ANALYZE
79798 sqlite3DeleteIndexSamples(db, p);
79799 #endif
79800 sqlite3DbFree(db, p->zColAff);
79801 sqlite3DbFree(db, p);
79805 ** For the index called zIdxName which is found in the database iDb,
79806 ** unlike that index from its Table then remove the index from
79807 ** the index hash table and free all memory structures associated
79808 ** with the index.
79810 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
79811 Index *pIndex;
79812 int len;
79813 Hash *pHash;
79815 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
79816 pHash = &db->aDb[iDb].pSchema->idxHash;
79817 len = sqlite3Strlen30(zIdxName);
79818 pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
79819 if( ALWAYS(pIndex) ){
79820 if( pIndex->pTable->pIndex==pIndex ){
79821 pIndex->pTable->pIndex = pIndex->pNext;
79822 }else{
79823 Index *p;
79824 /* Justification of ALWAYS(); The index must be on the list of
79825 ** indices. */
79826 p = pIndex->pTable->pIndex;
79827 while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
79828 if( ALWAYS(p && p->pNext==pIndex) ){
79829 p->pNext = pIndex->pNext;
79832 freeIndex(db, pIndex);
79834 db->flags |= SQLITE_InternChanges;
79838 ** Erase all schema information from the in-memory hash tables of
79839 ** a single database. This routine is called to reclaim memory
79840 ** before the database closes. It is also called during a rollback
79841 ** if there were schema changes during the transaction or if a
79842 ** schema-cookie mismatch occurs.
79844 ** If iDb<0 then reset the internal schema tables for all database
79845 ** files. If iDb>=0 then reset the internal schema for only the
79846 ** single file indicated.
79848 SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
79849 int i, j;
79850 assert( iDb<db->nDb );
79852 if( iDb>=0 ){
79853 /* Case 1: Reset the single schema identified by iDb */
79854 Db *pDb = &db->aDb[iDb];
79855 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
79856 assert( pDb->pSchema!=0 );
79857 sqlite3SchemaClear(pDb->pSchema);
79859 /* If any database other than TEMP is reset, then also reset TEMP
79860 ** since TEMP might be holding triggers that reference tables in the
79861 ** other database.
79863 if( iDb!=1 ){
79864 pDb = &db->aDb[1];
79865 assert( pDb->pSchema!=0 );
79866 sqlite3SchemaClear(pDb->pSchema);
79868 return;
79870 /* Case 2 (from here to the end): Reset all schemas for all attached
79871 ** databases. */
79872 assert( iDb<0 );
79873 sqlite3BtreeEnterAll(db);
79874 for(i=0; i<db->nDb; i++){
79875 Db *pDb = &db->aDb[i];
79876 if( pDb->pSchema ){
79877 sqlite3SchemaClear(pDb->pSchema);
79880 db->flags &= ~SQLITE_InternChanges;
79881 sqlite3VtabUnlockList(db);
79882 sqlite3BtreeLeaveAll(db);
79884 /* If one or more of the auxiliary database files has been closed,
79885 ** then remove them from the auxiliary database list. We take the
79886 ** opportunity to do this here since we have just deleted all of the
79887 ** schema hash tables and therefore do not have to make any changes
79888 ** to any of those tables.
79890 for(i=j=2; i<db->nDb; i++){
79891 struct Db *pDb = &db->aDb[i];
79892 if( pDb->pBt==0 ){
79893 sqlite3DbFree(db, pDb->zName);
79894 pDb->zName = 0;
79895 continue;
79897 if( j<i ){
79898 db->aDb[j] = db->aDb[i];
79900 j++;
79902 memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
79903 db->nDb = j;
79904 if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
79905 memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
79906 sqlite3DbFree(db, db->aDb);
79907 db->aDb = db->aDbStatic;
79912 ** This routine is called when a commit occurs.
79914 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
79915 db->flags &= ~SQLITE_InternChanges;
79919 ** Delete memory allocated for the column names of a table or view (the
79920 ** Table.aCol[] array).
79922 static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
79923 int i;
79924 Column *pCol;
79925 assert( pTable!=0 );
79926 if( (pCol = pTable->aCol)!=0 ){
79927 for(i=0; i<pTable->nCol; i++, pCol++){
79928 sqlite3DbFree(db, pCol->zName);
79929 sqlite3ExprDelete(db, pCol->pDflt);
79930 sqlite3DbFree(db, pCol->zDflt);
79931 sqlite3DbFree(db, pCol->zType);
79932 sqlite3DbFree(db, pCol->zColl);
79934 sqlite3DbFree(db, pTable->aCol);
79939 ** Remove the memory data structures associated with the given
79940 ** Table. No changes are made to disk by this routine.
79942 ** This routine just deletes the data structure. It does not unlink
79943 ** the table data structure from the hash table. But it does destroy
79944 ** memory structures of the indices and foreign keys associated with
79945 ** the table.
79947 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
79948 Index *pIndex, *pNext;
79950 assert( !pTable || pTable->nRef>0 );
79952 /* Do not delete the table until the reference count reaches zero. */
79953 if( !pTable ) return;
79954 if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
79956 /* Delete all indices associated with this table. */
79957 for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
79958 pNext = pIndex->pNext;
79959 assert( pIndex->pSchema==pTable->pSchema );
79960 if( !db || db->pnBytesFreed==0 ){
79961 char *zName = pIndex->zName;
79962 TESTONLY ( Index *pOld = ) sqlite3HashInsert(
79963 &pIndex->pSchema->idxHash, zName, sqlite3Strlen30(zName), 0
79965 assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
79966 assert( pOld==pIndex || pOld==0 );
79968 freeIndex(db, pIndex);
79971 /* Delete any foreign keys attached to this table. */
79972 sqlite3FkDelete(db, pTable);
79974 /* Delete the Table structure itself.
79976 sqliteDeleteColumnNames(db, pTable);
79977 sqlite3DbFree(db, pTable->zName);
79978 sqlite3DbFree(db, pTable->zColAff);
79979 sqlite3SelectDelete(db, pTable->pSelect);
79980 #ifndef SQLITE_OMIT_CHECK
79981 sqlite3ExprDelete(db, pTable->pCheck);
79982 #endif
79983 #ifndef SQLITE_OMIT_VIRTUALTABLE
79984 sqlite3VtabClear(db, pTable);
79985 #endif
79986 sqlite3DbFree(db, pTable);
79990 ** Unlink the given table from the hash tables and the delete the
79991 ** table structure with all its indices and foreign keys.
79993 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
79994 Table *p;
79995 Db *pDb;
79997 assert( db!=0 );
79998 assert( iDb>=0 && iDb<db->nDb );
79999 assert( zTabName );
80000 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
80001 testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
80002 pDb = &db->aDb[iDb];
80003 p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
80004 sqlite3Strlen30(zTabName),0);
80005 sqlite3DeleteTable(db, p);
80006 db->flags |= SQLITE_InternChanges;
80010 ** Given a token, return a string that consists of the text of that
80011 ** token. Space to hold the returned string
80012 ** is obtained from sqliteMalloc() and must be freed by the calling
80013 ** function.
80015 ** Any quotation marks (ex: "name", 'name', [name], or `name`) that
80016 ** surround the body of the token are removed.
80018 ** Tokens are often just pointers into the original SQL text and so
80019 ** are not \000 terminated and are not persistent. The returned string
80020 ** is \000 terminated and is persistent.
80022 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
80023 char *zName;
80024 if( pName ){
80025 zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
80026 sqlite3Dequote(zName);
80027 }else{
80028 zName = 0;
80030 return zName;
80034 ** Open the sqlite_master table stored in database number iDb for
80035 ** writing. The table is opened using cursor 0.
80037 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
80038 Vdbe *v = sqlite3GetVdbe(p);
80039 sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
80040 sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
80041 sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32); /* 5 column table */
80042 if( p->nTab==0 ){
80043 p->nTab = 1;
80048 ** Parameter zName points to a nul-terminated buffer containing the name
80049 ** of a database ("main", "temp" or the name of an attached db). This
80050 ** function returns the index of the named database in db->aDb[], or
80051 ** -1 if the named db cannot be found.
80053 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
80054 int i = -1; /* Database number */
80055 if( zName ){
80056 Db *pDb;
80057 int n = sqlite3Strlen30(zName);
80058 for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
80059 if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
80060 0==sqlite3StrICmp(pDb->zName, zName) ){
80061 break;
80065 return i;
80069 ** The token *pName contains the name of a database (either "main" or
80070 ** "temp" or the name of an attached db). This routine returns the
80071 ** index of the named database in db->aDb[], or -1 if the named db
80072 ** does not exist.
80074 SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
80075 int i; /* Database number */
80076 char *zName; /* Name we are searching for */
80077 zName = sqlite3NameFromToken(db, pName);
80078 i = sqlite3FindDbName(db, zName);
80079 sqlite3DbFree(db, zName);
80080 return i;
80083 /* The table or view or trigger name is passed to this routine via tokens
80084 ** pName1 and pName2. If the table name was fully qualified, for example:
80086 ** CREATE TABLE xxx.yyy (...);
80088 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
80089 ** the table name is not fully qualified, i.e.:
80091 ** CREATE TABLE yyy(...);
80093 ** Then pName1 is set to "yyy" and pName2 is "".
80095 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
80096 ** pName2) that stores the unqualified table name. The index of the
80097 ** database "xxx" is returned.
80099 SQLITE_PRIVATE int sqlite3TwoPartName(
80100 Parse *pParse, /* Parsing and code generating context */
80101 Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
80102 Token *pName2, /* The "yyy" in the name "xxx.yyy" */
80103 Token **pUnqual /* Write the unqualified object name here */
80105 int iDb; /* Database holding the object */
80106 sqlite3 *db = pParse->db;
80108 if( ALWAYS(pName2!=0) && pName2->n>0 ){
80109 if( db->init.busy ) {
80110 sqlite3ErrorMsg(pParse, "corrupt database");
80111 pParse->nErr++;
80112 return -1;
80114 *pUnqual = pName2;
80115 iDb = sqlite3FindDb(db, pName1);
80116 if( iDb<0 ){
80117 sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
80118 pParse->nErr++;
80119 return -1;
80121 }else{
80122 assert( db->init.iDb==0 || db->init.busy );
80123 iDb = db->init.iDb;
80124 *pUnqual = pName1;
80126 return iDb;
80130 ** This routine is used to check if the UTF-8 string zName is a legal
80131 ** unqualified name for a new schema object (table, index, view or
80132 ** trigger). All names are legal except those that begin with the string
80133 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
80134 ** is reserved for internal use.
80136 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
80137 if( !pParse->db->init.busy && pParse->nested==0
80138 && (pParse->db->flags & SQLITE_WriteSchema)==0
80139 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
80140 sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
80141 return SQLITE_ERROR;
80143 return SQLITE_OK;
80147 ** Begin constructing a new table representation in memory. This is
80148 ** the first of several action routines that get called in response
80149 ** to a CREATE TABLE statement. In particular, this routine is called
80150 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
80151 ** flag is true if the table should be stored in the auxiliary database
80152 ** file instead of in the main database file. This is normally the case
80153 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
80154 ** CREATE and TABLE.
80156 ** The new table record is initialized and put in pParse->pNewTable.
80157 ** As more of the CREATE TABLE statement is parsed, additional action
80158 ** routines will be called to add more information to this record.
80159 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
80160 ** is called to complete the construction of the new table record.
80162 SQLITE_PRIVATE void sqlite3StartTable(
80163 Parse *pParse, /* Parser context */
80164 Token *pName1, /* First part of the name of the table or view */
80165 Token *pName2, /* Second part of the name of the table or view */
80166 int isTemp, /* True if this is a TEMP table */
80167 int isView, /* True if this is a VIEW */
80168 int isVirtual, /* True if this is a VIRTUAL table */
80169 int noErr /* Do nothing if table already exists */
80171 Table *pTable;
80172 char *zName = 0; /* The name of the new table */
80173 sqlite3 *db = pParse->db;
80174 Vdbe *v;
80175 int iDb; /* Database number to create the table in */
80176 Token *pName; /* Unqualified name of the table to create */
80178 /* The table or view name to create is passed to this routine via tokens
80179 ** pName1 and pName2. If the table name was fully qualified, for example:
80181 ** CREATE TABLE xxx.yyy (...);
80183 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
80184 ** the table name is not fully qualified, i.e.:
80186 ** CREATE TABLE yyy(...);
80188 ** Then pName1 is set to "yyy" and pName2 is "".
80190 ** The call below sets the pName pointer to point at the token (pName1 or
80191 ** pName2) that stores the unqualified table name. The variable iDb is
80192 ** set to the index of the database that the table or view is to be
80193 ** created in.
80195 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
80196 if( iDb<0 ) return;
80197 if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
80198 /* If creating a temp table, the name may not be qualified. Unless
80199 ** the database name is "temp" anyway. */
80200 sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
80201 return;
80203 if( !OMIT_TEMPDB && isTemp ) iDb = 1;
80205 pParse->sNameToken = *pName;
80206 zName = sqlite3NameFromToken(db, pName);
80207 if( zName==0 ) return;
80208 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
80209 goto begin_table_error;
80211 if( db->init.iDb==1 ) isTemp = 1;
80212 #ifndef SQLITE_OMIT_AUTHORIZATION
80213 assert( (isTemp & 1)==isTemp );
80215 int code;
80216 char *zDb = db->aDb[iDb].zName;
80217 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
80218 goto begin_table_error;
80220 if( isView ){
80221 if( !OMIT_TEMPDB && isTemp ){
80222 code = SQLITE_CREATE_TEMP_VIEW;
80223 }else{
80224 code = SQLITE_CREATE_VIEW;
80226 }else{
80227 if( !OMIT_TEMPDB && isTemp ){
80228 code = SQLITE_CREATE_TEMP_TABLE;
80229 }else{
80230 code = SQLITE_CREATE_TABLE;
80233 if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
80234 goto begin_table_error;
80237 #endif
80239 /* Make sure the new table name does not collide with an existing
80240 ** index or table name in the same database. Issue an error message if
80241 ** it does. The exception is if the statement being parsed was passed
80242 ** to an sqlite3_declare_vtab() call. In that case only the column names
80243 ** and types will be used, so there is no need to test for namespace
80244 ** collisions.
80246 if( !IN_DECLARE_VTAB ){
80247 char *zDb = db->aDb[iDb].zName;
80248 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
80249 goto begin_table_error;
80251 pTable = sqlite3FindTable(db, zName, zDb);
80252 if( pTable ){
80253 if( !noErr ){
80254 sqlite3ErrorMsg(pParse, "table %T already exists", pName);
80255 }else{
80256 assert( !db->init.busy );
80257 sqlite3CodeVerifySchema(pParse, iDb);
80259 goto begin_table_error;
80261 if( sqlite3FindIndex(db, zName, zDb)!=0 ){
80262 sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
80263 goto begin_table_error;
80267 pTable = sqlite3DbMallocZero(db, sizeof(Table));
80268 if( pTable==0 ){
80269 db->mallocFailed = 1;
80270 pParse->rc = SQLITE_NOMEM;
80271 pParse->nErr++;
80272 goto begin_table_error;
80274 pTable->zName = zName;
80275 pTable->iPKey = -1;
80276 pTable->pSchema = db->aDb[iDb].pSchema;
80277 pTable->nRef = 1;
80278 pTable->nRowEst = 1000000;
80279 assert( pParse->pNewTable==0 );
80280 pParse->pNewTable = pTable;
80282 /* If this is the magic sqlite_sequence table used by autoincrement,
80283 ** then record a pointer to this table in the main database structure
80284 ** so that INSERT can find the table easily.
80286 #ifndef SQLITE_OMIT_AUTOINCREMENT
80287 if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
80288 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
80289 pTable->pSchema->pSeqTab = pTable;
80291 #endif
80293 /* Begin generating the code that will insert the table record into
80294 ** the SQLITE_MASTER table. Note in particular that we must go ahead
80295 ** and allocate the record number for the table entry now. Before any
80296 ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
80297 ** indices to be created and the table record must come before the
80298 ** indices. Hence, the record number for the table must be allocated
80299 ** now.
80301 if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
80302 int j1;
80303 int fileFormat;
80304 int reg1, reg2, reg3;
80305 sqlite3BeginWriteOperation(pParse, 0, iDb);
80307 #ifndef SQLITE_OMIT_VIRTUALTABLE
80308 if( isVirtual ){
80309 sqlite3VdbeAddOp0(v, OP_VBegin);
80311 #endif
80313 /* If the file format and encoding in the database have not been set,
80314 ** set them now.
80316 reg1 = pParse->regRowid = ++pParse->nMem;
80317 reg2 = pParse->regRoot = ++pParse->nMem;
80318 reg3 = ++pParse->nMem;
80319 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
80320 sqlite3VdbeUsesBtree(v, iDb);
80321 j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
80322 fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
80323 1 : SQLITE_MAX_FILE_FORMAT;
80324 sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
80325 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
80326 sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
80327 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
80328 sqlite3VdbeJumpHere(v, j1);
80330 /* This just creates a place-holder record in the sqlite_master table.
80331 ** The record created does not contain anything yet. It will be replaced
80332 ** by the real entry in code generated at sqlite3EndTable().
80334 ** The rowid for the new entry is left in register pParse->regRowid.
80335 ** The root page number of the new table is left in reg pParse->regRoot.
80336 ** The rowid and root page number values are needed by the code that
80337 ** sqlite3EndTable will generate.
80339 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
80340 if( isView || isVirtual ){
80341 sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
80342 }else
80343 #endif
80345 sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
80347 sqlite3OpenMasterTable(pParse, iDb);
80348 sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
80349 sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
80350 sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
80351 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
80352 sqlite3VdbeAddOp0(v, OP_Close);
80355 /* Normal (non-error) return. */
80356 return;
80358 /* If an error occurs, we jump here */
80359 begin_table_error:
80360 sqlite3DbFree(db, zName);
80361 return;
80365 ** This macro is used to compare two strings in a case-insensitive manner.
80366 ** It is slightly faster than calling sqlite3StrICmp() directly, but
80367 ** produces larger code.
80369 ** WARNING: This macro is not compatible with the strcmp() family. It
80370 ** returns true if the two strings are equal, otherwise false.
80372 #define STRICMP(x, y) (\
80373 sqlite3UpperToLower[*(unsigned char *)(x)]== \
80374 sqlite3UpperToLower[*(unsigned char *)(y)] \
80375 && sqlite3StrICmp((x)+1,(y)+1)==0 )
80378 ** Add a new column to the table currently being constructed.
80380 ** The parser calls this routine once for each column declaration
80381 ** in a CREATE TABLE statement. sqlite3StartTable() gets called
80382 ** first to get things going. Then this routine is called for each
80383 ** column.
80385 SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
80386 Table *p;
80387 int i;
80388 char *z;
80389 Column *pCol;
80390 sqlite3 *db = pParse->db;
80391 if( (p = pParse->pNewTable)==0 ) return;
80392 #if SQLITE_MAX_COLUMN
80393 if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
80394 sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
80395 return;
80397 #endif
80398 z = sqlite3NameFromToken(db, pName);
80399 if( z==0 ) return;
80400 for(i=0; i<p->nCol; i++){
80401 if( STRICMP(z, p->aCol[i].zName) ){
80402 sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
80403 sqlite3DbFree(db, z);
80404 return;
80407 if( (p->nCol & 0x7)==0 ){
80408 Column *aNew;
80409 aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
80410 if( aNew==0 ){
80411 sqlite3DbFree(db, z);
80412 return;
80414 p->aCol = aNew;
80416 pCol = &p->aCol[p->nCol];
80417 memset(pCol, 0, sizeof(p->aCol[0]));
80418 pCol->zName = z;
80420 /* If there is no type specified, columns have the default affinity
80421 ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
80422 ** be called next to set pCol->affinity correctly.
80424 pCol->affinity = SQLITE_AFF_NONE;
80425 p->nCol++;
80429 ** This routine is called by the parser while in the middle of
80430 ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
80431 ** been seen on a column. This routine sets the notNull flag on
80432 ** the column currently under construction.
80434 SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
80435 Table *p;
80436 p = pParse->pNewTable;
80437 if( p==0 || NEVER(p->nCol<1) ) return;
80438 p->aCol[p->nCol-1].notNull = (u8)onError;
80442 ** Scan the column type name zType (length nType) and return the
80443 ** associated affinity type.
80445 ** This routine does a case-independent search of zType for the
80446 ** substrings in the following table. If one of the substrings is
80447 ** found, the corresponding affinity is returned. If zType contains
80448 ** more than one of the substrings, entries toward the top of
80449 ** the table take priority. For example, if zType is 'BLOBINT',
80450 ** SQLITE_AFF_INTEGER is returned.
80452 ** Substring | Affinity
80453 ** --------------------------------
80454 ** 'INT' | SQLITE_AFF_INTEGER
80455 ** 'CHAR' | SQLITE_AFF_TEXT
80456 ** 'CLOB' | SQLITE_AFF_TEXT
80457 ** 'TEXT' | SQLITE_AFF_TEXT
80458 ** 'BLOB' | SQLITE_AFF_NONE
80459 ** 'REAL' | SQLITE_AFF_REAL
80460 ** 'FLOA' | SQLITE_AFF_REAL
80461 ** 'DOUB' | SQLITE_AFF_REAL
80463 ** If none of the substrings in the above table are found,
80464 ** SQLITE_AFF_NUMERIC is returned.
80466 SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn){
80467 u32 h = 0;
80468 char aff = SQLITE_AFF_NUMERIC;
80470 if( zIn ) while( zIn[0] ){
80471 h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
80472 zIn++;
80473 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
80474 aff = SQLITE_AFF_TEXT;
80475 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
80476 aff = SQLITE_AFF_TEXT;
80477 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
80478 aff = SQLITE_AFF_TEXT;
80479 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
80480 && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
80481 aff = SQLITE_AFF_NONE;
80482 #ifndef SQLITE_OMIT_FLOATING_POINT
80483 }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
80484 && aff==SQLITE_AFF_NUMERIC ){
80485 aff = SQLITE_AFF_REAL;
80486 }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
80487 && aff==SQLITE_AFF_NUMERIC ){
80488 aff = SQLITE_AFF_REAL;
80489 }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
80490 && aff==SQLITE_AFF_NUMERIC ){
80491 aff = SQLITE_AFF_REAL;
80492 #endif
80493 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
80494 aff = SQLITE_AFF_INTEGER;
80495 break;
80499 return aff;
80503 ** This routine is called by the parser while in the middle of
80504 ** parsing a CREATE TABLE statement. The pFirst token is the first
80505 ** token in the sequence of tokens that describe the type of the
80506 ** column currently under construction. pLast is the last token
80507 ** in the sequence. Use this information to construct a string
80508 ** that contains the typename of the column and store that string
80509 ** in zType.
80511 SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
80512 Table *p;
80513 Column *pCol;
80515 p = pParse->pNewTable;
80516 if( p==0 || NEVER(p->nCol<1) ) return;
80517 pCol = &p->aCol[p->nCol-1];
80518 assert( pCol->zType==0 );
80519 pCol->zType = sqlite3NameFromToken(pParse->db, pType);
80520 pCol->affinity = sqlite3AffinityType(pCol->zType);
80524 ** The expression is the default value for the most recently added column
80525 ** of the table currently under construction.
80527 ** Default value expressions must be constant. Raise an exception if this
80528 ** is not the case.
80530 ** This routine is called by the parser while in the middle of
80531 ** parsing a CREATE TABLE statement.
80533 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
80534 Table *p;
80535 Column *pCol;
80536 sqlite3 *db = pParse->db;
80537 p = pParse->pNewTable;
80538 if( p!=0 ){
80539 pCol = &(p->aCol[p->nCol-1]);
80540 if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
80541 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
80542 pCol->zName);
80543 }else{
80544 /* A copy of pExpr is used instead of the original, as pExpr contains
80545 ** tokens that point to volatile memory. The 'span' of the expression
80546 ** is required by pragma table_info.
80548 sqlite3ExprDelete(db, pCol->pDflt);
80549 pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
80550 sqlite3DbFree(db, pCol->zDflt);
80551 pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
80552 (int)(pSpan->zEnd - pSpan->zStart));
80555 sqlite3ExprDelete(db, pSpan->pExpr);
80559 ** Designate the PRIMARY KEY for the table. pList is a list of names
80560 ** of columns that form the primary key. If pList is NULL, then the
80561 ** most recently added column of the table is the primary key.
80563 ** A table can have at most one primary key. If the table already has
80564 ** a primary key (and this is the second primary key) then create an
80565 ** error.
80567 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
80568 ** then we will try to use that column as the rowid. Set the Table.iPKey
80569 ** field of the table under construction to be the index of the
80570 ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
80571 ** no INTEGER PRIMARY KEY.
80573 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
80574 ** index for the key. No index is created for INTEGER PRIMARY KEYs.
80576 SQLITE_PRIVATE void sqlite3AddPrimaryKey(
80577 Parse *pParse, /* Parsing context */
80578 ExprList *pList, /* List of field names to be indexed */
80579 int onError, /* What to do with a uniqueness conflict */
80580 int autoInc, /* True if the AUTOINCREMENT keyword is present */
80581 int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
80583 Table *pTab = pParse->pNewTable;
80584 char *zType = 0;
80585 int iCol = -1, i;
80586 if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
80587 if( pTab->tabFlags & TF_HasPrimaryKey ){
80588 sqlite3ErrorMsg(pParse,
80589 "table \"%s\" has more than one primary key", pTab->zName);
80590 goto primary_key_exit;
80592 pTab->tabFlags |= TF_HasPrimaryKey;
80593 if( pList==0 ){
80594 iCol = pTab->nCol - 1;
80595 pTab->aCol[iCol].isPrimKey = 1;
80596 }else{
80597 for(i=0; i<pList->nExpr; i++){
80598 for(iCol=0; iCol<pTab->nCol; iCol++){
80599 if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
80600 break;
80603 if( iCol<pTab->nCol ){
80604 pTab->aCol[iCol].isPrimKey = 1;
80607 if( pList->nExpr>1 ) iCol = -1;
80609 if( iCol>=0 && iCol<pTab->nCol ){
80610 zType = pTab->aCol[iCol].zType;
80612 if( zType && sqlite3StrICmp(zType, "INTEGER")==0
80613 && sortOrder==SQLITE_SO_ASC ){
80614 pTab->iPKey = iCol;
80615 pTab->keyConf = (u8)onError;
80616 assert( autoInc==0 || autoInc==1 );
80617 pTab->tabFlags |= autoInc*TF_Autoincrement;
80618 }else if( autoInc ){
80619 #ifndef SQLITE_OMIT_AUTOINCREMENT
80620 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
80621 "INTEGER PRIMARY KEY");
80622 #endif
80623 }else{
80624 Index *p;
80625 p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
80626 if( p ){
80627 p->autoIndex = 2;
80629 pList = 0;
80632 primary_key_exit:
80633 sqlite3ExprListDelete(pParse->db, pList);
80634 return;
80638 ** Add a new CHECK constraint to the table currently under construction.
80640 SQLITE_PRIVATE void sqlite3AddCheckConstraint(
80641 Parse *pParse, /* Parsing context */
80642 Expr *pCheckExpr /* The check expression */
80644 sqlite3 *db = pParse->db;
80645 #ifndef SQLITE_OMIT_CHECK
80646 Table *pTab = pParse->pNewTable;
80647 if( pTab && !IN_DECLARE_VTAB ){
80648 pTab->pCheck = sqlite3ExprAnd(db, pTab->pCheck, pCheckExpr);
80649 }else
80650 #endif
80652 sqlite3ExprDelete(db, pCheckExpr);
80657 ** Set the collation function of the most recently parsed table column
80658 ** to the CollSeq given.
80660 SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
80661 Table *p;
80662 int i;
80663 char *zColl; /* Dequoted name of collation sequence */
80664 sqlite3 *db;
80666 if( (p = pParse->pNewTable)==0 ) return;
80667 i = p->nCol-1;
80668 db = pParse->db;
80669 zColl = sqlite3NameFromToken(db, pToken);
80670 if( !zColl ) return;
80672 if( sqlite3LocateCollSeq(pParse, zColl) ){
80673 Index *pIdx;
80674 p->aCol[i].zColl = zColl;
80676 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
80677 ** then an index may have been created on this column before the
80678 ** collation type was added. Correct this if it is the case.
80680 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
80681 assert( pIdx->nColumn==1 );
80682 if( pIdx->aiColumn[0]==i ){
80683 pIdx->azColl[0] = p->aCol[i].zColl;
80686 }else{
80687 sqlite3DbFree(db, zColl);
80692 ** This function returns the collation sequence for database native text
80693 ** encoding identified by the string zName, length nName.
80695 ** If the requested collation sequence is not available, or not available
80696 ** in the database native encoding, the collation factory is invoked to
80697 ** request it. If the collation factory does not supply such a sequence,
80698 ** and the sequence is available in another text encoding, then that is
80699 ** returned instead.
80701 ** If no versions of the requested collations sequence are available, or
80702 ** another error occurs, NULL is returned and an error message written into
80703 ** pParse.
80705 ** This routine is a wrapper around sqlite3FindCollSeq(). This routine
80706 ** invokes the collation factory if the named collation cannot be found
80707 ** and generates an error message.
80709 ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
80711 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
80712 sqlite3 *db = pParse->db;
80713 u8 enc = ENC(db);
80714 u8 initbusy = db->init.busy;
80715 CollSeq *pColl;
80717 pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
80718 if( !initbusy && (!pColl || !pColl->xCmp) ){
80719 pColl = sqlite3GetCollSeq(db, enc, pColl, zName);
80720 if( !pColl ){
80721 sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
80725 return pColl;
80730 ** Generate code that will increment the schema cookie.
80732 ** The schema cookie is used to determine when the schema for the
80733 ** database changes. After each schema change, the cookie value
80734 ** changes. When a process first reads the schema it records the
80735 ** cookie. Thereafter, whenever it goes to access the database,
80736 ** it checks the cookie to make sure the schema has not changed
80737 ** since it was last read.
80739 ** This plan is not completely bullet-proof. It is possible for
80740 ** the schema to change multiple times and for the cookie to be
80741 ** set back to prior value. But schema changes are infrequent
80742 ** and the probability of hitting the same cookie value is only
80743 ** 1 chance in 2^32. So we're safe enough.
80745 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
80746 int r1 = sqlite3GetTempReg(pParse);
80747 sqlite3 *db = pParse->db;
80748 Vdbe *v = pParse->pVdbe;
80749 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
80750 sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
80751 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
80752 sqlite3ReleaseTempReg(pParse, r1);
80756 ** Measure the number of characters needed to output the given
80757 ** identifier. The number returned includes any quotes used
80758 ** but does not include the null terminator.
80760 ** The estimate is conservative. It might be larger that what is
80761 ** really needed.
80763 static int identLength(const char *z){
80764 int n;
80765 for(n=0; *z; n++, z++){
80766 if( *z=='"' ){ n++; }
80768 return n + 2;
80772 ** The first parameter is a pointer to an output buffer. The second
80773 ** parameter is a pointer to an integer that contains the offset at
80774 ** which to write into the output buffer. This function copies the
80775 ** nul-terminated string pointed to by the third parameter, zSignedIdent,
80776 ** to the specified offset in the buffer and updates *pIdx to refer
80777 ** to the first byte after the last byte written before returning.
80779 ** If the string zSignedIdent consists entirely of alpha-numeric
80780 ** characters, does not begin with a digit and is not an SQL keyword,
80781 ** then it is copied to the output buffer exactly as it is. Otherwise,
80782 ** it is quoted using double-quotes.
80784 static void identPut(char *z, int *pIdx, char *zSignedIdent){
80785 unsigned char *zIdent = (unsigned char*)zSignedIdent;
80786 int i, j, needQuote;
80787 i = *pIdx;
80789 for(j=0; zIdent[j]; j++){
80790 if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
80792 needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;
80793 if( !needQuote ){
80794 needQuote = zIdent[j];
80797 if( needQuote ) z[i++] = '"';
80798 for(j=0; zIdent[j]; j++){
80799 z[i++] = zIdent[j];
80800 if( zIdent[j]=='"' ) z[i++] = '"';
80802 if( needQuote ) z[i++] = '"';
80803 z[i] = 0;
80804 *pIdx = i;
80808 ** Generate a CREATE TABLE statement appropriate for the given
80809 ** table. Memory to hold the text of the statement is obtained
80810 ** from sqliteMalloc() and must be freed by the calling function.
80812 static char *createTableStmt(sqlite3 *db, Table *p){
80813 int i, k, n;
80814 char *zStmt;
80815 char *zSep, *zSep2, *zEnd;
80816 Column *pCol;
80817 n = 0;
80818 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
80819 n += identLength(pCol->zName) + 5;
80821 n += identLength(p->zName);
80822 if( n<50 ){
80823 zSep = "";
80824 zSep2 = ",";
80825 zEnd = ")";
80826 }else{
80827 zSep = "\n ";
80828 zSep2 = ",\n ";
80829 zEnd = "\n)";
80831 n += 35 + 6*p->nCol;
80832 zStmt = sqlite3DbMallocRaw(0, n);
80833 if( zStmt==0 ){
80834 db->mallocFailed = 1;
80835 return 0;
80837 sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
80838 k = sqlite3Strlen30(zStmt);
80839 identPut(zStmt, &k, p->zName);
80840 zStmt[k++] = '(';
80841 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
80842 static const char * const azType[] = {
80843 /* SQLITE_AFF_TEXT */ " TEXT",
80844 /* SQLITE_AFF_NONE */ "",
80845 /* SQLITE_AFF_NUMERIC */ " NUM",
80846 /* SQLITE_AFF_INTEGER */ " INT",
80847 /* SQLITE_AFF_REAL */ " REAL"
80849 int len;
80850 const char *zType;
80852 sqlite3_snprintf(n-k, &zStmt[k], zSep);
80853 k += sqlite3Strlen30(&zStmt[k]);
80854 zSep = zSep2;
80855 identPut(zStmt, &k, pCol->zName);
80856 assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
80857 assert( pCol->affinity-SQLITE_AFF_TEXT < ArraySize(azType) );
80858 testcase( pCol->affinity==SQLITE_AFF_TEXT );
80859 testcase( pCol->affinity==SQLITE_AFF_NONE );
80860 testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
80861 testcase( pCol->affinity==SQLITE_AFF_INTEGER );
80862 testcase( pCol->affinity==SQLITE_AFF_REAL );
80864 zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
80865 len = sqlite3Strlen30(zType);
80866 assert( pCol->affinity==SQLITE_AFF_NONE
80867 || pCol->affinity==sqlite3AffinityType(zType) );
80868 memcpy(&zStmt[k], zType, len);
80869 k += len;
80870 assert( k<=n );
80872 sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
80873 return zStmt;
80877 ** This routine is called to report the final ")" that terminates
80878 ** a CREATE TABLE statement.
80880 ** The table structure that other action routines have been building
80881 ** is added to the internal hash tables, assuming no errors have
80882 ** occurred.
80884 ** An entry for the table is made in the master table on disk, unless
80885 ** this is a temporary table or db->init.busy==1. When db->init.busy==1
80886 ** it means we are reading the sqlite_master table because we just
80887 ** connected to the database or because the sqlite_master table has
80888 ** recently changed, so the entry for this table already exists in
80889 ** the sqlite_master table. We do not want to create it again.
80891 ** If the pSelect argument is not NULL, it means that this routine
80892 ** was called to create a table generated from a
80893 ** "CREATE TABLE ... AS SELECT ..." statement. The column names of
80894 ** the new table will match the result set of the SELECT.
80896 SQLITE_PRIVATE void sqlite3EndTable(
80897 Parse *pParse, /* Parse context */
80898 Token *pCons, /* The ',' token after the last column defn. */
80899 Token *pEnd, /* The final ')' token in the CREATE TABLE */
80900 Select *pSelect /* Select from a "CREATE ... AS SELECT" */
80902 Table *p;
80903 sqlite3 *db = pParse->db;
80904 int iDb;
80906 if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
80907 return;
80909 p = pParse->pNewTable;
80910 if( p==0 ) return;
80912 assert( !db->init.busy || !pSelect );
80914 iDb = sqlite3SchemaToIndex(db, p->pSchema);
80916 #ifndef SQLITE_OMIT_CHECK
80917 /* Resolve names in all CHECK constraint expressions.
80919 if( p->pCheck ){
80920 SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
80921 NameContext sNC; /* Name context for pParse->pNewTable */
80923 memset(&sNC, 0, sizeof(sNC));
80924 memset(&sSrc, 0, sizeof(sSrc));
80925 sSrc.nSrc = 1;
80926 sSrc.a[0].zName = p->zName;
80927 sSrc.a[0].pTab = p;
80928 sSrc.a[0].iCursor = -1;
80929 sNC.pParse = pParse;
80930 sNC.pSrcList = &sSrc;
80931 sNC.isCheck = 1;
80932 if( sqlite3ResolveExprNames(&sNC, p->pCheck) ){
80933 return;
80936 #endif /* !defined(SQLITE_OMIT_CHECK) */
80938 /* If the db->init.busy is 1 it means we are reading the SQL off the
80939 ** "sqlite_master" or "sqlite_temp_master" table on the disk.
80940 ** So do not write to the disk again. Extract the root page number
80941 ** for the table from the db->init.newTnum field. (The page number
80942 ** should have been put there by the sqliteOpenCb routine.)
80944 if( db->init.busy ){
80945 p->tnum = db->init.newTnum;
80948 /* If not initializing, then create a record for the new table
80949 ** in the SQLITE_MASTER table of the database.
80951 ** If this is a TEMPORARY table, write the entry into the auxiliary
80952 ** file instead of into the main database file.
80954 if( !db->init.busy ){
80955 int n;
80956 Vdbe *v;
80957 char *zType; /* "view" or "table" */
80958 char *zType2; /* "VIEW" or "TABLE" */
80959 char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
80961 v = sqlite3GetVdbe(pParse);
80962 if( NEVER(v==0) ) return;
80964 sqlite3VdbeAddOp1(v, OP_Close, 0);
80967 ** Initialize zType for the new view or table.
80969 if( p->pSelect==0 ){
80970 /* A regular table */
80971 zType = "table";
80972 zType2 = "TABLE";
80973 #ifndef SQLITE_OMIT_VIEW
80974 }else{
80975 /* A view */
80976 zType = "view";
80977 zType2 = "VIEW";
80978 #endif
80981 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
80982 ** statement to populate the new table. The root-page number for the
80983 ** new table is in register pParse->regRoot.
80985 ** Once the SELECT has been coded by sqlite3Select(), it is in a
80986 ** suitable state to query for the column names and types to be used
80987 ** by the new table.
80989 ** A shared-cache write-lock is not required to write to the new table,
80990 ** as a schema-lock must have already been obtained to create it. Since
80991 ** a schema-lock excludes all other database users, the write-lock would
80992 ** be redundant.
80994 if( pSelect ){
80995 SelectDest dest;
80996 Table *pSelTab;
80998 assert(pParse->nTab==1);
80999 sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
81000 sqlite3VdbeChangeP5(v, 1);
81001 pParse->nTab = 2;
81002 sqlite3SelectDestInit(&dest, SRT_Table, 1);
81003 sqlite3Select(pParse, pSelect, &dest);
81004 sqlite3VdbeAddOp1(v, OP_Close, 1);
81005 if( pParse->nErr==0 ){
81006 pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
81007 if( pSelTab==0 ) return;
81008 assert( p->aCol==0 );
81009 p->nCol = pSelTab->nCol;
81010 p->aCol = pSelTab->aCol;
81011 pSelTab->nCol = 0;
81012 pSelTab->aCol = 0;
81013 sqlite3DeleteTable(db, pSelTab);
81017 /* Compute the complete text of the CREATE statement */
81018 if( pSelect ){
81019 zStmt = createTableStmt(db, p);
81020 }else{
81021 n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
81022 zStmt = sqlite3MPrintf(db,
81023 "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
81027 /* A slot for the record has already been allocated in the
81028 ** SQLITE_MASTER table. We just need to update that slot with all
81029 ** the information we've collected.
81031 sqlite3NestedParse(pParse,
81032 "UPDATE %Q.%s "
81033 "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
81034 "WHERE rowid=#%d",
81035 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
81036 zType,
81037 p->zName,
81038 p->zName,
81039 pParse->regRoot,
81040 zStmt,
81041 pParse->regRowid
81043 sqlite3DbFree(db, zStmt);
81044 sqlite3ChangeCookie(pParse, iDb);
81046 #ifndef SQLITE_OMIT_AUTOINCREMENT
81047 /* Check to see if we need to create an sqlite_sequence table for
81048 ** keeping track of autoincrement keys.
81050 if( p->tabFlags & TF_Autoincrement ){
81051 Db *pDb = &db->aDb[iDb];
81052 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
81053 if( pDb->pSchema->pSeqTab==0 ){
81054 sqlite3NestedParse(pParse,
81055 "CREATE TABLE %Q.sqlite_sequence(name,seq)",
81056 pDb->zName
81060 #endif
81062 /* Reparse everything to update our internal data structures */
81063 sqlite3VdbeAddParseSchemaOp(v, iDb,
81064 sqlite3MPrintf(db, "tbl_name='%q'", p->zName));
81068 /* Add the table to the in-memory representation of the database.
81070 if( db->init.busy ){
81071 Table *pOld;
81072 Schema *pSchema = p->pSchema;
81073 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
81074 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
81075 sqlite3Strlen30(p->zName),p);
81076 if( pOld ){
81077 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
81078 db->mallocFailed = 1;
81079 return;
81081 pParse->pNewTable = 0;
81082 db->nTable++;
81083 db->flags |= SQLITE_InternChanges;
81085 #ifndef SQLITE_OMIT_ALTERTABLE
81086 if( !p->pSelect ){
81087 const char *zName = (const char *)pParse->sNameToken.z;
81088 int nName;
81089 assert( !pSelect && pCons && pEnd );
81090 if( pCons->z==0 ){
81091 pCons = pEnd;
81093 nName = (int)((const char *)pCons->z - zName);
81094 p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
81096 #endif
81100 #ifndef SQLITE_OMIT_VIEW
81102 ** The parser calls this routine in order to create a new VIEW
81104 SQLITE_PRIVATE void sqlite3CreateView(
81105 Parse *pParse, /* The parsing context */
81106 Token *pBegin, /* The CREATE token that begins the statement */
81107 Token *pName1, /* The token that holds the name of the view */
81108 Token *pName2, /* The token that holds the name of the view */
81109 Select *pSelect, /* A SELECT statement that will become the new view */
81110 int isTemp, /* TRUE for a TEMPORARY view */
81111 int noErr /* Suppress error messages if VIEW already exists */
81113 Table *p;
81114 int n;
81115 const char *z;
81116 Token sEnd;
81117 DbFixer sFix;
81118 Token *pName = 0;
81119 int iDb;
81120 sqlite3 *db = pParse->db;
81122 if( pParse->nVar>0 ){
81123 sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
81124 sqlite3SelectDelete(db, pSelect);
81125 return;
81127 sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
81128 p = pParse->pNewTable;
81129 if( p==0 || pParse->nErr ){
81130 sqlite3SelectDelete(db, pSelect);
81131 return;
81133 sqlite3TwoPartName(pParse, pName1, pName2, &pName);
81134 iDb = sqlite3SchemaToIndex(db, p->pSchema);
81135 if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
81136 && sqlite3FixSelect(&sFix, pSelect)
81138 sqlite3SelectDelete(db, pSelect);
81139 return;
81142 /* Make a copy of the entire SELECT statement that defines the view.
81143 ** This will force all the Expr.token.z values to be dynamically
81144 ** allocated rather than point to the input string - which means that
81145 ** they will persist after the current sqlite3_exec() call returns.
81147 p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
81148 sqlite3SelectDelete(db, pSelect);
81149 if( db->mallocFailed ){
81150 return;
81152 if( !db->init.busy ){
81153 sqlite3ViewGetColumnNames(pParse, p);
81156 /* Locate the end of the CREATE VIEW statement. Make sEnd point to
81157 ** the end.
81159 sEnd = pParse->sLastToken;
81160 if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
81161 sEnd.z += sEnd.n;
81163 sEnd.n = 0;
81164 n = (int)(sEnd.z - pBegin->z);
81165 z = pBegin->z;
81166 while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
81167 sEnd.z = &z[n-1];
81168 sEnd.n = 1;
81170 /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
81171 sqlite3EndTable(pParse, 0, &sEnd, 0);
81172 return;
81174 #endif /* SQLITE_OMIT_VIEW */
81176 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
81178 ** The Table structure pTable is really a VIEW. Fill in the names of
81179 ** the columns of the view in the pTable structure. Return the number
81180 ** of errors. If an error is seen leave an error message in pParse->zErrMsg.
81182 SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
81183 Table *pSelTab; /* A fake table from which we get the result set */
81184 Select *pSel; /* Copy of the SELECT that implements the view */
81185 int nErr = 0; /* Number of errors encountered */
81186 int n; /* Temporarily holds the number of cursors assigned */
81187 sqlite3 *db = pParse->db; /* Database connection for malloc errors */
81188 int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
81190 assert( pTable );
81192 #ifndef SQLITE_OMIT_VIRTUALTABLE
81193 if( sqlite3VtabCallConnect(pParse, pTable) ){
81194 return SQLITE_ERROR;
81196 if( IsVirtual(pTable) ) return 0;
81197 #endif
81199 #ifndef SQLITE_OMIT_VIEW
81200 /* A positive nCol means the columns names for this view are
81201 ** already known.
81203 if( pTable->nCol>0 ) return 0;
81205 /* A negative nCol is a special marker meaning that we are currently
81206 ** trying to compute the column names. If we enter this routine with
81207 ** a negative nCol, it means two or more views form a loop, like this:
81209 ** CREATE VIEW one AS SELECT * FROM two;
81210 ** CREATE VIEW two AS SELECT * FROM one;
81212 ** Actually, the error above is now caught prior to reaching this point.
81213 ** But the following test is still important as it does come up
81214 ** in the following:
81216 ** CREATE TABLE main.ex1(a);
81217 ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
81218 ** SELECT * FROM temp.ex1;
81220 if( pTable->nCol<0 ){
81221 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
81222 return 1;
81224 assert( pTable->nCol>=0 );
81226 /* If we get this far, it means we need to compute the table names.
81227 ** Note that the call to sqlite3ResultSetOfSelect() will expand any
81228 ** "*" elements in the results set of the view and will assign cursors
81229 ** to the elements of the FROM clause. But we do not want these changes
81230 ** to be permanent. So the computation is done on a copy of the SELECT
81231 ** statement that defines the view.
81233 assert( pTable->pSelect );
81234 pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
81235 if( pSel ){
81236 u8 enableLookaside = db->lookaside.bEnabled;
81237 n = pParse->nTab;
81238 sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
81239 pTable->nCol = -1;
81240 db->lookaside.bEnabled = 0;
81241 #ifndef SQLITE_OMIT_AUTHORIZATION
81242 xAuth = db->xAuth;
81243 db->xAuth = 0;
81244 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
81245 db->xAuth = xAuth;
81246 #else
81247 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
81248 #endif
81249 db->lookaside.bEnabled = enableLookaside;
81250 pParse->nTab = n;
81251 if( pSelTab ){
81252 assert( pTable->aCol==0 );
81253 pTable->nCol = pSelTab->nCol;
81254 pTable->aCol = pSelTab->aCol;
81255 pSelTab->nCol = 0;
81256 pSelTab->aCol = 0;
81257 sqlite3DeleteTable(db, pSelTab);
81258 assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
81259 pTable->pSchema->flags |= DB_UnresetViews;
81260 }else{
81261 pTable->nCol = 0;
81262 nErr++;
81264 sqlite3SelectDelete(db, pSel);
81265 } else {
81266 nErr++;
81268 #endif /* SQLITE_OMIT_VIEW */
81269 return nErr;
81271 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
81273 #ifndef SQLITE_OMIT_VIEW
81275 ** Clear the column names from every VIEW in database idx.
81277 static void sqliteViewResetAll(sqlite3 *db, int idx){
81278 HashElem *i;
81279 assert( sqlite3SchemaMutexHeld(db, idx, 0) );
81280 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
81281 for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
81282 Table *pTab = sqliteHashData(i);
81283 if( pTab->pSelect ){
81284 sqliteDeleteColumnNames(db, pTab);
81285 pTab->aCol = 0;
81286 pTab->nCol = 0;
81289 DbClearProperty(db, idx, DB_UnresetViews);
81291 #else
81292 # define sqliteViewResetAll(A,B)
81293 #endif /* SQLITE_OMIT_VIEW */
81296 ** This function is called by the VDBE to adjust the internal schema
81297 ** used by SQLite when the btree layer moves a table root page. The
81298 ** root-page of a table or index in database iDb has changed from iFrom
81299 ** to iTo.
81301 ** Ticket #1728: The symbol table might still contain information
81302 ** on tables and/or indices that are the process of being deleted.
81303 ** If you are unlucky, one of those deleted indices or tables might
81304 ** have the same rootpage number as the real table or index that is
81305 ** being moved. So we cannot stop searching after the first match
81306 ** because the first match might be for one of the deleted indices
81307 ** or tables and not the table/index that is actually being moved.
81308 ** We must continue looping until all tables and indices with
81309 ** rootpage==iFrom have been converted to have a rootpage of iTo
81310 ** in order to be certain that we got the right one.
81312 #ifndef SQLITE_OMIT_AUTOVACUUM
81313 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
81314 HashElem *pElem;
81315 Hash *pHash;
81316 Db *pDb;
81318 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
81319 pDb = &db->aDb[iDb];
81320 pHash = &pDb->pSchema->tblHash;
81321 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
81322 Table *pTab = sqliteHashData(pElem);
81323 if( pTab->tnum==iFrom ){
81324 pTab->tnum = iTo;
81327 pHash = &pDb->pSchema->idxHash;
81328 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
81329 Index *pIdx = sqliteHashData(pElem);
81330 if( pIdx->tnum==iFrom ){
81331 pIdx->tnum = iTo;
81335 #endif
81338 ** Write code to erase the table with root-page iTable from database iDb.
81339 ** Also write code to modify the sqlite_master table and internal schema
81340 ** if a root-page of another table is moved by the btree-layer whilst
81341 ** erasing iTable (this can happen with an auto-vacuum database).
81343 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
81344 Vdbe *v = sqlite3GetVdbe(pParse);
81345 int r1 = sqlite3GetTempReg(pParse);
81346 sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
81347 sqlite3MayAbort(pParse);
81348 #ifndef SQLITE_OMIT_AUTOVACUUM
81349 /* OP_Destroy stores an in integer r1. If this integer
81350 ** is non-zero, then it is the root page number of a table moved to
81351 ** location iTable. The following code modifies the sqlite_master table to
81352 ** reflect this.
81354 ** The "#NNN" in the SQL is a special constant that means whatever value
81355 ** is in register NNN. See grammar rules associated with the TK_REGISTER
81356 ** token for additional information.
81358 sqlite3NestedParse(pParse,
81359 "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
81360 pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
81361 #endif
81362 sqlite3ReleaseTempReg(pParse, r1);
81366 ** Write VDBE code to erase table pTab and all associated indices on disk.
81367 ** Code to update the sqlite_master tables and internal schema definitions
81368 ** in case a root-page belonging to another table is moved by the btree layer
81369 ** is also added (this can happen with an auto-vacuum database).
81371 static void destroyTable(Parse *pParse, Table *pTab){
81372 #ifdef SQLITE_OMIT_AUTOVACUUM
81373 Index *pIdx;
81374 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
81375 destroyRootPage(pParse, pTab->tnum, iDb);
81376 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
81377 destroyRootPage(pParse, pIdx->tnum, iDb);
81379 #else
81380 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
81381 ** is not defined), then it is important to call OP_Destroy on the
81382 ** table and index root-pages in order, starting with the numerically
81383 ** largest root-page number. This guarantees that none of the root-pages
81384 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
81385 ** following were coded:
81387 ** OP_Destroy 4 0
81388 ** ...
81389 ** OP_Destroy 5 0
81391 ** and root page 5 happened to be the largest root-page number in the
81392 ** database, then root page 5 would be moved to page 4 by the
81393 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
81394 ** a free-list page.
81396 int iTab = pTab->tnum;
81397 int iDestroyed = 0;
81399 while( 1 ){
81400 Index *pIdx;
81401 int iLargest = 0;
81403 if( iDestroyed==0 || iTab<iDestroyed ){
81404 iLargest = iTab;
81406 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
81407 int iIdx = pIdx->tnum;
81408 assert( pIdx->pSchema==pTab->pSchema );
81409 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
81410 iLargest = iIdx;
81413 if( iLargest==0 ){
81414 return;
81415 }else{
81416 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
81417 destroyRootPage(pParse, iLargest, iDb);
81418 iDestroyed = iLargest;
81421 #endif
81425 ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
81426 ** after a DROP INDEX or DROP TABLE command.
81428 static void sqlite3ClearStatTables(
81429 Parse *pParse, /* The parsing context */
81430 int iDb, /* The database number */
81431 const char *zType, /* "idx" or "tbl" */
81432 const char *zName /* Name of index or table */
81434 int i;
81435 const char *zDbName = pParse->db->aDb[iDb].zName;
81436 for(i=1; i<=3; i++){
81437 char zTab[24];
81438 sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
81439 if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
81440 sqlite3NestedParse(pParse,
81441 "DELETE FROM %Q.%s WHERE %s=%Q",
81442 zDbName, zTab, zType, zName
81449 ** Generate code to drop a table.
81451 SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
81452 Vdbe *v;
81453 sqlite3 *db = pParse->db;
81454 Trigger *pTrigger;
81455 Db *pDb = &db->aDb[iDb];
81457 v = sqlite3GetVdbe(pParse);
81458 assert( v!=0 );
81459 sqlite3BeginWriteOperation(pParse, 1, iDb);
81461 #ifndef SQLITE_OMIT_VIRTUALTABLE
81462 if( IsVirtual(pTab) ){
81463 sqlite3VdbeAddOp0(v, OP_VBegin);
81465 #endif
81467 /* Drop all triggers associated with the table being dropped. Code
81468 ** is generated to remove entries from sqlite_master and/or
81469 ** sqlite_temp_master if required.
81471 pTrigger = sqlite3TriggerList(pParse, pTab);
81472 while( pTrigger ){
81473 assert( pTrigger->pSchema==pTab->pSchema ||
81474 pTrigger->pSchema==db->aDb[1].pSchema );
81475 sqlite3DropTriggerPtr(pParse, pTrigger);
81476 pTrigger = pTrigger->pNext;
81479 #ifndef SQLITE_OMIT_AUTOINCREMENT
81480 /* Remove any entries of the sqlite_sequence table associated with
81481 ** the table being dropped. This is done before the table is dropped
81482 ** at the btree level, in case the sqlite_sequence table needs to
81483 ** move as a result of the drop (can happen in auto-vacuum mode).
81485 if( pTab->tabFlags & TF_Autoincrement ){
81486 sqlite3NestedParse(pParse,
81487 "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
81488 pDb->zName, pTab->zName
81491 #endif
81493 /* Drop all SQLITE_MASTER table and index entries that refer to the
81494 ** table. The program name loops through the master table and deletes
81495 ** every row that refers to a table of the same name as the one being
81496 ** dropped. Triggers are handled seperately because a trigger can be
81497 ** created in the temp database that refers to a table in another
81498 ** database.
81500 sqlite3NestedParse(pParse,
81501 "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
81502 pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
81503 if( !isView && !IsVirtual(pTab) ){
81504 destroyTable(pParse, pTab);
81507 /* Remove the table entry from SQLite's internal schema and modify
81508 ** the schema cookie.
81510 if( IsVirtual(pTab) ){
81511 sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
81513 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
81514 sqlite3ChangeCookie(pParse, iDb);
81515 sqliteViewResetAll(db, iDb);
81519 ** This routine is called to do the work of a DROP TABLE statement.
81520 ** pName is the name of the table to be dropped.
81522 SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
81523 Table *pTab;
81524 Vdbe *v;
81525 sqlite3 *db = pParse->db;
81526 int iDb;
81528 if( db->mallocFailed ){
81529 goto exit_drop_table;
81531 assert( pParse->nErr==0 );
81532 assert( pName->nSrc==1 );
81533 if( noErr ) db->suppressErr++;
81534 pTab = sqlite3LocateTable(pParse, isView,
81535 pName->a[0].zName, pName->a[0].zDatabase);
81536 if( noErr ) db->suppressErr--;
81538 if( pTab==0 ){
81539 if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
81540 goto exit_drop_table;
81542 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
81543 assert( iDb>=0 && iDb<db->nDb );
81545 /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
81546 ** it is initialized.
81548 if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
81549 goto exit_drop_table;
81551 #ifndef SQLITE_OMIT_AUTHORIZATION
81553 int code;
81554 const char *zTab = SCHEMA_TABLE(iDb);
81555 const char *zDb = db->aDb[iDb].zName;
81556 const char *zArg2 = 0;
81557 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
81558 goto exit_drop_table;
81560 if( isView ){
81561 if( !OMIT_TEMPDB && iDb==1 ){
81562 code = SQLITE_DROP_TEMP_VIEW;
81563 }else{
81564 code = SQLITE_DROP_VIEW;
81566 #ifndef SQLITE_OMIT_VIRTUALTABLE
81567 }else if( IsVirtual(pTab) ){
81568 code = SQLITE_DROP_VTABLE;
81569 zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
81570 #endif
81571 }else{
81572 if( !OMIT_TEMPDB && iDb==1 ){
81573 code = SQLITE_DROP_TEMP_TABLE;
81574 }else{
81575 code = SQLITE_DROP_TABLE;
81578 if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
81579 goto exit_drop_table;
81581 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
81582 goto exit_drop_table;
81585 #endif
81586 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
81587 && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
81588 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
81589 goto exit_drop_table;
81592 #ifndef SQLITE_OMIT_VIEW
81593 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
81594 ** on a table.
81596 if( isView && pTab->pSelect==0 ){
81597 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
81598 goto exit_drop_table;
81600 if( !isView && pTab->pSelect ){
81601 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
81602 goto exit_drop_table;
81604 #endif
81606 /* Generate code to remove the table from the master table
81607 ** on disk.
81609 v = sqlite3GetVdbe(pParse);
81610 if( v ){
81611 sqlite3BeginWriteOperation(pParse, 1, iDb);
81612 sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
81613 sqlite3FkDropTable(pParse, pName, pTab);
81614 sqlite3CodeDropTable(pParse, pTab, iDb, isView);
81617 exit_drop_table:
81618 sqlite3SrcListDelete(db, pName);
81622 ** This routine is called to create a new foreign key on the table
81623 ** currently under construction. pFromCol determines which columns
81624 ** in the current table point to the foreign key. If pFromCol==0 then
81625 ** connect the key to the last column inserted. pTo is the name of
81626 ** the table referred to. pToCol is a list of tables in the other
81627 ** pTo table that the foreign key points to. flags contains all
81628 ** information about the conflict resolution algorithms specified
81629 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
81631 ** An FKey structure is created and added to the table currently
81632 ** under construction in the pParse->pNewTable field.
81634 ** The foreign key is set for IMMEDIATE processing. A subsequent call
81635 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
81637 SQLITE_PRIVATE void sqlite3CreateForeignKey(
81638 Parse *pParse, /* Parsing context */
81639 ExprList *pFromCol, /* Columns in this table that point to other table */
81640 Token *pTo, /* Name of the other table */
81641 ExprList *pToCol, /* Columns in the other table */
81642 int flags /* Conflict resolution algorithms. */
81644 sqlite3 *db = pParse->db;
81645 #ifndef SQLITE_OMIT_FOREIGN_KEY
81646 FKey *pFKey = 0;
81647 FKey *pNextTo;
81648 Table *p = pParse->pNewTable;
81649 int nByte;
81650 int i;
81651 int nCol;
81652 char *z;
81654 assert( pTo!=0 );
81655 if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
81656 if( pFromCol==0 ){
81657 int iCol = p->nCol-1;
81658 if( NEVER(iCol<0) ) goto fk_end;
81659 if( pToCol && pToCol->nExpr!=1 ){
81660 sqlite3ErrorMsg(pParse, "foreign key on %s"
81661 " should reference only one column of table %T",
81662 p->aCol[iCol].zName, pTo);
81663 goto fk_end;
81665 nCol = 1;
81666 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
81667 sqlite3ErrorMsg(pParse,
81668 "number of columns in foreign key does not match the number of "
81669 "columns in the referenced table");
81670 goto fk_end;
81671 }else{
81672 nCol = pFromCol->nExpr;
81674 nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
81675 if( pToCol ){
81676 for(i=0; i<pToCol->nExpr; i++){
81677 nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
81680 pFKey = sqlite3DbMallocZero(db, nByte );
81681 if( pFKey==0 ){
81682 goto fk_end;
81684 pFKey->pFrom = p;
81685 pFKey->pNextFrom = p->pFKey;
81686 z = (char*)&pFKey->aCol[nCol];
81687 pFKey->zTo = z;
81688 memcpy(z, pTo->z, pTo->n);
81689 z[pTo->n] = 0;
81690 sqlite3Dequote(z);
81691 z += pTo->n+1;
81692 pFKey->nCol = nCol;
81693 if( pFromCol==0 ){
81694 pFKey->aCol[0].iFrom = p->nCol-1;
81695 }else{
81696 for(i=0; i<nCol; i++){
81697 int j;
81698 for(j=0; j<p->nCol; j++){
81699 if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
81700 pFKey->aCol[i].iFrom = j;
81701 break;
81704 if( j>=p->nCol ){
81705 sqlite3ErrorMsg(pParse,
81706 "unknown column \"%s\" in foreign key definition",
81707 pFromCol->a[i].zName);
81708 goto fk_end;
81712 if( pToCol ){
81713 for(i=0; i<nCol; i++){
81714 int n = sqlite3Strlen30(pToCol->a[i].zName);
81715 pFKey->aCol[i].zCol = z;
81716 memcpy(z, pToCol->a[i].zName, n);
81717 z[n] = 0;
81718 z += n+1;
81721 pFKey->isDeferred = 0;
81722 pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
81723 pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
81725 assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
81726 pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
81727 pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
81729 if( pNextTo==pFKey ){
81730 db->mallocFailed = 1;
81731 goto fk_end;
81733 if( pNextTo ){
81734 assert( pNextTo->pPrevTo==0 );
81735 pFKey->pNextTo = pNextTo;
81736 pNextTo->pPrevTo = pFKey;
81739 /* Link the foreign key to the table as the last step.
81741 p->pFKey = pFKey;
81742 pFKey = 0;
81744 fk_end:
81745 sqlite3DbFree(db, pFKey);
81746 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
81747 sqlite3ExprListDelete(db, pFromCol);
81748 sqlite3ExprListDelete(db, pToCol);
81752 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
81753 ** clause is seen as part of a foreign key definition. The isDeferred
81754 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
81755 ** The behavior of the most recently created foreign key is adjusted
81756 ** accordingly.
81758 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
81759 #ifndef SQLITE_OMIT_FOREIGN_KEY
81760 Table *pTab;
81761 FKey *pFKey;
81762 if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
81763 assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
81764 pFKey->isDeferred = (u8)isDeferred;
81765 #endif
81769 ** Generate code that will erase and refill index *pIdx. This is
81770 ** used to initialize a newly created index or to recompute the
81771 ** content of an index in response to a REINDEX command.
81773 ** if memRootPage is not negative, it means that the index is newly
81774 ** created. The register specified by memRootPage contains the
81775 ** root page number of the index. If memRootPage is negative, then
81776 ** the index already exists and must be cleared before being refilled and
81777 ** the root page number of the index is taken from pIndex->tnum.
81779 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
81780 Table *pTab = pIndex->pTable; /* The table that is indexed */
81781 int iTab = pParse->nTab++; /* Btree cursor used for pTab */
81782 int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
81783 int iSorter; /* Cursor opened by OpenSorter (if in use) */
81784 int addr1; /* Address of top of loop */
81785 int addr2; /* Address to jump to for next iteration */
81786 int tnum; /* Root page of index */
81787 Vdbe *v; /* Generate code into this virtual machine */
81788 KeyInfo *pKey; /* KeyInfo for index */
81789 #ifdef SQLITE_OMIT_MERGE_SORT
81790 int regIdxKey; /* Registers containing the index key */
81791 #endif
81792 int regRecord; /* Register holding assemblied index record */
81793 sqlite3 *db = pParse->db; /* The database connection */
81794 int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
81796 #ifndef SQLITE_OMIT_AUTHORIZATION
81797 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
81798 db->aDb[iDb].zName ) ){
81799 return;
81801 #endif
81803 /* Require a write-lock on the table to perform this operation */
81804 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
81806 v = sqlite3GetVdbe(pParse);
81807 if( v==0 ) return;
81808 if( memRootPage>=0 ){
81809 tnum = memRootPage;
81810 }else{
81811 tnum = pIndex->tnum;
81812 sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
81814 pKey = sqlite3IndexKeyinfo(pParse, pIndex);
81815 sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
81816 (char *)pKey, P4_KEYINFO_HANDOFF);
81817 if( memRootPage>=0 ){
81818 sqlite3VdbeChangeP5(v, 1);
81821 #ifndef SQLITE_OMIT_MERGE_SORT
81822 /* Open the sorter cursor if we are to use one. */
81823 iSorter = pParse->nTab++;
81824 sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, 0, (char*)pKey, P4_KEYINFO);
81825 #else
81826 iSorter = iTab;
81827 #endif
81829 /* Open the table. Loop through all rows of the table, inserting index
81830 ** records into the sorter. */
81831 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
81832 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
81833 regRecord = sqlite3GetTempReg(pParse);
81835 #ifndef SQLITE_OMIT_MERGE_SORT
81836 sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
81837 sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
81838 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
81839 sqlite3VdbeJumpHere(v, addr1);
81840 addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0);
81841 if( pIndex->onError!=OE_None ){
81842 int j2 = sqlite3VdbeCurrentAddr(v) + 3;
81843 sqlite3VdbeAddOp2(v, OP_Goto, 0, j2);
81844 addr2 = sqlite3VdbeCurrentAddr(v);
81845 sqlite3VdbeAddOp3(v, OP_SorterCompare, iSorter, j2, regRecord);
81846 sqlite3HaltConstraint(
81847 pParse, OE_Abort, "indexed columns are not unique", P4_STATIC
81849 }else{
81850 addr2 = sqlite3VdbeCurrentAddr(v);
81852 sqlite3VdbeAddOp2(v, OP_SorterData, iSorter, regRecord);
81853 sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 1);
81854 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
81855 #else
81856 regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
81857 addr2 = addr1 + 1;
81858 if( pIndex->onError!=OE_None ){
81859 const int regRowid = regIdxKey + pIndex->nColumn;
81860 const int j2 = sqlite3VdbeCurrentAddr(v) + 2;
81861 void * const pRegKey = SQLITE_INT_TO_PTR(regIdxKey);
81863 /* The registers accessed by the OP_IsUnique opcode were allocated
81864 ** using sqlite3GetTempRange() inside of the sqlite3GenerateIndexKey()
81865 ** call above. Just before that function was freed they were released
81866 ** (made available to the compiler for reuse) using
81867 ** sqlite3ReleaseTempRange(). So in some ways having the OP_IsUnique
81868 ** opcode use the values stored within seems dangerous. However, since
81869 ** we can be sure that no other temp registers have been allocated
81870 ** since sqlite3ReleaseTempRange() was called, it is safe to do so.
81872 sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx, j2, regRowid, pRegKey, P4_INT32);
81873 sqlite3HaltConstraint(
81874 pParse, OE_Abort, "indexed columns are not unique", P4_STATIC);
81876 sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 0);
81877 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
81878 #endif
81879 sqlite3ReleaseTempReg(pParse, regRecord);
81880 sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2);
81881 sqlite3VdbeJumpHere(v, addr1);
81883 sqlite3VdbeAddOp1(v, OP_Close, iTab);
81884 sqlite3VdbeAddOp1(v, OP_Close, iIdx);
81885 sqlite3VdbeAddOp1(v, OP_Close, iSorter);
81889 ** Create a new index for an SQL table. pName1.pName2 is the name of the index
81890 ** and pTblList is the name of the table that is to be indexed. Both will
81891 ** be NULL for a primary key or an index that is created to satisfy a
81892 ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
81893 ** as the table to be indexed. pParse->pNewTable is a table that is
81894 ** currently being constructed by a CREATE TABLE statement.
81896 ** pList is a list of columns to be indexed. pList will be NULL if this
81897 ** is a primary key or unique-constraint on the most recent column added
81898 ** to the table currently under construction.
81900 ** If the index is created successfully, return a pointer to the new Index
81901 ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
81902 ** as the tables primary key (Index.autoIndex==2).
81904 SQLITE_PRIVATE Index *sqlite3CreateIndex(
81905 Parse *pParse, /* All information about this parse */
81906 Token *pName1, /* First part of index name. May be NULL */
81907 Token *pName2, /* Second part of index name. May be NULL */
81908 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
81909 ExprList *pList, /* A list of columns to be indexed */
81910 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
81911 Token *pStart, /* The CREATE token that begins this statement */
81912 Token *pEnd, /* The ")" that closes the CREATE INDEX statement */
81913 int sortOrder, /* Sort order of primary key when pList==NULL */
81914 int ifNotExist /* Omit error if index already exists */
81916 Index *pRet = 0; /* Pointer to return */
81917 Table *pTab = 0; /* Table to be indexed */
81918 Index *pIndex = 0; /* The index to be created */
81919 char *zName = 0; /* Name of the index */
81920 int nName; /* Number of characters in zName */
81921 int i, j;
81922 Token nullId; /* Fake token for an empty ID list */
81923 DbFixer sFix; /* For assigning database names to pTable */
81924 int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
81925 sqlite3 *db = pParse->db;
81926 Db *pDb; /* The specific table containing the indexed database */
81927 int iDb; /* Index of the database that is being written */
81928 Token *pName = 0; /* Unqualified name of the index to create */
81929 struct ExprList_item *pListItem; /* For looping over pList */
81930 int nCol;
81931 int nExtra = 0;
81932 char *zExtra;
81934 assert( pStart==0 || pEnd!=0 ); /* pEnd must be non-NULL if pStart is */
81935 assert( pParse->nErr==0 ); /* Never called with prior errors */
81936 if( db->mallocFailed || IN_DECLARE_VTAB ){
81937 goto exit_create_index;
81939 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
81940 goto exit_create_index;
81944 ** Find the table that is to be indexed. Return early if not found.
81946 if( pTblName!=0 ){
81948 /* Use the two-part index name to determine the database
81949 ** to search for the table. 'Fix' the table name to this db
81950 ** before looking up the table.
81952 assert( pName1 && pName2 );
81953 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
81954 if( iDb<0 ) goto exit_create_index;
81955 assert( pName && pName->z );
81957 #ifndef SQLITE_OMIT_TEMPDB
81958 /* If the index name was unqualified, check if the the table
81959 ** is a temp table. If so, set the database to 1. Do not do this
81960 ** if initialising a database schema.
81962 if( !db->init.busy ){
81963 pTab = sqlite3SrcListLookup(pParse, pTblName);
81964 if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
81965 iDb = 1;
81968 #endif
81970 if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
81971 sqlite3FixSrcList(&sFix, pTblName)
81973 /* Because the parser constructs pTblName from a single identifier,
81974 ** sqlite3FixSrcList can never fail. */
81975 assert(0);
81977 pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName,
81978 pTblName->a[0].zDatabase);
81979 if( !pTab || db->mallocFailed ) goto exit_create_index;
81980 assert( db->aDb[iDb].pSchema==pTab->pSchema );
81981 }else{
81982 assert( pName==0 );
81983 assert( pStart==0 );
81984 pTab = pParse->pNewTable;
81985 if( !pTab ) goto exit_create_index;
81986 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
81988 pDb = &db->aDb[iDb];
81990 assert( pTab!=0 );
81991 assert( pParse->nErr==0 );
81992 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
81993 && memcmp(&pTab->zName[7],"altertab_",9)!=0 ){
81994 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
81995 goto exit_create_index;
81997 #ifndef SQLITE_OMIT_VIEW
81998 if( pTab->pSelect ){
81999 sqlite3ErrorMsg(pParse, "views may not be indexed");
82000 goto exit_create_index;
82002 #endif
82003 #ifndef SQLITE_OMIT_VIRTUALTABLE
82004 if( IsVirtual(pTab) ){
82005 sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
82006 goto exit_create_index;
82008 #endif
82011 ** Find the name of the index. Make sure there is not already another
82012 ** index or table with the same name.
82014 ** Exception: If we are reading the names of permanent indices from the
82015 ** sqlite_master table (because some other process changed the schema) and
82016 ** one of the index names collides with the name of a temporary table or
82017 ** index, then we will continue to process this index.
82019 ** If pName==0 it means that we are
82020 ** dealing with a primary key or UNIQUE constraint. We have to invent our
82021 ** own name.
82023 if( pName ){
82024 zName = sqlite3NameFromToken(db, pName);
82025 if( zName==0 ) goto exit_create_index;
82026 assert( pName->z!=0 );
82027 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
82028 goto exit_create_index;
82030 if( !db->init.busy ){
82031 if( sqlite3FindTable(db, zName, 0)!=0 ){
82032 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
82033 goto exit_create_index;
82036 if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
82037 if( !ifNotExist ){
82038 sqlite3ErrorMsg(pParse, "index %s already exists", zName);
82039 }else{
82040 assert( !db->init.busy );
82041 sqlite3CodeVerifySchema(pParse, iDb);
82043 goto exit_create_index;
82045 }else{
82046 int n;
82047 Index *pLoop;
82048 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
82049 zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
82050 if( zName==0 ){
82051 goto exit_create_index;
82055 /* Check for authorization to create an index.
82057 #ifndef SQLITE_OMIT_AUTHORIZATION
82059 const char *zDb = pDb->zName;
82060 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
82061 goto exit_create_index;
82063 i = SQLITE_CREATE_INDEX;
82064 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
82065 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
82066 goto exit_create_index;
82069 #endif
82071 /* If pList==0, it means this routine was called to make a primary
82072 ** key out of the last column added to the table under construction.
82073 ** So create a fake list to simulate this.
82075 if( pList==0 ){
82076 nullId.z = pTab->aCol[pTab->nCol-1].zName;
82077 nullId.n = sqlite3Strlen30((char*)nullId.z);
82078 pList = sqlite3ExprListAppend(pParse, 0, 0);
82079 if( pList==0 ) goto exit_create_index;
82080 sqlite3ExprListSetName(pParse, pList, &nullId, 0);
82081 pList->a[0].sortOrder = (u8)sortOrder;
82084 /* Figure out how many bytes of space are required to store explicitly
82085 ** specified collation sequence names.
82087 for(i=0; i<pList->nExpr; i++){
82088 Expr *pExpr = pList->a[i].pExpr;
82089 if( pExpr ){
82090 CollSeq *pColl = pExpr->pColl;
82091 /* Either pColl!=0 or there was an OOM failure. But if an OOM
82092 ** failure we have quit before reaching this point. */
82093 if( ALWAYS(pColl) ){
82094 nExtra += (1 + sqlite3Strlen30(pColl->zName));
82100 ** Allocate the index structure.
82102 nName = sqlite3Strlen30(zName);
82103 nCol = pList->nExpr;
82104 pIndex = sqlite3DbMallocZero(db,
82105 sizeof(Index) + /* Index structure */
82106 sizeof(tRowcnt)*(nCol+1) + /* Index.aiRowEst */
82107 sizeof(int)*nCol + /* Index.aiColumn */
82108 sizeof(char *)*nCol + /* Index.azColl */
82109 sizeof(u8)*nCol + /* Index.aSortOrder */
82110 nName + 1 + /* Index.zName */
82111 nExtra /* Collation sequence names */
82113 if( db->mallocFailed ){
82114 goto exit_create_index;
82116 pIndex->aiRowEst = (tRowcnt*)(&pIndex[1]);
82117 pIndex->azColl = (char**)(&pIndex->aiRowEst[nCol+1]);
82118 pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
82119 pIndex->aSortOrder = (u8 *)(&pIndex->aiColumn[nCol]);
82120 pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
82121 zExtra = (char *)(&pIndex->zName[nName+1]);
82122 memcpy(pIndex->zName, zName, nName+1);
82123 pIndex->pTable = pTab;
82124 pIndex->nColumn = pList->nExpr;
82125 pIndex->onError = (u8)onError;
82126 pIndex->autoIndex = (u8)(pName==0);
82127 pIndex->pSchema = db->aDb[iDb].pSchema;
82128 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
82130 /* Check to see if we should honor DESC requests on index columns
82132 if( pDb->pSchema->file_format>=4 ){
82133 sortOrderMask = -1; /* Honor DESC */
82134 }else{
82135 sortOrderMask = 0; /* Ignore DESC */
82138 /* Scan the names of the columns of the table to be indexed and
82139 ** load the column indices into the Index structure. Report an error
82140 ** if any column is not found.
82142 ** TODO: Add a test to make sure that the same column is not named
82143 ** more than once within the same index. Only the first instance of
82144 ** the column will ever be used by the optimizer. Note that using the
82145 ** same column more than once cannot be an error because that would
82146 ** break backwards compatibility - it needs to be a warning.
82148 for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
82149 const char *zColName = pListItem->zName;
82150 Column *pTabCol;
82151 int requestedSortOrder;
82152 char *zColl; /* Collation sequence name */
82154 for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
82155 if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
82157 if( j>=pTab->nCol ){
82158 sqlite3ErrorMsg(pParse, "table %s has no column named %s",
82159 pTab->zName, zColName);
82160 pParse->checkSchema = 1;
82161 goto exit_create_index;
82163 pIndex->aiColumn[i] = j;
82164 /* Justification of the ALWAYS(pListItem->pExpr->pColl): Because of
82165 ** the way the "idxlist" non-terminal is constructed by the parser,
82166 ** if pListItem->pExpr is not null then either pListItem->pExpr->pColl
82167 ** must exist or else there must have been an OOM error. But if there
82168 ** was an OOM error, we would never reach this point. */
82169 if( pListItem->pExpr && ALWAYS(pListItem->pExpr->pColl) ){
82170 int nColl;
82171 zColl = pListItem->pExpr->pColl->zName;
82172 nColl = sqlite3Strlen30(zColl) + 1;
82173 assert( nExtra>=nColl );
82174 memcpy(zExtra, zColl, nColl);
82175 zColl = zExtra;
82176 zExtra += nColl;
82177 nExtra -= nColl;
82178 }else{
82179 zColl = pTab->aCol[j].zColl;
82180 if( !zColl ){
82181 zColl = db->pDfltColl->zName;
82184 if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
82185 goto exit_create_index;
82187 pIndex->azColl[i] = zColl;
82188 requestedSortOrder = pListItem->sortOrder & sortOrderMask;
82189 pIndex->aSortOrder[i] = (u8)requestedSortOrder;
82191 sqlite3DefaultRowEst(pIndex);
82193 if( pTab==pParse->pNewTable ){
82194 /* This routine has been called to create an automatic index as a
82195 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
82196 ** a PRIMARY KEY or UNIQUE clause following the column definitions.
82197 ** i.e. one of:
82199 ** CREATE TABLE t(x PRIMARY KEY, y);
82200 ** CREATE TABLE t(x, y, UNIQUE(x, y));
82202 ** Either way, check to see if the table already has such an index. If
82203 ** so, don't bother creating this one. This only applies to
82204 ** automatically created indices. Users can do as they wish with
82205 ** explicit indices.
82207 ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
82208 ** (and thus suppressing the second one) even if they have different
82209 ** sort orders.
82211 ** If there are different collating sequences or if the columns of
82212 ** the constraint occur in different orders, then the constraints are
82213 ** considered distinct and both result in separate indices.
82215 Index *pIdx;
82216 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
82217 int k;
82218 assert( pIdx->onError!=OE_None );
82219 assert( pIdx->autoIndex );
82220 assert( pIndex->onError!=OE_None );
82222 if( pIdx->nColumn!=pIndex->nColumn ) continue;
82223 for(k=0; k<pIdx->nColumn; k++){
82224 const char *z1;
82225 const char *z2;
82226 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
82227 z1 = pIdx->azColl[k];
82228 z2 = pIndex->azColl[k];
82229 if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
82231 if( k==pIdx->nColumn ){
82232 if( pIdx->onError!=pIndex->onError ){
82233 /* This constraint creates the same index as a previous
82234 ** constraint specified somewhere in the CREATE TABLE statement.
82235 ** However the ON CONFLICT clauses are different. If both this
82236 ** constraint and the previous equivalent constraint have explicit
82237 ** ON CONFLICT clauses this is an error. Otherwise, use the
82238 ** explicitly specified behaviour for the index.
82240 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
82241 sqlite3ErrorMsg(pParse,
82242 "conflicting ON CONFLICT clauses specified", 0);
82244 if( pIdx->onError==OE_Default ){
82245 pIdx->onError = pIndex->onError;
82248 goto exit_create_index;
82253 /* Link the new Index structure to its table and to the other
82254 ** in-memory database structures.
82256 if( db->init.busy ){
82257 Index *p;
82258 assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
82259 p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
82260 pIndex->zName, sqlite3Strlen30(pIndex->zName),
82261 pIndex);
82262 if( p ){
82263 assert( p==pIndex ); /* Malloc must have failed */
82264 db->mallocFailed = 1;
82265 goto exit_create_index;
82267 db->flags |= SQLITE_InternChanges;
82268 if( pTblName!=0 ){
82269 pIndex->tnum = db->init.newTnum;
82273 /* If the db->init.busy is 0 then create the index on disk. This
82274 ** involves writing the index into the master table and filling in the
82275 ** index with the current table contents.
82277 ** The db->init.busy is 0 when the user first enters a CREATE INDEX
82278 ** command. db->init.busy is 1 when a database is opened and
82279 ** CREATE INDEX statements are read out of the master table. In
82280 ** the latter case the index already exists on disk, which is why
82281 ** we don't want to recreate it.
82283 ** If pTblName==0 it means this index is generated as a primary key
82284 ** or UNIQUE constraint of a CREATE TABLE statement. Since the table
82285 ** has just been created, it contains no data and the index initialization
82286 ** step can be skipped.
82288 else{ /* if( db->init.busy==0 ) */
82289 Vdbe *v;
82290 char *zStmt;
82291 int iMem = ++pParse->nMem;
82293 v = sqlite3GetVdbe(pParse);
82294 if( v==0 ) goto exit_create_index;
82297 /* Create the rootpage for the index
82299 sqlite3BeginWriteOperation(pParse, 1, iDb);
82300 sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
82302 /* Gather the complete text of the CREATE INDEX statement into
82303 ** the zStmt variable
82305 if( pStart ){
82306 assert( pEnd!=0 );
82307 /* A named index with an explicit CREATE INDEX statement */
82308 zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
82309 onError==OE_None ? "" : " UNIQUE",
82310 (int)(pEnd->z - pName->z) + 1,
82311 pName->z);
82312 }else{
82313 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
82314 /* zStmt = sqlite3MPrintf(""); */
82315 zStmt = 0;
82318 /* Add an entry in sqlite_master for this index
82320 sqlite3NestedParse(pParse,
82321 "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
82322 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
82323 pIndex->zName,
82324 pTab->zName,
82325 iMem,
82326 zStmt
82328 sqlite3DbFree(db, zStmt);
82330 /* Fill the index with data and reparse the schema. Code an OP_Expire
82331 ** to invalidate all pre-compiled statements.
82333 if( pTblName ){
82334 sqlite3RefillIndex(pParse, pIndex, iMem);
82335 sqlite3ChangeCookie(pParse, iDb);
82336 sqlite3VdbeAddParseSchemaOp(v, iDb,
82337 sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
82338 sqlite3VdbeAddOp1(v, OP_Expire, 0);
82342 /* When adding an index to the list of indices for a table, make
82343 ** sure all indices labeled OE_Replace come after all those labeled
82344 ** OE_Ignore. This is necessary for the correct constraint check
82345 ** processing (in sqlite3GenerateConstraintChecks()) as part of
82346 ** UPDATE and INSERT statements.
82348 if( db->init.busy || pTblName==0 ){
82349 if( onError!=OE_Replace || pTab->pIndex==0
82350 || pTab->pIndex->onError==OE_Replace){
82351 pIndex->pNext = pTab->pIndex;
82352 pTab->pIndex = pIndex;
82353 }else{
82354 Index *pOther = pTab->pIndex;
82355 while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
82356 pOther = pOther->pNext;
82358 pIndex->pNext = pOther->pNext;
82359 pOther->pNext = pIndex;
82361 pRet = pIndex;
82362 pIndex = 0;
82365 /* Clean up before exiting */
82366 exit_create_index:
82367 if( pIndex ){
82368 sqlite3DbFree(db, pIndex->zColAff);
82369 sqlite3DbFree(db, pIndex);
82371 sqlite3ExprListDelete(db, pList);
82372 sqlite3SrcListDelete(db, pTblName);
82373 sqlite3DbFree(db, zName);
82374 return pRet;
82378 ** Fill the Index.aiRowEst[] array with default information - information
82379 ** to be used when we have not run the ANALYZE command.
82381 ** aiRowEst[0] is suppose to contain the number of elements in the index.
82382 ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
82383 ** number of rows in the table that match any particular value of the
82384 ** first column of the index. aiRowEst[2] is an estimate of the number
82385 ** of rows that match any particular combiniation of the first 2 columns
82386 ** of the index. And so forth. It must always be the case that
82388 ** aiRowEst[N]<=aiRowEst[N-1]
82389 ** aiRowEst[N]>=1
82391 ** Apart from that, we have little to go on besides intuition as to
82392 ** how aiRowEst[] should be initialized. The numbers generated here
82393 ** are based on typical values found in actual indices.
82395 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
82396 tRowcnt *a = pIdx->aiRowEst;
82397 int i;
82398 tRowcnt n;
82399 assert( a!=0 );
82400 a[0] = pIdx->pTable->nRowEst;
82401 if( a[0]<10 ) a[0] = 10;
82402 n = 10;
82403 for(i=1; i<=pIdx->nColumn; i++){
82404 a[i] = n;
82405 if( n>5 ) n--;
82407 if( pIdx->onError!=OE_None ){
82408 a[pIdx->nColumn] = 1;
82413 ** This routine will drop an existing named index. This routine
82414 ** implements the DROP INDEX statement.
82416 SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
82417 Index *pIndex;
82418 Vdbe *v;
82419 sqlite3 *db = pParse->db;
82420 int iDb;
82422 assert( pParse->nErr==0 ); /* Never called with prior errors */
82423 if( db->mallocFailed ){
82424 goto exit_drop_index;
82426 assert( pName->nSrc==1 );
82427 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
82428 goto exit_drop_index;
82430 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
82431 if( pIndex==0 ){
82432 if( !ifExists ){
82433 sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
82434 }else{
82435 sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
82437 pParse->checkSchema = 1;
82438 goto exit_drop_index;
82440 if( pIndex->autoIndex ){
82441 sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
82442 "or PRIMARY KEY constraint cannot be dropped", 0);
82443 goto exit_drop_index;
82445 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
82446 #ifndef SQLITE_OMIT_AUTHORIZATION
82448 int code = SQLITE_DROP_INDEX;
82449 Table *pTab = pIndex->pTable;
82450 const char *zDb = db->aDb[iDb].zName;
82451 const char *zTab = SCHEMA_TABLE(iDb);
82452 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
82453 goto exit_drop_index;
82455 if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
82456 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
82457 goto exit_drop_index;
82460 #endif
82462 /* Generate code to remove the index and from the master table */
82463 v = sqlite3GetVdbe(pParse);
82464 if( v ){
82465 sqlite3BeginWriteOperation(pParse, 1, iDb);
82466 sqlite3NestedParse(pParse,
82467 "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
82468 db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
82470 sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
82471 sqlite3ChangeCookie(pParse, iDb);
82472 destroyRootPage(pParse, pIndex->tnum, iDb);
82473 sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
82476 exit_drop_index:
82477 sqlite3SrcListDelete(db, pName);
82481 ** pArray is a pointer to an array of objects. Each object in the
82482 ** array is szEntry bytes in size. This routine allocates a new
82483 ** object on the end of the array.
82485 ** *pnEntry is the number of entries already in use. *pnAlloc is
82486 ** the previously allocated size of the array. initSize is the
82487 ** suggested initial array size allocation.
82489 ** The index of the new entry is returned in *pIdx.
82491 ** This routine returns a pointer to the array of objects. This
82492 ** might be the same as the pArray parameter or it might be a different
82493 ** pointer if the array was resized.
82495 SQLITE_PRIVATE void *sqlite3ArrayAllocate(
82496 sqlite3 *db, /* Connection to notify of malloc failures */
82497 void *pArray, /* Array of objects. Might be reallocated */
82498 int szEntry, /* Size of each object in the array */
82499 int initSize, /* Suggested initial allocation, in elements */
82500 int *pnEntry, /* Number of objects currently in use */
82501 int *pnAlloc, /* Current size of the allocation, in elements */
82502 int *pIdx /* Write the index of a new slot here */
82504 char *z;
82505 if( *pnEntry >= *pnAlloc ){
82506 void *pNew;
82507 int newSize;
82508 newSize = (*pnAlloc)*2 + initSize;
82509 pNew = sqlite3DbRealloc(db, pArray, newSize*szEntry);
82510 if( pNew==0 ){
82511 *pIdx = -1;
82512 return pArray;
82514 *pnAlloc = sqlite3DbMallocSize(db, pNew)/szEntry;
82515 pArray = pNew;
82517 z = (char*)pArray;
82518 memset(&z[*pnEntry * szEntry], 0, szEntry);
82519 *pIdx = *pnEntry;
82520 ++*pnEntry;
82521 return pArray;
82525 ** Append a new element to the given IdList. Create a new IdList if
82526 ** need be.
82528 ** A new IdList is returned, or NULL if malloc() fails.
82530 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
82531 int i;
82532 if( pList==0 ){
82533 pList = sqlite3DbMallocZero(db, sizeof(IdList) );
82534 if( pList==0 ) return 0;
82535 pList->nAlloc = 0;
82537 pList->a = sqlite3ArrayAllocate(
82539 pList->a,
82540 sizeof(pList->a[0]),
82542 &pList->nId,
82543 &pList->nAlloc,
82546 if( i<0 ){
82547 sqlite3IdListDelete(db, pList);
82548 return 0;
82550 pList->a[i].zName = sqlite3NameFromToken(db, pToken);
82551 return pList;
82555 ** Delete an IdList.
82557 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
82558 int i;
82559 if( pList==0 ) return;
82560 for(i=0; i<pList->nId; i++){
82561 sqlite3DbFree(db, pList->a[i].zName);
82563 sqlite3DbFree(db, pList->a);
82564 sqlite3DbFree(db, pList);
82568 ** Return the index in pList of the identifier named zId. Return -1
82569 ** if not found.
82571 SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
82572 int i;
82573 if( pList==0 ) return -1;
82574 for(i=0; i<pList->nId; i++){
82575 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
82577 return -1;
82581 ** Expand the space allocated for the given SrcList object by
82582 ** creating nExtra new slots beginning at iStart. iStart is zero based.
82583 ** New slots are zeroed.
82585 ** For example, suppose a SrcList initially contains two entries: A,B.
82586 ** To append 3 new entries onto the end, do this:
82588 ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
82590 ** After the call above it would contain: A, B, nil, nil, nil.
82591 ** If the iStart argument had been 1 instead of 2, then the result
82592 ** would have been: A, nil, nil, nil, B. To prepend the new slots,
82593 ** the iStart value would be 0. The result then would
82594 ** be: nil, nil, nil, A, B.
82596 ** If a memory allocation fails the SrcList is unchanged. The
82597 ** db->mallocFailed flag will be set to true.
82599 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
82600 sqlite3 *db, /* Database connection to notify of OOM errors */
82601 SrcList *pSrc, /* The SrcList to be enlarged */
82602 int nExtra, /* Number of new slots to add to pSrc->a[] */
82603 int iStart /* Index in pSrc->a[] of first new slot */
82605 int i;
82607 /* Sanity checking on calling parameters */
82608 assert( iStart>=0 );
82609 assert( nExtra>=1 );
82610 assert( pSrc!=0 );
82611 assert( iStart<=pSrc->nSrc );
82613 /* Allocate additional space if needed */
82614 if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
82615 SrcList *pNew;
82616 int nAlloc = pSrc->nSrc+nExtra;
82617 int nGot;
82618 pNew = sqlite3DbRealloc(db, pSrc,
82619 sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
82620 if( pNew==0 ){
82621 assert( db->mallocFailed );
82622 return pSrc;
82624 pSrc = pNew;
82625 nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
82626 pSrc->nAlloc = (u16)nGot;
82629 /* Move existing slots that come after the newly inserted slots
82630 ** out of the way */
82631 for(i=pSrc->nSrc-1; i>=iStart; i--){
82632 pSrc->a[i+nExtra] = pSrc->a[i];
82634 pSrc->nSrc += (i16)nExtra;
82636 /* Zero the newly allocated slots */
82637 memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
82638 for(i=iStart; i<iStart+nExtra; i++){
82639 pSrc->a[i].iCursor = -1;
82642 /* Return a pointer to the enlarged SrcList */
82643 return pSrc;
82648 ** Append a new table name to the given SrcList. Create a new SrcList if
82649 ** need be. A new entry is created in the SrcList even if pTable is NULL.
82651 ** A SrcList is returned, or NULL if there is an OOM error. The returned
82652 ** SrcList might be the same as the SrcList that was input or it might be
82653 ** a new one. If an OOM error does occurs, then the prior value of pList
82654 ** that is input to this routine is automatically freed.
82656 ** If pDatabase is not null, it means that the table has an optional
82657 ** database name prefix. Like this: "database.table". The pDatabase
82658 ** points to the table name and the pTable points to the database name.
82659 ** The SrcList.a[].zName field is filled with the table name which might
82660 ** come from pTable (if pDatabase is NULL) or from pDatabase.
82661 ** SrcList.a[].zDatabase is filled with the database name from pTable,
82662 ** or with NULL if no database is specified.
82664 ** In other words, if call like this:
82666 ** sqlite3SrcListAppend(D,A,B,0);
82668 ** Then B is a table name and the database name is unspecified. If called
82669 ** like this:
82671 ** sqlite3SrcListAppend(D,A,B,C);
82673 ** Then C is the table name and B is the database name. If C is defined
82674 ** then so is B. In other words, we never have a case where:
82676 ** sqlite3SrcListAppend(D,A,0,C);
82678 ** Both pTable and pDatabase are assumed to be quoted. They are dequoted
82679 ** before being added to the SrcList.
82681 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
82682 sqlite3 *db, /* Connection to notify of malloc failures */
82683 SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
82684 Token *pTable, /* Table to append */
82685 Token *pDatabase /* Database of the table */
82687 struct SrcList_item *pItem;
82688 assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
82689 if( pList==0 ){
82690 pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
82691 if( pList==0 ) return 0;
82692 pList->nAlloc = 1;
82694 pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
82695 if( db->mallocFailed ){
82696 sqlite3SrcListDelete(db, pList);
82697 return 0;
82699 pItem = &pList->a[pList->nSrc-1];
82700 if( pDatabase && pDatabase->z==0 ){
82701 pDatabase = 0;
82703 if( pDatabase ){
82704 Token *pTemp = pDatabase;
82705 pDatabase = pTable;
82706 pTable = pTemp;
82708 pItem->zName = sqlite3NameFromToken(db, pTable);
82709 pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
82710 return pList;
82714 ** Assign VdbeCursor index numbers to all tables in a SrcList
82716 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
82717 int i;
82718 struct SrcList_item *pItem;
82719 assert(pList || pParse->db->mallocFailed );
82720 if( pList ){
82721 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
82722 if( pItem->iCursor>=0 ) break;
82723 pItem->iCursor = pParse->nTab++;
82724 if( pItem->pSelect ){
82725 sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
82732 ** Delete an entire SrcList including all its substructure.
82734 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
82735 int i;
82736 struct SrcList_item *pItem;
82737 if( pList==0 ) return;
82738 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
82739 sqlite3DbFree(db, pItem->zDatabase);
82740 sqlite3DbFree(db, pItem->zName);
82741 sqlite3DbFree(db, pItem->zAlias);
82742 sqlite3DbFree(db, pItem->zIndex);
82743 sqlite3DeleteTable(db, pItem->pTab);
82744 sqlite3SelectDelete(db, pItem->pSelect);
82745 sqlite3ExprDelete(db, pItem->pOn);
82746 sqlite3IdListDelete(db, pItem->pUsing);
82748 sqlite3DbFree(db, pList);
82752 ** This routine is called by the parser to add a new term to the
82753 ** end of a growing FROM clause. The "p" parameter is the part of
82754 ** the FROM clause that has already been constructed. "p" is NULL
82755 ** if this is the first term of the FROM clause. pTable and pDatabase
82756 ** are the name of the table and database named in the FROM clause term.
82757 ** pDatabase is NULL if the database name qualifier is missing - the
82758 ** usual case. If the term has a alias, then pAlias points to the
82759 ** alias token. If the term is a subquery, then pSubquery is the
82760 ** SELECT statement that the subquery encodes. The pTable and
82761 ** pDatabase parameters are NULL for subqueries. The pOn and pUsing
82762 ** parameters are the content of the ON and USING clauses.
82764 ** Return a new SrcList which encodes is the FROM with the new
82765 ** term added.
82767 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
82768 Parse *pParse, /* Parsing context */
82769 SrcList *p, /* The left part of the FROM clause already seen */
82770 Token *pTable, /* Name of the table to add to the FROM clause */
82771 Token *pDatabase, /* Name of the database containing pTable */
82772 Token *pAlias, /* The right-hand side of the AS subexpression */
82773 Select *pSubquery, /* A subquery used in place of a table name */
82774 Expr *pOn, /* The ON clause of a join */
82775 IdList *pUsing /* The USING clause of a join */
82777 struct SrcList_item *pItem;
82778 sqlite3 *db = pParse->db;
82779 if( !p && (pOn || pUsing) ){
82780 sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
82781 (pOn ? "ON" : "USING")
82783 goto append_from_error;
82785 p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
82786 if( p==0 || NEVER(p->nSrc==0) ){
82787 goto append_from_error;
82789 pItem = &p->a[p->nSrc-1];
82790 assert( pAlias!=0 );
82791 if( pAlias->n ){
82792 pItem->zAlias = sqlite3NameFromToken(db, pAlias);
82794 pItem->pSelect = pSubquery;
82795 pItem->pOn = pOn;
82796 pItem->pUsing = pUsing;
82797 return p;
82799 append_from_error:
82800 assert( p==0 );
82801 sqlite3ExprDelete(db, pOn);
82802 sqlite3IdListDelete(db, pUsing);
82803 sqlite3SelectDelete(db, pSubquery);
82804 return 0;
82808 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
82809 ** element of the source-list passed as the second argument.
82811 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
82812 assert( pIndexedBy!=0 );
82813 if( p && ALWAYS(p->nSrc>0) ){
82814 struct SrcList_item *pItem = &p->a[p->nSrc-1];
82815 assert( pItem->notIndexed==0 && pItem->zIndex==0 );
82816 if( pIndexedBy->n==1 && !pIndexedBy->z ){
82817 /* A "NOT INDEXED" clause was supplied. See parse.y
82818 ** construct "indexed_opt" for details. */
82819 pItem->notIndexed = 1;
82820 }else{
82821 pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
82827 ** When building up a FROM clause in the parser, the join operator
82828 ** is initially attached to the left operand. But the code generator
82829 ** expects the join operator to be on the right operand. This routine
82830 ** Shifts all join operators from left to right for an entire FROM
82831 ** clause.
82833 ** Example: Suppose the join is like this:
82835 ** A natural cross join B
82837 ** The operator is "natural cross join". The A and B operands are stored
82838 ** in p->a[0] and p->a[1], respectively. The parser initially stores the
82839 ** operator with A. This routine shifts that operator over to B.
82841 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
82842 if( p ){
82843 int i;
82844 assert( p->a || p->nSrc==0 );
82845 for(i=p->nSrc-1; i>0; i--){
82846 p->a[i].jointype = p->a[i-1].jointype;
82848 p->a[0].jointype = 0;
82853 ** Begin a transaction
82855 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
82856 sqlite3 *db;
82857 Vdbe *v;
82858 int i;
82860 assert( pParse!=0 );
82861 db = pParse->db;
82862 assert( db!=0 );
82863 /* if( db->aDb[0].pBt==0 ) return; */
82864 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
82865 return;
82867 v = sqlite3GetVdbe(pParse);
82868 if( !v ) return;
82869 if( type!=TK_DEFERRED ){
82870 for(i=0; i<db->nDb; i++){
82871 sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
82872 sqlite3VdbeUsesBtree(v, i);
82875 sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
82879 ** Commit a transaction
82881 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
82882 Vdbe *v;
82884 assert( pParse!=0 );
82885 assert( pParse->db!=0 );
82886 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
82887 return;
82889 v = sqlite3GetVdbe(pParse);
82890 if( v ){
82891 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
82896 ** Rollback a transaction
82898 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
82899 Vdbe *v;
82901 assert( pParse!=0 );
82902 assert( pParse->db!=0 );
82903 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
82904 return;
82906 v = sqlite3GetVdbe(pParse);
82907 if( v ){
82908 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
82913 ** This function is called by the parser when it parses a command to create,
82914 ** release or rollback an SQL savepoint.
82916 SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
82917 char *zName = sqlite3NameFromToken(pParse->db, pName);
82918 if( zName ){
82919 Vdbe *v = sqlite3GetVdbe(pParse);
82920 #ifndef SQLITE_OMIT_AUTHORIZATION
82921 static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
82922 assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
82923 #endif
82924 if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
82925 sqlite3DbFree(pParse->db, zName);
82926 return;
82928 sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
82933 ** Make sure the TEMP database is open and available for use. Return
82934 ** the number of errors. Leave any error messages in the pParse structure.
82936 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
82937 sqlite3 *db = pParse->db;
82938 if( db->aDb[1].pBt==0 && !pParse->explain ){
82939 int rc;
82940 Btree *pBt;
82941 static const int flags =
82942 SQLITE_OPEN_READWRITE |
82943 SQLITE_OPEN_CREATE |
82944 SQLITE_OPEN_EXCLUSIVE |
82945 SQLITE_OPEN_DELETEONCLOSE |
82946 SQLITE_OPEN_TEMP_DB;
82948 rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
82949 if( rc!=SQLITE_OK ){
82950 sqlite3ErrorMsg(pParse, "unable to open a temporary database "
82951 "file for storing temporary tables");
82952 pParse->rc = rc;
82953 return 1;
82955 db->aDb[1].pBt = pBt;
82956 assert( db->aDb[1].pSchema );
82957 if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
82958 db->mallocFailed = 1;
82959 return 1;
82962 return 0;
82966 ** Generate VDBE code that will verify the schema cookie and start
82967 ** a read-transaction for all named database files.
82969 ** It is important that all schema cookies be verified and all
82970 ** read transactions be started before anything else happens in
82971 ** the VDBE program. But this routine can be called after much other
82972 ** code has been generated. So here is what we do:
82974 ** The first time this routine is called, we code an OP_Goto that
82975 ** will jump to a subroutine at the end of the program. Then we
82976 ** record every database that needs its schema verified in the
82977 ** pParse->cookieMask field. Later, after all other code has been
82978 ** generated, the subroutine that does the cookie verifications and
82979 ** starts the transactions will be coded and the OP_Goto P2 value
82980 ** will be made to point to that subroutine. The generation of the
82981 ** cookie verification subroutine code happens in sqlite3FinishCoding().
82983 ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
82984 ** schema on any databases. This can be used to position the OP_Goto
82985 ** early in the code, before we know if any database tables will be used.
82987 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
82988 Parse *pToplevel = sqlite3ParseToplevel(pParse);
82990 if( pToplevel->cookieGoto==0 ){
82991 Vdbe *v = sqlite3GetVdbe(pToplevel);
82992 if( v==0 ) return; /* This only happens if there was a prior error */
82993 pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
82995 if( iDb>=0 ){
82996 sqlite3 *db = pToplevel->db;
82997 yDbMask mask;
82999 assert( iDb<db->nDb );
83000 assert( db->aDb[iDb].pBt!=0 || iDb==1 );
83001 assert( iDb<SQLITE_MAX_ATTACHED+2 );
83002 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
83003 mask = ((yDbMask)1)<<iDb;
83004 if( (pToplevel->cookieMask & mask)==0 ){
83005 pToplevel->cookieMask |= mask;
83006 pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
83007 if( !OMIT_TEMPDB && iDb==1 ){
83008 sqlite3OpenTempDatabase(pToplevel);
83015 ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
83016 ** attached database. Otherwise, invoke it for the database named zDb only.
83018 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
83019 sqlite3 *db = pParse->db;
83020 int i;
83021 for(i=0; i<db->nDb; i++){
83022 Db *pDb = &db->aDb[i];
83023 if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
83024 sqlite3CodeVerifySchema(pParse, i);
83030 ** Generate VDBE code that prepares for doing an operation that
83031 ** might change the database.
83033 ** This routine starts a new transaction if we are not already within
83034 ** a transaction. If we are already within a transaction, then a checkpoint
83035 ** is set if the setStatement parameter is true. A checkpoint should
83036 ** be set for operations that might fail (due to a constraint) part of
83037 ** the way through and which will need to undo some writes without having to
83038 ** rollback the whole transaction. For operations where all constraints
83039 ** can be checked before any changes are made to the database, it is never
83040 ** necessary to undo a write and the checkpoint should not be set.
83042 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
83043 Parse *pToplevel = sqlite3ParseToplevel(pParse);
83044 sqlite3CodeVerifySchema(pParse, iDb);
83045 pToplevel->writeMask |= ((yDbMask)1)<<iDb;
83046 pToplevel->isMultiWrite |= setStatement;
83050 ** Indicate that the statement currently under construction might write
83051 ** more than one entry (example: deleting one row then inserting another,
83052 ** inserting multiple rows in a table, or inserting a row and index entries.)
83053 ** If an abort occurs after some of these writes have completed, then it will
83054 ** be necessary to undo the completed writes.
83056 SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
83057 Parse *pToplevel = sqlite3ParseToplevel(pParse);
83058 pToplevel->isMultiWrite = 1;
83062 ** The code generator calls this routine if is discovers that it is
83063 ** possible to abort a statement prior to completion. In order to
83064 ** perform this abort without corrupting the database, we need to make
83065 ** sure that the statement is protected by a statement transaction.
83067 ** Technically, we only need to set the mayAbort flag if the
83068 ** isMultiWrite flag was previously set. There is a time dependency
83069 ** such that the abort must occur after the multiwrite. This makes
83070 ** some statements involving the REPLACE conflict resolution algorithm
83071 ** go a little faster. But taking advantage of this time dependency
83072 ** makes it more difficult to prove that the code is correct (in
83073 ** particular, it prevents us from writing an effective
83074 ** implementation of sqlite3AssertMayAbort()) and so we have chosen
83075 ** to take the safe route and skip the optimization.
83077 SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
83078 Parse *pToplevel = sqlite3ParseToplevel(pParse);
83079 pToplevel->mayAbort = 1;
83083 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
83084 ** error. The onError parameter determines which (if any) of the statement
83085 ** and/or current transaction is rolled back.
83087 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse *pParse, int onError, char *p4, int p4type){
83088 Vdbe *v = sqlite3GetVdbe(pParse);
83089 if( onError==OE_Abort ){
83090 sqlite3MayAbort(pParse);
83092 sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, p4, p4type);
83096 ** Check to see if pIndex uses the collating sequence pColl. Return
83097 ** true if it does and false if it does not.
83099 #ifndef SQLITE_OMIT_REINDEX
83100 static int collationMatch(const char *zColl, Index *pIndex){
83101 int i;
83102 assert( zColl!=0 );
83103 for(i=0; i<pIndex->nColumn; i++){
83104 const char *z = pIndex->azColl[i];
83105 assert( z!=0 );
83106 if( 0==sqlite3StrICmp(z, zColl) ){
83107 return 1;
83110 return 0;
83112 #endif
83115 ** Recompute all indices of pTab that use the collating sequence pColl.
83116 ** If pColl==0 then recompute all indices of pTab.
83118 #ifndef SQLITE_OMIT_REINDEX
83119 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
83120 Index *pIndex; /* An index associated with pTab */
83122 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
83123 if( zColl==0 || collationMatch(zColl, pIndex) ){
83124 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
83125 sqlite3BeginWriteOperation(pParse, 0, iDb);
83126 sqlite3RefillIndex(pParse, pIndex, -1);
83130 #endif
83133 ** Recompute all indices of all tables in all databases where the
83134 ** indices use the collating sequence pColl. If pColl==0 then recompute
83135 ** all indices everywhere.
83137 #ifndef SQLITE_OMIT_REINDEX
83138 static void reindexDatabases(Parse *pParse, char const *zColl){
83139 Db *pDb; /* A single database */
83140 int iDb; /* The database index number */
83141 sqlite3 *db = pParse->db; /* The database connection */
83142 HashElem *k; /* For looping over tables in pDb */
83143 Table *pTab; /* A table in the database */
83145 assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
83146 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
83147 assert( pDb!=0 );
83148 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
83149 pTab = (Table*)sqliteHashData(k);
83150 reindexTable(pParse, pTab, zColl);
83154 #endif
83157 ** Generate code for the REINDEX command.
83159 ** REINDEX -- 1
83160 ** REINDEX <collation> -- 2
83161 ** REINDEX ?<database>.?<tablename> -- 3
83162 ** REINDEX ?<database>.?<indexname> -- 4
83164 ** Form 1 causes all indices in all attached databases to be rebuilt.
83165 ** Form 2 rebuilds all indices in all databases that use the named
83166 ** collating function. Forms 3 and 4 rebuild the named index or all
83167 ** indices associated with the named table.
83169 #ifndef SQLITE_OMIT_REINDEX
83170 SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
83171 CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
83172 char *z; /* Name of a table or index */
83173 const char *zDb; /* Name of the database */
83174 Table *pTab; /* A table in the database */
83175 Index *pIndex; /* An index associated with pTab */
83176 int iDb; /* The database index number */
83177 sqlite3 *db = pParse->db; /* The database connection */
83178 Token *pObjName; /* Name of the table or index to be reindexed */
83180 /* Read the database schema. If an error occurs, leave an error message
83181 ** and code in pParse and return NULL. */
83182 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
83183 return;
83186 if( pName1==0 ){
83187 reindexDatabases(pParse, 0);
83188 return;
83189 }else if( NEVER(pName2==0) || pName2->z==0 ){
83190 char *zColl;
83191 assert( pName1->z );
83192 zColl = sqlite3NameFromToken(pParse->db, pName1);
83193 if( !zColl ) return;
83194 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
83195 if( pColl ){
83196 reindexDatabases(pParse, zColl);
83197 sqlite3DbFree(db, zColl);
83198 return;
83200 sqlite3DbFree(db, zColl);
83202 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
83203 if( iDb<0 ) return;
83204 z = sqlite3NameFromToken(db, pObjName);
83205 if( z==0 ) return;
83206 zDb = db->aDb[iDb].zName;
83207 pTab = sqlite3FindTable(db, z, zDb);
83208 if( pTab ){
83209 reindexTable(pParse, pTab, 0);
83210 sqlite3DbFree(db, z);
83211 return;
83213 pIndex = sqlite3FindIndex(db, z, zDb);
83214 sqlite3DbFree(db, z);
83215 if( pIndex ){
83216 sqlite3BeginWriteOperation(pParse, 0, iDb);
83217 sqlite3RefillIndex(pParse, pIndex, -1);
83218 return;
83220 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
83222 #endif
83225 ** Return a dynamicly allocated KeyInfo structure that can be used
83226 ** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
83228 ** If successful, a pointer to the new structure is returned. In this case
83229 ** the caller is responsible for calling sqlite3DbFree(db, ) on the returned
83230 ** pointer. If an error occurs (out of memory or missing collation
83231 ** sequence), NULL is returned and the state of pParse updated to reflect
83232 ** the error.
83234 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
83235 int i;
83236 int nCol = pIdx->nColumn;
83237 int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
83238 sqlite3 *db = pParse->db;
83239 KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
83241 if( pKey ){
83242 pKey->db = pParse->db;
83243 pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
83244 assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
83245 for(i=0; i<nCol; i++){
83246 char *zColl = pIdx->azColl[i];
83247 assert( zColl );
83248 pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
83249 pKey->aSortOrder[i] = pIdx->aSortOrder[i];
83251 pKey->nField = (u16)nCol;
83254 if( pParse->nErr ){
83255 sqlite3DbFree(db, pKey);
83256 pKey = 0;
83258 return pKey;
83261 /************** End of build.c ***********************************************/
83262 /************** Begin file callback.c ****************************************/
83264 ** 2005 May 23
83266 ** The author disclaims copyright to this source code. In place of
83267 ** a legal notice, here is a blessing:
83269 ** May you do good and not evil.
83270 ** May you find forgiveness for yourself and forgive others.
83271 ** May you share freely, never taking more than you give.
83273 *************************************************************************
83275 ** This file contains functions used to access the internal hash tables
83276 ** of user defined functions and collation sequences.
83281 ** Invoke the 'collation needed' callback to request a collation sequence
83282 ** in the encoding enc of name zName, length nName.
83284 static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
83285 assert( !db->xCollNeeded || !db->xCollNeeded16 );
83286 if( db->xCollNeeded ){
83287 char *zExternal = sqlite3DbStrDup(db, zName);
83288 if( !zExternal ) return;
83289 db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
83290 sqlite3DbFree(db, zExternal);
83292 #ifndef SQLITE_OMIT_UTF16
83293 if( db->xCollNeeded16 ){
83294 char const *zExternal;
83295 sqlite3_value *pTmp = sqlite3ValueNew(db);
83296 sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
83297 zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
83298 if( zExternal ){
83299 db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
83301 sqlite3ValueFree(pTmp);
83303 #endif
83307 ** This routine is called if the collation factory fails to deliver a
83308 ** collation function in the best encoding but there may be other versions
83309 ** of this collation function (for other text encodings) available. Use one
83310 ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
83311 ** possible.
83313 static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
83314 CollSeq *pColl2;
83315 char *z = pColl->zName;
83316 int i;
83317 static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
83318 for(i=0; i<3; i++){
83319 pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
83320 if( pColl2->xCmp!=0 ){
83321 memcpy(pColl, pColl2, sizeof(CollSeq));
83322 pColl->xDel = 0; /* Do not copy the destructor */
83323 return SQLITE_OK;
83326 return SQLITE_ERROR;
83330 ** This function is responsible for invoking the collation factory callback
83331 ** or substituting a collation sequence of a different encoding when the
83332 ** requested collation sequence is not available in the desired encoding.
83334 ** If it is not NULL, then pColl must point to the database native encoding
83335 ** collation sequence with name zName, length nName.
83337 ** The return value is either the collation sequence to be used in database
83338 ** db for collation type name zName, length nName, or NULL, if no collation
83339 ** sequence can be found.
83341 ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
83343 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
83344 sqlite3* db, /* The database connection */
83345 u8 enc, /* The desired encoding for the collating sequence */
83346 CollSeq *pColl, /* Collating sequence with native encoding, or NULL */
83347 const char *zName /* Collating sequence name */
83349 CollSeq *p;
83351 p = pColl;
83352 if( !p ){
83353 p = sqlite3FindCollSeq(db, enc, zName, 0);
83355 if( !p || !p->xCmp ){
83356 /* No collation sequence of this type for this encoding is registered.
83357 ** Call the collation factory to see if it can supply us with one.
83359 callCollNeeded(db, enc, zName);
83360 p = sqlite3FindCollSeq(db, enc, zName, 0);
83362 if( p && !p->xCmp && synthCollSeq(db, p) ){
83363 p = 0;
83365 assert( !p || p->xCmp );
83366 return p;
83370 ** This routine is called on a collation sequence before it is used to
83371 ** check that it is defined. An undefined collation sequence exists when
83372 ** a database is loaded that contains references to collation sequences
83373 ** that have not been defined by sqlite3_create_collation() etc.
83375 ** If required, this routine calls the 'collation needed' callback to
83376 ** request a definition of the collating sequence. If this doesn't work,
83377 ** an equivalent collating sequence that uses a text encoding different
83378 ** from the main database is substituted, if one is available.
83380 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
83381 if( pColl ){
83382 const char *zName = pColl->zName;
83383 sqlite3 *db = pParse->db;
83384 CollSeq *p = sqlite3GetCollSeq(db, ENC(db), pColl, zName);
83385 if( !p ){
83386 sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
83387 pParse->nErr++;
83388 return SQLITE_ERROR;
83390 assert( p==pColl );
83392 return SQLITE_OK;
83398 ** Locate and return an entry from the db.aCollSeq hash table. If the entry
83399 ** specified by zName and nName is not found and parameter 'create' is
83400 ** true, then create a new entry. Otherwise return NULL.
83402 ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
83403 ** array of three CollSeq structures. The first is the collation sequence
83404 ** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
83406 ** Stored immediately after the three collation sequences is a copy of
83407 ** the collation sequence name. A pointer to this string is stored in
83408 ** each collation sequence structure.
83410 static CollSeq *findCollSeqEntry(
83411 sqlite3 *db, /* Database connection */
83412 const char *zName, /* Name of the collating sequence */
83413 int create /* Create a new entry if true */
83415 CollSeq *pColl;
83416 int nName = sqlite3Strlen30(zName);
83417 pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
83419 if( 0==pColl && create ){
83420 pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
83421 if( pColl ){
83422 CollSeq *pDel = 0;
83423 pColl[0].zName = (char*)&pColl[3];
83424 pColl[0].enc = SQLITE_UTF8;
83425 pColl[1].zName = (char*)&pColl[3];
83426 pColl[1].enc = SQLITE_UTF16LE;
83427 pColl[2].zName = (char*)&pColl[3];
83428 pColl[2].enc = SQLITE_UTF16BE;
83429 memcpy(pColl[0].zName, zName, nName);
83430 pColl[0].zName[nName] = 0;
83431 pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
83433 /* If a malloc() failure occurred in sqlite3HashInsert(), it will
83434 ** return the pColl pointer to be deleted (because it wasn't added
83435 ** to the hash table).
83437 assert( pDel==0 || pDel==pColl );
83438 if( pDel!=0 ){
83439 db->mallocFailed = 1;
83440 sqlite3DbFree(db, pDel);
83441 pColl = 0;
83445 return pColl;
83449 ** Parameter zName points to a UTF-8 encoded string nName bytes long.
83450 ** Return the CollSeq* pointer for the collation sequence named zName
83451 ** for the encoding 'enc' from the database 'db'.
83453 ** If the entry specified is not found and 'create' is true, then create a
83454 ** new entry. Otherwise return NULL.
83456 ** A separate function sqlite3LocateCollSeq() is a wrapper around
83457 ** this routine. sqlite3LocateCollSeq() invokes the collation factory
83458 ** if necessary and generates an error message if the collating sequence
83459 ** cannot be found.
83461 ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
83463 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
83464 sqlite3 *db,
83465 u8 enc,
83466 const char *zName,
83467 int create
83469 CollSeq *pColl;
83470 if( zName ){
83471 pColl = findCollSeqEntry(db, zName, create);
83472 }else{
83473 pColl = db->pDfltColl;
83475 assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
83476 assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
83477 if( pColl ) pColl += enc-1;
83478 return pColl;
83481 /* During the search for the best function definition, this procedure
83482 ** is called to test how well the function passed as the first argument
83483 ** matches the request for a function with nArg arguments in a system
83484 ** that uses encoding enc. The value returned indicates how well the
83485 ** request is matched. A higher value indicates a better match.
83487 ** The returned value is always between 0 and 6, as follows:
83489 ** 0: Not a match, or if nArg<0 and the function is has no implementation.
83490 ** 1: A variable arguments function that prefers UTF-8 when a UTF-16
83491 ** encoding is requested, or vice versa.
83492 ** 2: A variable arguments function that uses UTF-16BE when UTF-16LE is
83493 ** requested, or vice versa.
83494 ** 3: A variable arguments function using the same text encoding.
83495 ** 4: A function with the exact number of arguments requested that
83496 ** prefers UTF-8 when a UTF-16 encoding is requested, or vice versa.
83497 ** 5: A function with the exact number of arguments requested that
83498 ** prefers UTF-16LE when UTF-16BE is requested, or vice versa.
83499 ** 6: An exact match.
83502 static int matchQuality(FuncDef *p, int nArg, u8 enc){
83503 int match = 0;
83504 if( p->nArg==-1 || p->nArg==nArg
83505 || (nArg==-1 && (p->xFunc!=0 || p->xStep!=0))
83507 match = 1;
83508 if( p->nArg==nArg || nArg==-1 ){
83509 match = 4;
83511 if( enc==p->iPrefEnc ){
83512 match += 2;
83514 else if( (enc==SQLITE_UTF16LE && p->iPrefEnc==SQLITE_UTF16BE) ||
83515 (enc==SQLITE_UTF16BE && p->iPrefEnc==SQLITE_UTF16LE) ){
83516 match += 1;
83519 return match;
83523 ** Search a FuncDefHash for a function with the given name. Return
83524 ** a pointer to the matching FuncDef if found, or 0 if there is no match.
83526 static FuncDef *functionSearch(
83527 FuncDefHash *pHash, /* Hash table to search */
83528 int h, /* Hash of the name */
83529 const char *zFunc, /* Name of function */
83530 int nFunc /* Number of bytes in zFunc */
83532 FuncDef *p;
83533 for(p=pHash->a[h]; p; p=p->pHash){
83534 if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
83535 return p;
83538 return 0;
83542 ** Insert a new FuncDef into a FuncDefHash hash table.
83544 SQLITE_PRIVATE void sqlite3FuncDefInsert(
83545 FuncDefHash *pHash, /* The hash table into which to insert */
83546 FuncDef *pDef /* The function definition to insert */
83548 FuncDef *pOther;
83549 int nName = sqlite3Strlen30(pDef->zName);
83550 u8 c1 = (u8)pDef->zName[0];
83551 int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
83552 pOther = functionSearch(pHash, h, pDef->zName, nName);
83553 if( pOther ){
83554 assert( pOther!=pDef && pOther->pNext!=pDef );
83555 pDef->pNext = pOther->pNext;
83556 pOther->pNext = pDef;
83557 }else{
83558 pDef->pNext = 0;
83559 pDef->pHash = pHash->a[h];
83560 pHash->a[h] = pDef;
83567 ** Locate a user function given a name, a number of arguments and a flag
83568 ** indicating whether the function prefers UTF-16 over UTF-8. Return a
83569 ** pointer to the FuncDef structure that defines that function, or return
83570 ** NULL if the function does not exist.
83572 ** If the createFlag argument is true, then a new (blank) FuncDef
83573 ** structure is created and liked into the "db" structure if a
83574 ** no matching function previously existed. When createFlag is true
83575 ** and the nArg parameter is -1, then only a function that accepts
83576 ** any number of arguments will be returned.
83578 ** If createFlag is false and nArg is -1, then the first valid
83579 ** function found is returned. A function is valid if either xFunc
83580 ** or xStep is non-zero.
83582 ** If createFlag is false, then a function with the required name and
83583 ** number of arguments may be returned even if the eTextRep flag does not
83584 ** match that requested.
83586 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
83587 sqlite3 *db, /* An open database */
83588 const char *zName, /* Name of the function. Not null-terminated */
83589 int nName, /* Number of characters in the name */
83590 int nArg, /* Number of arguments. -1 means any number */
83591 u8 enc, /* Preferred text encoding */
83592 int createFlag /* Create new entry if true and does not otherwise exist */
83594 FuncDef *p; /* Iterator variable */
83595 FuncDef *pBest = 0; /* Best match found so far */
83596 int bestScore = 0; /* Score of best match */
83597 int h; /* Hash value */
83600 assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
83601 h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
83603 /* First search for a match amongst the application-defined functions.
83605 p = functionSearch(&db->aFunc, h, zName, nName);
83606 while( p ){
83607 int score = matchQuality(p, nArg, enc);
83608 if( score>bestScore ){
83609 pBest = p;
83610 bestScore = score;
83612 p = p->pNext;
83615 /* If no match is found, search the built-in functions.
83617 ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
83618 ** functions even if a prior app-defined function was found. And give
83619 ** priority to built-in functions.
83621 ** Except, if createFlag is true, that means that we are trying to
83622 ** install a new function. Whatever FuncDef structure is returned it will
83623 ** have fields overwritten with new information appropriate for the
83624 ** new function. But the FuncDefs for built-in functions are read-only.
83625 ** So we must not search for built-ins when creating a new function.
83627 if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
83628 FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
83629 bestScore = 0;
83630 p = functionSearch(pHash, h, zName, nName);
83631 while( p ){
83632 int score = matchQuality(p, nArg, enc);
83633 if( score>bestScore ){
83634 pBest = p;
83635 bestScore = score;
83637 p = p->pNext;
83641 /* If the createFlag parameter is true and the search did not reveal an
83642 ** exact match for the name, number of arguments and encoding, then add a
83643 ** new entry to the hash table and return it.
83645 if( createFlag && (bestScore<6 || pBest->nArg!=nArg) &&
83646 (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
83647 pBest->zName = (char *)&pBest[1];
83648 pBest->nArg = (u16)nArg;
83649 pBest->iPrefEnc = enc;
83650 memcpy(pBest->zName, zName, nName);
83651 pBest->zName[nName] = 0;
83652 sqlite3FuncDefInsert(&db->aFunc, pBest);
83655 if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
83656 return pBest;
83658 return 0;
83662 ** Free all resources held by the schema structure. The void* argument points
83663 ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
83664 ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
83665 ** of the schema hash tables).
83667 ** The Schema.cache_size variable is not cleared.
83669 SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
83670 Hash temp1;
83671 Hash temp2;
83672 HashElem *pElem;
83673 Schema *pSchema = (Schema *)p;
83675 temp1 = pSchema->tblHash;
83676 temp2 = pSchema->trigHash;
83677 sqlite3HashInit(&pSchema->trigHash);
83678 sqlite3HashClear(&pSchema->idxHash);
83679 for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
83680 sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
83682 sqlite3HashClear(&temp2);
83683 sqlite3HashInit(&pSchema->tblHash);
83684 for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
83685 Table *pTab = sqliteHashData(pElem);
83686 sqlite3DeleteTable(0, pTab);
83688 sqlite3HashClear(&temp1);
83689 sqlite3HashClear(&pSchema->fkeyHash);
83690 pSchema->pSeqTab = 0;
83691 if( pSchema->flags & DB_SchemaLoaded ){
83692 pSchema->iGeneration++;
83693 pSchema->flags &= ~DB_SchemaLoaded;
83698 ** Find and return the schema associated with a BTree. Create
83699 ** a new one if necessary.
83701 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
83702 Schema * p;
83703 if( pBt ){
83704 p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
83705 }else{
83706 p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
83708 if( !p ){
83709 db->mallocFailed = 1;
83710 }else if ( 0==p->file_format ){
83711 sqlite3HashInit(&p->tblHash);
83712 sqlite3HashInit(&p->idxHash);
83713 sqlite3HashInit(&p->trigHash);
83714 sqlite3HashInit(&p->fkeyHash);
83715 p->enc = SQLITE_UTF8;
83717 return p;
83720 /************** End of callback.c ********************************************/
83721 /************** Begin file delete.c ******************************************/
83723 ** 2001 September 15
83725 ** The author disclaims copyright to this source code. In place of
83726 ** a legal notice, here is a blessing:
83728 ** May you do good and not evil.
83729 ** May you find forgiveness for yourself and forgive others.
83730 ** May you share freely, never taking more than you give.
83732 *************************************************************************
83733 ** This file contains C code routines that are called by the parser
83734 ** in order to generate code for DELETE FROM statements.
83738 ** While a SrcList can in general represent multiple tables and subqueries
83739 ** (as in the FROM clause of a SELECT statement) in this case it contains
83740 ** the name of a single table, as one might find in an INSERT, DELETE,
83741 ** or UPDATE statement. Look up that table in the symbol table and
83742 ** return a pointer. Set an error message and return NULL if the table
83743 ** name is not found or if any other error occurs.
83745 ** The following fields are initialized appropriate in pSrc:
83747 ** pSrc->a[0].pTab Pointer to the Table object
83748 ** pSrc->a[0].pIndex Pointer to the INDEXED BY index, if there is one
83751 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
83752 struct SrcList_item *pItem = pSrc->a;
83753 Table *pTab;
83754 assert( pItem && pSrc->nSrc==1 );
83755 pTab = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
83756 sqlite3DeleteTable(pParse->db, pItem->pTab);
83757 pItem->pTab = pTab;
83758 if( pTab ){
83759 pTab->nRef++;
83761 if( sqlite3IndexedByLookup(pParse, pItem) ){
83762 pTab = 0;
83764 return pTab;
83768 ** Check to make sure the given table is writable. If it is not
83769 ** writable, generate an error message and return 1. If it is
83770 ** writable return 0;
83772 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
83773 /* A table is not writable under the following circumstances:
83775 ** 1) It is a virtual table and no implementation of the xUpdate method
83776 ** has been provided, or
83777 ** 2) It is a system table (i.e. sqlite_master), this call is not
83778 ** part of a nested parse and writable_schema pragma has not
83779 ** been specified.
83781 ** In either case leave an error message in pParse and return non-zero.
83783 if( ( IsVirtual(pTab)
83784 && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
83785 || ( (pTab->tabFlags & TF_Readonly)!=0
83786 && (pParse->db->flags & SQLITE_WriteSchema)==0
83787 && pParse->nested==0 )
83789 sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
83790 return 1;
83793 #ifndef SQLITE_OMIT_VIEW
83794 if( !viewOk && pTab->pSelect ){
83795 sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
83796 return 1;
83798 #endif
83799 return 0;
83803 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
83805 ** Evaluate a view and store its result in an ephemeral table. The
83806 ** pWhere argument is an optional WHERE clause that restricts the
83807 ** set of rows in the view that are to be added to the ephemeral table.
83809 SQLITE_PRIVATE void sqlite3MaterializeView(
83810 Parse *pParse, /* Parsing context */
83811 Table *pView, /* View definition */
83812 Expr *pWhere, /* Optional WHERE clause to be added */
83813 int iCur /* Cursor number for ephemerial table */
83815 SelectDest dest;
83816 Select *pDup;
83817 sqlite3 *db = pParse->db;
83819 pDup = sqlite3SelectDup(db, pView->pSelect, 0);
83820 if( pWhere ){
83821 SrcList *pFrom;
83823 pWhere = sqlite3ExprDup(db, pWhere, 0);
83824 pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
83825 if( pFrom ){
83826 assert( pFrom->nSrc==1 );
83827 pFrom->a[0].zAlias = sqlite3DbStrDup(db, pView->zName);
83828 pFrom->a[0].pSelect = pDup;
83829 assert( pFrom->a[0].pOn==0 );
83830 assert( pFrom->a[0].pUsing==0 );
83831 }else{
83832 sqlite3SelectDelete(db, pDup);
83834 pDup = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
83836 sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
83837 sqlite3Select(pParse, pDup, &dest);
83838 sqlite3SelectDelete(db, pDup);
83840 #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
83842 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
83844 ** Generate an expression tree to implement the WHERE, ORDER BY,
83845 ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
83847 ** DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
83848 ** \__________________________/
83849 ** pLimitWhere (pInClause)
83851 SQLITE_PRIVATE Expr *sqlite3LimitWhere(
83852 Parse *pParse, /* The parser context */
83853 SrcList *pSrc, /* the FROM clause -- which tables to scan */
83854 Expr *pWhere, /* The WHERE clause. May be null */
83855 ExprList *pOrderBy, /* The ORDER BY clause. May be null */
83856 Expr *pLimit, /* The LIMIT clause. May be null */
83857 Expr *pOffset, /* The OFFSET clause. May be null */
83858 char *zStmtType /* Either DELETE or UPDATE. For error messages. */
83860 Expr *pWhereRowid = NULL; /* WHERE rowid .. */
83861 Expr *pInClause = NULL; /* WHERE rowid IN ( select ) */
83862 Expr *pSelectRowid = NULL; /* SELECT rowid ... */
83863 ExprList *pEList = NULL; /* Expression list contaning only pSelectRowid */
83864 SrcList *pSelectSrc = NULL; /* SELECT rowid FROM x ... (dup of pSrc) */
83865 Select *pSelect = NULL; /* Complete SELECT tree */
83867 /* Check that there isn't an ORDER BY without a LIMIT clause.
83869 if( pOrderBy && (pLimit == 0) ) {
83870 sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
83871 pParse->parseError = 1;
83872 goto limit_where_cleanup_2;
83875 /* We only need to generate a select expression if there
83876 ** is a limit/offset term to enforce.
83878 if( pLimit == 0 ) {
83879 /* if pLimit is null, pOffset will always be null as well. */
83880 assert( pOffset == 0 );
83881 return pWhere;
83884 /* Generate a select expression tree to enforce the limit/offset
83885 ** term for the DELETE or UPDATE statement. For example:
83886 ** DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
83887 ** becomes:
83888 ** DELETE FROM table_a WHERE rowid IN (
83889 ** SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
83890 ** );
83893 pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
83894 if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
83895 pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
83896 if( pEList == 0 ) goto limit_where_cleanup_2;
83898 /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
83899 ** and the SELECT subtree. */
83900 pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
83901 if( pSelectSrc == 0 ) {
83902 sqlite3ExprListDelete(pParse->db, pEList);
83903 goto limit_where_cleanup_2;
83906 /* generate the SELECT expression tree. */
83907 pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
83908 pOrderBy,0,pLimit,pOffset);
83909 if( pSelect == 0 ) return 0;
83911 /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
83912 pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
83913 if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
83914 pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
83915 if( pInClause == 0 ) goto limit_where_cleanup_1;
83917 pInClause->x.pSelect = pSelect;
83918 pInClause->flags |= EP_xIsSelect;
83919 sqlite3ExprSetHeight(pParse, pInClause);
83920 return pInClause;
83922 /* something went wrong. clean up anything allocated. */
83923 limit_where_cleanup_1:
83924 sqlite3SelectDelete(pParse->db, pSelect);
83925 return 0;
83927 limit_where_cleanup_2:
83928 sqlite3ExprDelete(pParse->db, pWhere);
83929 sqlite3ExprListDelete(pParse->db, pOrderBy);
83930 sqlite3ExprDelete(pParse->db, pLimit);
83931 sqlite3ExprDelete(pParse->db, pOffset);
83932 return 0;
83934 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
83937 ** Generate code for a DELETE FROM statement.
83939 ** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
83940 ** \________/ \________________/
83941 ** pTabList pWhere
83943 SQLITE_PRIVATE void sqlite3DeleteFrom(
83944 Parse *pParse, /* The parser context */
83945 SrcList *pTabList, /* The table from which we should delete things */
83946 Expr *pWhere /* The WHERE clause. May be null */
83948 Vdbe *v; /* The virtual database engine */
83949 Table *pTab; /* The table from which records will be deleted */
83950 const char *zDb; /* Name of database holding pTab */
83951 int end, addr = 0; /* A couple addresses of generated code */
83952 int i; /* Loop counter */
83953 WhereInfo *pWInfo; /* Information about the WHERE clause */
83954 Index *pIdx; /* For looping over indices of the table */
83955 int iCur; /* VDBE Cursor number for pTab */
83956 sqlite3 *db; /* Main database structure */
83957 AuthContext sContext; /* Authorization context */
83958 NameContext sNC; /* Name context to resolve expressions in */
83959 int iDb; /* Database number */
83960 int memCnt = -1; /* Memory cell used for change counting */
83961 int rcauth; /* Value returned by authorization callback */
83963 #ifndef SQLITE_OMIT_TRIGGER
83964 int isView; /* True if attempting to delete from a view */
83965 Trigger *pTrigger; /* List of table triggers, if required */
83966 #endif
83968 memset(&sContext, 0, sizeof(sContext));
83969 db = pParse->db;
83970 if( pParse->nErr || db->mallocFailed ){
83971 goto delete_from_cleanup;
83973 assert( pTabList->nSrc==1 );
83975 /* Locate the table which we want to delete. This table has to be
83976 ** put in an SrcList structure because some of the subroutines we
83977 ** will be calling are designed to work with multiple tables and expect
83978 ** an SrcList* parameter instead of just a Table* parameter.
83980 pTab = sqlite3SrcListLookup(pParse, pTabList);
83981 if( pTab==0 ) goto delete_from_cleanup;
83983 /* Figure out if we have any triggers and if the table being
83984 ** deleted from is a view
83986 #ifndef SQLITE_OMIT_TRIGGER
83987 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
83988 isView = pTab->pSelect!=0;
83989 #else
83990 # define pTrigger 0
83991 # define isView 0
83992 #endif
83993 #ifdef SQLITE_OMIT_VIEW
83994 # undef isView
83995 # define isView 0
83996 #endif
83998 /* If pTab is really a view, make sure it has been initialized.
84000 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
84001 goto delete_from_cleanup;
84004 if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
84005 goto delete_from_cleanup;
84007 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
84008 assert( iDb<db->nDb );
84009 zDb = db->aDb[iDb].zName;
84010 rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
84011 assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
84012 if( rcauth==SQLITE_DENY ){
84013 goto delete_from_cleanup;
84015 assert(!isView || pTrigger);
84017 /* Assign cursor number to the table and all its indices.
84019 assert( pTabList->nSrc==1 );
84020 iCur = pTabList->a[0].iCursor = pParse->nTab++;
84021 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
84022 pParse->nTab++;
84025 /* Start the view context
84027 if( isView ){
84028 sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
84031 /* Begin generating code.
84033 v = sqlite3GetVdbe(pParse);
84034 if( v==0 ){
84035 goto delete_from_cleanup;
84037 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
84038 sqlite3BeginWriteOperation(pParse, 1, iDb);
84040 /* If we are trying to delete from a view, realize that view into
84041 ** a ephemeral table.
84043 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
84044 if( isView ){
84045 sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
84047 #endif
84049 /* Resolve the column names in the WHERE clause.
84051 memset(&sNC, 0, sizeof(sNC));
84052 sNC.pParse = pParse;
84053 sNC.pSrcList = pTabList;
84054 if( sqlite3ResolveExprNames(&sNC, pWhere) ){
84055 goto delete_from_cleanup;
84058 /* Initialize the counter of the number of rows deleted, if
84059 ** we are counting rows.
84061 if( db->flags & SQLITE_CountRows ){
84062 memCnt = ++pParse->nMem;
84063 sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
84066 #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
84067 /* Special case: A DELETE without a WHERE clause deletes everything.
84068 ** It is easier just to erase the whole table. Prior to version 3.6.5,
84069 ** this optimization caused the row change count (the value returned by
84070 ** API function sqlite3_count_changes) to be set incorrectly. */
84071 if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab)
84072 && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
84074 assert( !isView );
84075 sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
84076 pTab->zName, P4_STATIC);
84077 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
84078 assert( pIdx->pSchema==pTab->pSchema );
84079 sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
84081 }else
84082 #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
84083 /* The usual case: There is a WHERE clause so we have to scan through
84084 ** the table and pick which records to delete.
84087 int iRowSet = ++pParse->nMem; /* Register for rowset of rows to delete */
84088 int iRowid = ++pParse->nMem; /* Used for storing rowid values. */
84089 int regRowid; /* Actual register containing rowids */
84091 /* Collect rowids of every row to be deleted.
84093 sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
84094 pWInfo = sqlite3WhereBegin(
84095 pParse, pTabList, pWhere, 0, 0, WHERE_DUPLICATES_OK
84097 if( pWInfo==0 ) goto delete_from_cleanup;
84098 regRowid = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid);
84099 sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid);
84100 if( db->flags & SQLITE_CountRows ){
84101 sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
84103 sqlite3WhereEnd(pWInfo);
84105 /* Delete every item whose key was written to the list during the
84106 ** database scan. We have to delete items after the scan is complete
84107 ** because deleting an item can change the scan order. */
84108 end = sqlite3VdbeMakeLabel(v);
84110 /* Unless this is a view, open cursors for the table we are
84111 ** deleting from and all its indices. If this is a view, then the
84112 ** only effect this statement has is to fire the INSTEAD OF
84113 ** triggers. */
84114 if( !isView ){
84115 sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
84118 addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid);
84120 /* Delete the row */
84121 #ifndef SQLITE_OMIT_VIRTUALTABLE
84122 if( IsVirtual(pTab) ){
84123 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
84124 sqlite3VtabMakeWritable(pParse, pTab);
84125 sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB);
84126 sqlite3VdbeChangeP5(v, OE_Abort);
84127 sqlite3MayAbort(pParse);
84128 }else
84129 #endif
84131 int count = (pParse->nested==0); /* True to count changes */
84132 sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default);
84135 /* End of the delete loop */
84136 sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
84137 sqlite3VdbeResolveLabel(v, end);
84139 /* Close the cursors open on the table and its indexes. */
84140 if( !isView && !IsVirtual(pTab) ){
84141 for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
84142 sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
84144 sqlite3VdbeAddOp1(v, OP_Close, iCur);
84148 /* Update the sqlite_sequence table by storing the content of the
84149 ** maximum rowid counter values recorded while inserting into
84150 ** autoincrement tables.
84152 if( pParse->nested==0 && pParse->pTriggerTab==0 ){
84153 sqlite3AutoincrementEnd(pParse);
84156 /* Return the number of rows that were deleted. If this routine is
84157 ** generating code because of a call to sqlite3NestedParse(), do not
84158 ** invoke the callback function.
84160 if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
84161 sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
84162 sqlite3VdbeSetNumCols(v, 1);
84163 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
84166 delete_from_cleanup:
84167 sqlite3AuthContextPop(&sContext);
84168 sqlite3SrcListDelete(db, pTabList);
84169 sqlite3ExprDelete(db, pWhere);
84170 return;
84172 /* Make sure "isView" and other macros defined above are undefined. Otherwise
84173 ** thely may interfere with compilation of other functions in this file
84174 ** (or in another file, if this file becomes part of the amalgamation). */
84175 #ifdef isView
84176 #undef isView
84177 #endif
84178 #ifdef pTrigger
84179 #undef pTrigger
84180 #endif
84183 ** This routine generates VDBE code that causes a single row of a
84184 ** single table to be deleted.
84186 ** The VDBE must be in a particular state when this routine is called.
84187 ** These are the requirements:
84189 ** 1. A read/write cursor pointing to pTab, the table containing the row
84190 ** to be deleted, must be opened as cursor number $iCur.
84192 ** 2. Read/write cursors for all indices of pTab must be open as
84193 ** cursor number base+i for the i-th index.
84195 ** 3. The record number of the row to be deleted must be stored in
84196 ** memory cell iRowid.
84198 ** This routine generates code to remove both the table record and all
84199 ** index entries that point to that record.
84201 SQLITE_PRIVATE void sqlite3GenerateRowDelete(
84202 Parse *pParse, /* Parsing context */
84203 Table *pTab, /* Table containing the row to be deleted */
84204 int iCur, /* Cursor number for the table */
84205 int iRowid, /* Memory cell that contains the rowid to delete */
84206 int count, /* If non-zero, increment the row change counter */
84207 Trigger *pTrigger, /* List of triggers to (potentially) fire */
84208 int onconf /* Default ON CONFLICT policy for triggers */
84210 Vdbe *v = pParse->pVdbe; /* Vdbe */
84211 int iOld = 0; /* First register in OLD.* array */
84212 int iLabel; /* Label resolved to end of generated code */
84214 /* Vdbe is guaranteed to have been allocated by this stage. */
84215 assert( v );
84217 /* Seek cursor iCur to the row to delete. If this row no longer exists
84218 ** (this can happen if a trigger program has already deleted it), do
84219 ** not attempt to delete it or fire any DELETE triggers. */
84220 iLabel = sqlite3VdbeMakeLabel(v);
84221 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
84223 /* If there are any triggers to fire, allocate a range of registers to
84224 ** use for the old.* references in the triggers. */
84225 if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
84226 u32 mask; /* Mask of OLD.* columns in use */
84227 int iCol; /* Iterator used while populating OLD.* */
84229 /* TODO: Could use temporary registers here. Also could attempt to
84230 ** avoid copying the contents of the rowid register. */
84231 mask = sqlite3TriggerColmask(
84232 pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
84234 mask |= sqlite3FkOldmask(pParse, pTab);
84235 iOld = pParse->nMem+1;
84236 pParse->nMem += (1 + pTab->nCol);
84238 /* Populate the OLD.* pseudo-table register array. These values will be
84239 ** used by any BEFORE and AFTER triggers that exist. */
84240 sqlite3VdbeAddOp2(v, OP_Copy, iRowid, iOld);
84241 for(iCol=0; iCol<pTab->nCol; iCol++){
84242 if( mask==0xffffffff || mask&(1<<iCol) ){
84243 sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol, iOld+iCol+1);
84247 /* Invoke BEFORE DELETE trigger programs. */
84248 sqlite3CodeRowTrigger(pParse, pTrigger,
84249 TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
84252 /* Seek the cursor to the row to be deleted again. It may be that
84253 ** the BEFORE triggers coded above have already removed the row
84254 ** being deleted. Do not attempt to delete the row a second time, and
84255 ** do not fire AFTER triggers. */
84256 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
84258 /* Do FK processing. This call checks that any FK constraints that
84259 ** refer to this table (i.e. constraints attached to other tables)
84260 ** are not violated by deleting this row. */
84261 sqlite3FkCheck(pParse, pTab, iOld, 0);
84264 /* Delete the index and table entries. Skip this step if pTab is really
84265 ** a view (in which case the only effect of the DELETE statement is to
84266 ** fire the INSTEAD OF triggers). */
84267 if( pTab->pSelect==0 ){
84268 sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
84269 sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
84270 if( count ){
84271 sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
84275 /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
84276 ** handle rows (possibly in other tables) that refer via a foreign key
84277 ** to the row just deleted. */
84278 sqlite3FkActions(pParse, pTab, 0, iOld);
84280 /* Invoke AFTER DELETE trigger programs. */
84281 sqlite3CodeRowTrigger(pParse, pTrigger,
84282 TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
84285 /* Jump here if the row had already been deleted before any BEFORE
84286 ** trigger programs were invoked. Or if a trigger program throws a
84287 ** RAISE(IGNORE) exception. */
84288 sqlite3VdbeResolveLabel(v, iLabel);
84292 ** This routine generates VDBE code that causes the deletion of all
84293 ** index entries associated with a single row of a single table.
84295 ** The VDBE must be in a particular state when this routine is called.
84296 ** These are the requirements:
84298 ** 1. A read/write cursor pointing to pTab, the table containing the row
84299 ** to be deleted, must be opened as cursor number "iCur".
84301 ** 2. Read/write cursors for all indices of pTab must be open as
84302 ** cursor number iCur+i for the i-th index.
84304 ** 3. The "iCur" cursor must be pointing to the row that is to be
84305 ** deleted.
84307 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
84308 Parse *pParse, /* Parsing and code generating context */
84309 Table *pTab, /* Table containing the row to be deleted */
84310 int iCur, /* Cursor number for the table */
84311 int *aRegIdx /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
84313 int i;
84314 Index *pIdx;
84315 int r1;
84317 for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
84318 if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
84319 r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0);
84320 sqlite3VdbeAddOp3(pParse->pVdbe, OP_IdxDelete, iCur+i, r1,pIdx->nColumn+1);
84325 ** Generate code that will assemble an index key and put it in register
84326 ** regOut. The key with be for index pIdx which is an index on pTab.
84327 ** iCur is the index of a cursor open on the pTab table and pointing to
84328 ** the entry that needs indexing.
84330 ** Return a register number which is the first in a block of
84331 ** registers that holds the elements of the index key. The
84332 ** block of registers has already been deallocated by the time
84333 ** this routine returns.
84335 SQLITE_PRIVATE int sqlite3GenerateIndexKey(
84336 Parse *pParse, /* Parsing context */
84337 Index *pIdx, /* The index for which to generate a key */
84338 int iCur, /* Cursor number for the pIdx->pTable table */
84339 int regOut, /* Write the new index key to this register */
84340 int doMakeRec /* Run the OP_MakeRecord instruction if true */
84342 Vdbe *v = pParse->pVdbe;
84343 int j;
84344 Table *pTab = pIdx->pTable;
84345 int regBase;
84346 int nCol;
84348 nCol = pIdx->nColumn;
84349 regBase = sqlite3GetTempRange(pParse, nCol+1);
84350 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
84351 for(j=0; j<nCol; j++){
84352 int idx = pIdx->aiColumn[j];
84353 if( idx==pTab->iPKey ){
84354 sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);
84355 }else{
84356 sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);
84357 sqlite3ColumnDefault(v, pTab, idx, -1);
84360 if( doMakeRec ){
84361 const char *zAff;
84362 if( pTab->pSelect || (pParse->db->flags & SQLITE_IdxRealAsInt)!=0 ){
84363 zAff = 0;
84364 }else{
84365 zAff = sqlite3IndexAffinityStr(v, pIdx);
84367 sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);
84368 sqlite3VdbeChangeP4(v, -1, zAff, P4_TRANSIENT);
84370 sqlite3ReleaseTempRange(pParse, regBase, nCol+1);
84371 return regBase;
84374 /************** End of delete.c **********************************************/
84375 /************** Begin file func.c ********************************************/
84377 ** 2002 February 23
84379 ** The author disclaims copyright to this source code. In place of
84380 ** a legal notice, here is a blessing:
84382 ** May you do good and not evil.
84383 ** May you find forgiveness for yourself and forgive others.
84384 ** May you share freely, never taking more than you give.
84386 *************************************************************************
84387 ** This file contains the C functions that implement various SQL
84388 ** functions of SQLite.
84390 ** There is only one exported symbol in this file - the function
84391 ** sqliteRegisterBuildinFunctions() found at the bottom of the file.
84392 ** All other code has file scope.
84394 /* #include <stdlib.h> */
84395 /* #include <assert.h> */
84398 ** Return the collating function associated with a function.
84400 static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
84401 return context->pColl;
84405 ** Implementation of the non-aggregate min() and max() functions
84407 static void minmaxFunc(
84408 sqlite3_context *context,
84409 int argc,
84410 sqlite3_value **argv
84412 int i;
84413 int mask; /* 0 for min() or 0xffffffff for max() */
84414 int iBest;
84415 CollSeq *pColl;
84417 assert( argc>1 );
84418 mask = sqlite3_user_data(context)==0 ? 0 : -1;
84419 pColl = sqlite3GetFuncCollSeq(context);
84420 assert( pColl );
84421 assert( mask==-1 || mask==0 );
84422 iBest = 0;
84423 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
84424 for(i=1; i<argc; i++){
84425 if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
84426 if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
84427 testcase( mask==0 );
84428 iBest = i;
84431 sqlite3_result_value(context, argv[iBest]);
84435 ** Return the type of the argument.
84437 static void typeofFunc(
84438 sqlite3_context *context,
84439 int NotUsed,
84440 sqlite3_value **argv
84442 const char *z = 0;
84443 UNUSED_PARAMETER(NotUsed);
84444 switch( sqlite3_value_type(argv[0]) ){
84445 case SQLITE_INTEGER: z = "integer"; break;
84446 case SQLITE_TEXT: z = "text"; break;
84447 case SQLITE_FLOAT: z = "real"; break;
84448 case SQLITE_BLOB: z = "blob"; break;
84449 default: z = "null"; break;
84451 sqlite3_result_text(context, z, -1, SQLITE_STATIC);
84456 ** Implementation of the length() function
84458 static void lengthFunc(
84459 sqlite3_context *context,
84460 int argc,
84461 sqlite3_value **argv
84463 int len;
84465 assert( argc==1 );
84466 UNUSED_PARAMETER(argc);
84467 switch( sqlite3_value_type(argv[0]) ){
84468 case SQLITE_BLOB:
84469 case SQLITE_INTEGER:
84470 case SQLITE_FLOAT: {
84471 sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
84472 break;
84474 case SQLITE_TEXT: {
84475 const unsigned char *z = sqlite3_value_text(argv[0]);
84476 if( z==0 ) return;
84477 len = 0;
84478 while( *z ){
84479 len++;
84480 SQLITE_SKIP_UTF8(z);
84482 sqlite3_result_int(context, len);
84483 break;
84485 default: {
84486 sqlite3_result_null(context);
84487 break;
84493 ** Implementation of the abs() function.
84495 ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
84496 ** the numeric argument X.
84498 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
84499 assert( argc==1 );
84500 UNUSED_PARAMETER(argc);
84501 switch( sqlite3_value_type(argv[0]) ){
84502 case SQLITE_INTEGER: {
84503 i64 iVal = sqlite3_value_int64(argv[0]);
84504 if( iVal<0 ){
84505 if( (iVal<<1)==0 ){
84506 /* IMP: R-35460-15084 If X is the integer -9223372036854775807 then
84507 ** abs(X) throws an integer overflow error since there is no
84508 ** equivalent positive 64-bit two complement value. */
84509 sqlite3_result_error(context, "integer overflow", -1);
84510 return;
84512 iVal = -iVal;
84514 sqlite3_result_int64(context, iVal);
84515 break;
84517 case SQLITE_NULL: {
84518 /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
84519 sqlite3_result_null(context);
84520 break;
84522 default: {
84523 /* Because sqlite3_value_double() returns 0.0 if the argument is not
84524 ** something that can be converted into a number, we have:
84525 ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that
84526 ** cannot be converted to a numeric value.
84528 double rVal = sqlite3_value_double(argv[0]);
84529 if( rVal<0 ) rVal = -rVal;
84530 sqlite3_result_double(context, rVal);
84531 break;
84537 ** Implementation of the substr() function.
84539 ** substr(x,p1,p2) returns p2 characters of x[] beginning with p1.
84540 ** p1 is 1-indexed. So substr(x,1,1) returns the first character
84541 ** of x. If x is text, then we actually count UTF-8 characters.
84542 ** If x is a blob, then we count bytes.
84544 ** If p1 is negative, then we begin abs(p1) from the end of x[].
84546 ** If p2 is negative, return the p2 characters preceeding p1.
84548 static void substrFunc(
84549 sqlite3_context *context,
84550 int argc,
84551 sqlite3_value **argv
84553 const unsigned char *z;
84554 const unsigned char *z2;
84555 int len;
84556 int p0type;
84557 i64 p1, p2;
84558 int negP2 = 0;
84560 assert( argc==3 || argc==2 );
84561 if( sqlite3_value_type(argv[1])==SQLITE_NULL
84562 || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
84564 return;
84566 p0type = sqlite3_value_type(argv[0]);
84567 p1 = sqlite3_value_int(argv[1]);
84568 if( p0type==SQLITE_BLOB ){
84569 len = sqlite3_value_bytes(argv[0]);
84570 z = sqlite3_value_blob(argv[0]);
84571 if( z==0 ) return;
84572 assert( len==sqlite3_value_bytes(argv[0]) );
84573 }else{
84574 z = sqlite3_value_text(argv[0]);
84575 if( z==0 ) return;
84576 len = 0;
84577 if( p1<0 ){
84578 for(z2=z; *z2; len++){
84579 SQLITE_SKIP_UTF8(z2);
84583 if( argc==3 ){
84584 p2 = sqlite3_value_int(argv[2]);
84585 if( p2<0 ){
84586 p2 = -p2;
84587 negP2 = 1;
84589 }else{
84590 p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
84592 if( p1<0 ){
84593 p1 += len;
84594 if( p1<0 ){
84595 p2 += p1;
84596 if( p2<0 ) p2 = 0;
84597 p1 = 0;
84599 }else if( p1>0 ){
84600 p1--;
84601 }else if( p2>0 ){
84602 p2--;
84604 if( negP2 ){
84605 p1 -= p2;
84606 if( p1<0 ){
84607 p2 += p1;
84608 p1 = 0;
84611 assert( p1>=0 && p2>=0 );
84612 if( p0type!=SQLITE_BLOB ){
84613 while( *z && p1 ){
84614 SQLITE_SKIP_UTF8(z);
84615 p1--;
84617 for(z2=z; *z2 && p2; p2--){
84618 SQLITE_SKIP_UTF8(z2);
84620 sqlite3_result_text(context, (char*)z, (int)(z2-z), SQLITE_TRANSIENT);
84621 }else{
84622 if( p1+p2>len ){
84623 p2 = len-p1;
84624 if( p2<0 ) p2 = 0;
84626 sqlite3_result_blob(context, (char*)&z[p1], (int)p2, SQLITE_TRANSIENT);
84631 ** Implementation of the round() function
84633 #ifndef SQLITE_OMIT_FLOATING_POINT
84634 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
84635 int n = 0;
84636 double r;
84637 char *zBuf;
84638 assert( argc==1 || argc==2 );
84639 if( argc==2 ){
84640 if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
84641 n = sqlite3_value_int(argv[1]);
84642 if( n>30 ) n = 30;
84643 if( n<0 ) n = 0;
84645 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
84646 r = sqlite3_value_double(argv[0]);
84647 /* If Y==0 and X will fit in a 64-bit int,
84648 ** handle the rounding directly,
84649 ** otherwise use printf.
84651 if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
84652 r = (double)((sqlite_int64)(r+0.5));
84653 }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
84654 r = -(double)((sqlite_int64)((-r)+0.5));
84655 }else{
84656 zBuf = sqlite3_mprintf("%.*f",n,r);
84657 if( zBuf==0 ){
84658 sqlite3_result_error_nomem(context);
84659 return;
84661 sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
84662 sqlite3_free(zBuf);
84664 sqlite3_result_double(context, r);
84666 #endif
84669 ** Allocate nByte bytes of space using sqlite3_malloc(). If the
84670 ** allocation fails, call sqlite3_result_error_nomem() to notify
84671 ** the database handle that malloc() has failed and return NULL.
84672 ** If nByte is larger than the maximum string or blob length, then
84673 ** raise an SQLITE_TOOBIG exception and return NULL.
84675 static void *contextMalloc(sqlite3_context *context, i64 nByte){
84676 char *z;
84677 sqlite3 *db = sqlite3_context_db_handle(context);
84678 assert( nByte>0 );
84679 testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
84680 testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
84681 if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
84682 sqlite3_result_error_toobig(context);
84683 z = 0;
84684 }else{
84685 z = sqlite3Malloc((int)nByte);
84686 if( !z ){
84687 sqlite3_result_error_nomem(context);
84690 return z;
84694 ** Implementation of the upper() and lower() SQL functions.
84696 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
84697 char *z1;
84698 const char *z2;
84699 int i, n;
84700 UNUSED_PARAMETER(argc);
84701 z2 = (char*)sqlite3_value_text(argv[0]);
84702 n = sqlite3_value_bytes(argv[0]);
84703 /* Verify that the call to _bytes() does not invalidate the _text() pointer */
84704 assert( z2==(char*)sqlite3_value_text(argv[0]) );
84705 if( z2 ){
84706 z1 = contextMalloc(context, ((i64)n)+1);
84707 if( z1 ){
84708 for(i=0; i<n; i++){
84709 z1[i] = (char)sqlite3Toupper(z2[i]);
84711 sqlite3_result_text(context, z1, n, sqlite3_free);
84715 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
84716 char *z1;
84717 const char *z2;
84718 int i, n;
84719 UNUSED_PARAMETER(argc);
84720 z2 = (char*)sqlite3_value_text(argv[0]);
84721 n = sqlite3_value_bytes(argv[0]);
84722 /* Verify that the call to _bytes() does not invalidate the _text() pointer */
84723 assert( z2==(char*)sqlite3_value_text(argv[0]) );
84724 if( z2 ){
84725 z1 = contextMalloc(context, ((i64)n)+1);
84726 if( z1 ){
84727 for(i=0; i<n; i++){
84728 z1[i] = sqlite3Tolower(z2[i]);
84730 sqlite3_result_text(context, z1, n, sqlite3_free);
84736 #if 0 /* This function is never used. */
84738 ** The COALESCE() and IFNULL() functions used to be implemented as shown
84739 ** here. But now they are implemented as VDBE code so that unused arguments
84740 ** do not have to be computed. This legacy implementation is retained as
84741 ** comment.
84744 ** Implementation of the IFNULL(), NVL(), and COALESCE() functions.
84745 ** All three do the same thing. They return the first non-NULL
84746 ** argument.
84748 static void ifnullFunc(
84749 sqlite3_context *context,
84750 int argc,
84751 sqlite3_value **argv
84753 int i;
84754 for(i=0; i<argc; i++){
84755 if( SQLITE_NULL!=sqlite3_value_type(argv[i]) ){
84756 sqlite3_result_value(context, argv[i]);
84757 break;
84761 #endif /* NOT USED */
84762 #define ifnullFunc versionFunc /* Substitute function - never called */
84765 ** Implementation of random(). Return a random integer.
84767 static void randomFunc(
84768 sqlite3_context *context,
84769 int NotUsed,
84770 sqlite3_value **NotUsed2
84772 sqlite_int64 r;
84773 UNUSED_PARAMETER2(NotUsed, NotUsed2);
84774 sqlite3_randomness(sizeof(r), &r);
84775 if( r<0 ){
84776 /* We need to prevent a random number of 0x8000000000000000
84777 ** (or -9223372036854775808) since when you do abs() of that
84778 ** number of you get the same value back again. To do this
84779 ** in a way that is testable, mask the sign bit off of negative
84780 ** values, resulting in a positive value. Then take the
84781 ** 2s complement of that positive value. The end result can
84782 ** therefore be no less than -9223372036854775807.
84784 r = -(r ^ (((sqlite3_int64)1)<<63));
84786 sqlite3_result_int64(context, r);
84790 ** Implementation of randomblob(N). Return a random blob
84791 ** that is N bytes long.
84793 static void randomBlob(
84794 sqlite3_context *context,
84795 int argc,
84796 sqlite3_value **argv
84798 int n;
84799 unsigned char *p;
84800 assert( argc==1 );
84801 UNUSED_PARAMETER(argc);
84802 n = sqlite3_value_int(argv[0]);
84803 if( n<1 ){
84804 n = 1;
84806 p = contextMalloc(context, n);
84807 if( p ){
84808 sqlite3_randomness(n, p);
84809 sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
84814 ** Implementation of the last_insert_rowid() SQL function. The return
84815 ** value is the same as the sqlite3_last_insert_rowid() API function.
84817 static void last_insert_rowid(
84818 sqlite3_context *context,
84819 int NotUsed,
84820 sqlite3_value **NotUsed2
84822 sqlite3 *db = sqlite3_context_db_handle(context);
84823 UNUSED_PARAMETER2(NotUsed, NotUsed2);
84824 /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
84825 ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
84826 ** function. */
84827 sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
84831 ** Implementation of the changes() SQL function.
84833 ** IMP: R-62073-11209 The changes() SQL function is a wrapper
84834 ** around the sqlite3_changes() C/C++ function and hence follows the same
84835 ** rules for counting changes.
84837 static void changes(
84838 sqlite3_context *context,
84839 int NotUsed,
84840 sqlite3_value **NotUsed2
84842 sqlite3 *db = sqlite3_context_db_handle(context);
84843 UNUSED_PARAMETER2(NotUsed, NotUsed2);
84844 sqlite3_result_int(context, sqlite3_changes(db));
84848 ** Implementation of the total_changes() SQL function. The return value is
84849 ** the same as the sqlite3_total_changes() API function.
84851 static void total_changes(
84852 sqlite3_context *context,
84853 int NotUsed,
84854 sqlite3_value **NotUsed2
84856 sqlite3 *db = sqlite3_context_db_handle(context);
84857 UNUSED_PARAMETER2(NotUsed, NotUsed2);
84858 /* IMP: R-52756-41993 This function is a wrapper around the
84859 ** sqlite3_total_changes() C/C++ interface. */
84860 sqlite3_result_int(context, sqlite3_total_changes(db));
84864 ** A structure defining how to do GLOB-style comparisons.
84866 struct compareInfo {
84867 u8 matchAll;
84868 u8 matchOne;
84869 u8 matchSet;
84870 u8 noCase;
84874 ** For LIKE and GLOB matching on EBCDIC machines, assume that every
84875 ** character is exactly one byte in size. Also, all characters are
84876 ** able to participate in upper-case-to-lower-case mappings in EBCDIC
84877 ** whereas only characters less than 0x80 do in ASCII.
84879 #if defined(SQLITE_EBCDIC)
84880 # define sqlite3Utf8Read(A,C) (*(A++))
84881 # define GlogUpperToLower(A) A = sqlite3UpperToLower[A]
84882 #else
84883 # define GlogUpperToLower(A) if( !((A)&~0x7f) ){ A = sqlite3UpperToLower[A]; }
84884 #endif
84886 static const struct compareInfo globInfo = { '*', '?', '[', 0 };
84887 /* The correct SQL-92 behavior is for the LIKE operator to ignore
84888 ** case. Thus 'a' LIKE 'A' would be true. */
84889 static const struct compareInfo likeInfoNorm = { '%', '_', 0, 1 };
84890 /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
84891 ** is case sensitive causing 'a' LIKE 'A' to be false */
84892 static const struct compareInfo likeInfoAlt = { '%', '_', 0, 0 };
84895 ** Compare two UTF-8 strings for equality where the first string can
84896 ** potentially be a "glob" expression. Return true (1) if they
84897 ** are the same and false (0) if they are different.
84899 ** Globbing rules:
84901 ** '*' Matches any sequence of zero or more characters.
84903 ** '?' Matches exactly one character.
84905 ** [...] Matches one character from the enclosed list of
84906 ** characters.
84908 ** [^...] Matches one character not in the enclosed list.
84910 ** With the [...] and [^...] matching, a ']' character can be included
84911 ** in the list by making it the first character after '[' or '^'. A
84912 ** range of characters can be specified using '-'. Example:
84913 ** "[a-z]" matches any single lower-case letter. To match a '-', make
84914 ** it the last character in the list.
84916 ** This routine is usually quick, but can be N**2 in the worst case.
84918 ** Hints: to match '*' or '?', put them in "[]". Like this:
84920 ** abc[*]xyz Matches "abc*xyz" only
84922 static int patternCompare(
84923 const u8 *zPattern, /* The glob pattern */
84924 const u8 *zString, /* The string to compare against the glob */
84925 const struct compareInfo *pInfo, /* Information about how to do the compare */
84926 u32 esc /* The escape character */
84928 u32 c, c2;
84929 int invert;
84930 int seen;
84931 u8 matchOne = pInfo->matchOne;
84932 u8 matchAll = pInfo->matchAll;
84933 u8 matchSet = pInfo->matchSet;
84934 u8 noCase = pInfo->noCase;
84935 int prevEscape = 0; /* True if the previous character was 'escape' */
84937 while( (c = sqlite3Utf8Read(zPattern,&zPattern))!=0 ){
84938 if( !prevEscape && c==matchAll ){
84939 while( (c=sqlite3Utf8Read(zPattern,&zPattern)) == matchAll
84940 || c == matchOne ){
84941 if( c==matchOne && sqlite3Utf8Read(zString, &zString)==0 ){
84942 return 0;
84945 if( c==0 ){
84946 return 1;
84947 }else if( c==esc ){
84948 c = sqlite3Utf8Read(zPattern, &zPattern);
84949 if( c==0 ){
84950 return 0;
84952 }else if( c==matchSet ){
84953 assert( esc==0 ); /* This is GLOB, not LIKE */
84954 assert( matchSet<0x80 ); /* '[' is a single-byte character */
84955 while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
84956 SQLITE_SKIP_UTF8(zString);
84958 return *zString!=0;
84960 while( (c2 = sqlite3Utf8Read(zString,&zString))!=0 ){
84961 if( noCase ){
84962 GlogUpperToLower(c2);
84963 GlogUpperToLower(c);
84964 while( c2 != 0 && c2 != c ){
84965 c2 = sqlite3Utf8Read(zString, &zString);
84966 GlogUpperToLower(c2);
84968 }else{
84969 while( c2 != 0 && c2 != c ){
84970 c2 = sqlite3Utf8Read(zString, &zString);
84973 if( c2==0 ) return 0;
84974 if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
84976 return 0;
84977 }else if( !prevEscape && c==matchOne ){
84978 if( sqlite3Utf8Read(zString, &zString)==0 ){
84979 return 0;
84981 }else if( c==matchSet ){
84982 u32 prior_c = 0;
84983 assert( esc==0 ); /* This only occurs for GLOB, not LIKE */
84984 seen = 0;
84985 invert = 0;
84986 c = sqlite3Utf8Read(zString, &zString);
84987 if( c==0 ) return 0;
84988 c2 = sqlite3Utf8Read(zPattern, &zPattern);
84989 if( c2=='^' ){
84990 invert = 1;
84991 c2 = sqlite3Utf8Read(zPattern, &zPattern);
84993 if( c2==']' ){
84994 if( c==']' ) seen = 1;
84995 c2 = sqlite3Utf8Read(zPattern, &zPattern);
84997 while( c2 && c2!=']' ){
84998 if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
84999 c2 = sqlite3Utf8Read(zPattern, &zPattern);
85000 if( c>=prior_c && c<=c2 ) seen = 1;
85001 prior_c = 0;
85002 }else{
85003 if( c==c2 ){
85004 seen = 1;
85006 prior_c = c2;
85008 c2 = sqlite3Utf8Read(zPattern, &zPattern);
85010 if( c2==0 || (seen ^ invert)==0 ){
85011 return 0;
85013 }else if( esc==c && !prevEscape ){
85014 prevEscape = 1;
85015 }else{
85016 c2 = sqlite3Utf8Read(zString, &zString);
85017 if( noCase ){
85018 GlogUpperToLower(c);
85019 GlogUpperToLower(c2);
85021 if( c!=c2 ){
85022 return 0;
85024 prevEscape = 0;
85027 return *zString==0;
85031 ** Count the number of times that the LIKE operator (or GLOB which is
85032 ** just a variation of LIKE) gets called. This is used for testing
85033 ** only.
85035 #ifdef SQLITE_TEST
85036 SQLITE_API int sqlite3_like_count = 0;
85037 #endif
85041 ** Implementation of the like() SQL function. This function implements
85042 ** the build-in LIKE operator. The first argument to the function is the
85043 ** pattern and the second argument is the string. So, the SQL statements:
85045 ** A LIKE B
85047 ** is implemented as like(B,A).
85049 ** This same function (with a different compareInfo structure) computes
85050 ** the GLOB operator.
85052 static void likeFunc(
85053 sqlite3_context *context,
85054 int argc,
85055 sqlite3_value **argv
85057 const unsigned char *zA, *zB;
85058 u32 escape = 0;
85059 int nPat;
85060 sqlite3 *db = sqlite3_context_db_handle(context);
85062 zB = sqlite3_value_text(argv[0]);
85063 zA = sqlite3_value_text(argv[1]);
85065 /* Limit the length of the LIKE or GLOB pattern to avoid problems
85066 ** of deep recursion and N*N behavior in patternCompare().
85068 nPat = sqlite3_value_bytes(argv[0]);
85069 testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
85070 testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
85071 if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
85072 sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
85073 return;
85075 assert( zB==sqlite3_value_text(argv[0]) ); /* Encoding did not change */
85077 if( argc==3 ){
85078 /* The escape character string must consist of a single UTF-8 character.
85079 ** Otherwise, return an error.
85081 const unsigned char *zEsc = sqlite3_value_text(argv[2]);
85082 if( zEsc==0 ) return;
85083 if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
85084 sqlite3_result_error(context,
85085 "ESCAPE expression must be a single character", -1);
85086 return;
85088 escape = sqlite3Utf8Read(zEsc, &zEsc);
85090 if( zA && zB ){
85091 struct compareInfo *pInfo = sqlite3_user_data(context);
85092 #ifdef SQLITE_TEST
85093 sqlite3_like_count++;
85094 #endif
85096 sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
85101 ** Implementation of the NULLIF(x,y) function. The result is the first
85102 ** argument if the arguments are different. The result is NULL if the
85103 ** arguments are equal to each other.
85105 static void nullifFunc(
85106 sqlite3_context *context,
85107 int NotUsed,
85108 sqlite3_value **argv
85110 CollSeq *pColl = sqlite3GetFuncCollSeq(context);
85111 UNUSED_PARAMETER(NotUsed);
85112 if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
85113 sqlite3_result_value(context, argv[0]);
85118 ** Implementation of the sqlite_version() function. The result is the version
85119 ** of the SQLite library that is running.
85121 static void versionFunc(
85122 sqlite3_context *context,
85123 int NotUsed,
85124 sqlite3_value **NotUsed2
85126 UNUSED_PARAMETER2(NotUsed, NotUsed2);
85127 /* IMP: R-48699-48617 This function is an SQL wrapper around the
85128 ** sqlite3_libversion() C-interface. */
85129 sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
85133 ** Implementation of the sqlite_source_id() function. The result is a string
85134 ** that identifies the particular version of the source code used to build
85135 ** SQLite.
85137 static void sourceidFunc(
85138 sqlite3_context *context,
85139 int NotUsed,
85140 sqlite3_value **NotUsed2
85142 UNUSED_PARAMETER2(NotUsed, NotUsed2);
85143 /* IMP: R-24470-31136 This function is an SQL wrapper around the
85144 ** sqlite3_sourceid() C interface. */
85145 sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
85149 ** Implementation of the sqlite_log() function. This is a wrapper around
85150 ** sqlite3_log(). The return value is NULL. The function exists purely for
85151 ** its side-effects.
85153 static void errlogFunc(
85154 sqlite3_context *context,
85155 int argc,
85156 sqlite3_value **argv
85158 UNUSED_PARAMETER(argc);
85159 UNUSED_PARAMETER(context);
85160 sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
85164 ** Implementation of the sqlite_compileoption_used() function.
85165 ** The result is an integer that identifies if the compiler option
85166 ** was used to build SQLite.
85168 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
85169 static void compileoptionusedFunc(
85170 sqlite3_context *context,
85171 int argc,
85172 sqlite3_value **argv
85174 const char *zOptName;
85175 assert( argc==1 );
85176 UNUSED_PARAMETER(argc);
85177 /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
85178 ** function is a wrapper around the sqlite3_compileoption_used() C/C++
85179 ** function.
85181 if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
85182 sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
85185 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
85188 ** Implementation of the sqlite_compileoption_get() function.
85189 ** The result is a string that identifies the compiler options
85190 ** used to build SQLite.
85192 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
85193 static void compileoptiongetFunc(
85194 sqlite3_context *context,
85195 int argc,
85196 sqlite3_value **argv
85198 int n;
85199 assert( argc==1 );
85200 UNUSED_PARAMETER(argc);
85201 /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
85202 ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
85204 n = sqlite3_value_int(argv[0]);
85205 sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
85207 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
85209 /* Array for converting from half-bytes (nybbles) into ASCII hex
85210 ** digits. */
85211 static const char hexdigits[] = {
85212 '0', '1', '2', '3', '4', '5', '6', '7',
85213 '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
85217 ** EXPERIMENTAL - This is not an official function. The interface may
85218 ** change. This function may disappear. Do not write code that depends
85219 ** on this function.
85221 ** Implementation of the QUOTE() function. This function takes a single
85222 ** argument. If the argument is numeric, the return value is the same as
85223 ** the argument. If the argument is NULL, the return value is the string
85224 ** "NULL". Otherwise, the argument is enclosed in single quotes with
85225 ** single-quote escapes.
85227 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
85228 assert( argc==1 );
85229 UNUSED_PARAMETER(argc);
85230 switch( sqlite3_value_type(argv[0]) ){
85231 case SQLITE_INTEGER:
85232 case SQLITE_FLOAT: {
85233 sqlite3_result_value(context, argv[0]);
85234 break;
85236 case SQLITE_BLOB: {
85237 char *zText = 0;
85238 char const *zBlob = sqlite3_value_blob(argv[0]);
85239 int nBlob = sqlite3_value_bytes(argv[0]);
85240 assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
85241 zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
85242 if( zText ){
85243 int i;
85244 for(i=0; i<nBlob; i++){
85245 zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
85246 zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
85248 zText[(nBlob*2)+2] = '\'';
85249 zText[(nBlob*2)+3] = '\0';
85250 zText[0] = 'X';
85251 zText[1] = '\'';
85252 sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
85253 sqlite3_free(zText);
85255 break;
85257 case SQLITE_TEXT: {
85258 int i,j;
85259 u64 n;
85260 const unsigned char *zArg = sqlite3_value_text(argv[0]);
85261 char *z;
85263 if( zArg==0 ) return;
85264 for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
85265 z = contextMalloc(context, ((i64)i)+((i64)n)+3);
85266 if( z ){
85267 z[0] = '\'';
85268 for(i=0, j=1; zArg[i]; i++){
85269 z[j++] = zArg[i];
85270 if( zArg[i]=='\'' ){
85271 z[j++] = '\'';
85274 z[j++] = '\'';
85275 z[j] = 0;
85276 sqlite3_result_text(context, z, j, sqlite3_free);
85278 break;
85280 default: {
85281 assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
85282 sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
85283 break;
85289 ** The hex() function. Interpret the argument as a blob. Return
85290 ** a hexadecimal rendering as text.
85292 static void hexFunc(
85293 sqlite3_context *context,
85294 int argc,
85295 sqlite3_value **argv
85297 int i, n;
85298 const unsigned char *pBlob;
85299 char *zHex, *z;
85300 assert( argc==1 );
85301 UNUSED_PARAMETER(argc);
85302 pBlob = sqlite3_value_blob(argv[0]);
85303 n = sqlite3_value_bytes(argv[0]);
85304 assert( pBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
85305 z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
85306 if( zHex ){
85307 for(i=0; i<n; i++, pBlob++){
85308 unsigned char c = *pBlob;
85309 *(z++) = hexdigits[(c>>4)&0xf];
85310 *(z++) = hexdigits[c&0xf];
85312 *z = 0;
85313 sqlite3_result_text(context, zHex, n*2, sqlite3_free);
85318 ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
85320 static void zeroblobFunc(
85321 sqlite3_context *context,
85322 int argc,
85323 sqlite3_value **argv
85325 i64 n;
85326 sqlite3 *db = sqlite3_context_db_handle(context);
85327 assert( argc==1 );
85328 UNUSED_PARAMETER(argc);
85329 n = sqlite3_value_int64(argv[0]);
85330 testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
85331 testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
85332 if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
85333 sqlite3_result_error_toobig(context);
85334 }else{
85335 sqlite3_result_zeroblob(context, (int)n); /* IMP: R-00293-64994 */
85340 ** The replace() function. Three arguments are all strings: call
85341 ** them A, B, and C. The result is also a string which is derived
85342 ** from A by replacing every occurance of B with C. The match
85343 ** must be exact. Collating sequences are not used.
85345 static void replaceFunc(
85346 sqlite3_context *context,
85347 int argc,
85348 sqlite3_value **argv
85350 const unsigned char *zStr; /* The input string A */
85351 const unsigned char *zPattern; /* The pattern string B */
85352 const unsigned char *zRep; /* The replacement string C */
85353 unsigned char *zOut; /* The output */
85354 int nStr; /* Size of zStr */
85355 int nPattern; /* Size of zPattern */
85356 int nRep; /* Size of zRep */
85357 i64 nOut; /* Maximum size of zOut */
85358 int loopLimit; /* Last zStr[] that might match zPattern[] */
85359 int i, j; /* Loop counters */
85361 assert( argc==3 );
85362 UNUSED_PARAMETER(argc);
85363 zStr = sqlite3_value_text(argv[0]);
85364 if( zStr==0 ) return;
85365 nStr = sqlite3_value_bytes(argv[0]);
85366 assert( zStr==sqlite3_value_text(argv[0]) ); /* No encoding change */
85367 zPattern = sqlite3_value_text(argv[1]);
85368 if( zPattern==0 ){
85369 assert( sqlite3_value_type(argv[1])==SQLITE_NULL
85370 || sqlite3_context_db_handle(context)->mallocFailed );
85371 return;
85373 if( zPattern[0]==0 ){
85374 assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
85375 sqlite3_result_value(context, argv[0]);
85376 return;
85378 nPattern = sqlite3_value_bytes(argv[1]);
85379 assert( zPattern==sqlite3_value_text(argv[1]) ); /* No encoding change */
85380 zRep = sqlite3_value_text(argv[2]);
85381 if( zRep==0 ) return;
85382 nRep = sqlite3_value_bytes(argv[2]);
85383 assert( zRep==sqlite3_value_text(argv[2]) );
85384 nOut = nStr + 1;
85385 assert( nOut<SQLITE_MAX_LENGTH );
85386 zOut = contextMalloc(context, (i64)nOut);
85387 if( zOut==0 ){
85388 return;
85390 loopLimit = nStr - nPattern;
85391 for(i=j=0; i<=loopLimit; i++){
85392 if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
85393 zOut[j++] = zStr[i];
85394 }else{
85395 u8 *zOld;
85396 sqlite3 *db = sqlite3_context_db_handle(context);
85397 nOut += nRep - nPattern;
85398 testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
85399 testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
85400 if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
85401 sqlite3_result_error_toobig(context);
85402 sqlite3_free(zOut);
85403 return;
85405 zOld = zOut;
85406 zOut = sqlite3_realloc(zOut, (int)nOut);
85407 if( zOut==0 ){
85408 sqlite3_result_error_nomem(context);
85409 sqlite3_free(zOld);
85410 return;
85412 memcpy(&zOut[j], zRep, nRep);
85413 j += nRep;
85414 i += nPattern-1;
85417 assert( j+nStr-i+1==nOut );
85418 memcpy(&zOut[j], &zStr[i], nStr-i);
85419 j += nStr - i;
85420 assert( j<=nOut );
85421 zOut[j] = 0;
85422 sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
85426 ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
85427 ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
85429 static void trimFunc(
85430 sqlite3_context *context,
85431 int argc,
85432 sqlite3_value **argv
85434 const unsigned char *zIn; /* Input string */
85435 const unsigned char *zCharSet; /* Set of characters to trim */
85436 int nIn; /* Number of bytes in input */
85437 int flags; /* 1: trimleft 2: trimright 3: trim */
85438 int i; /* Loop counter */
85439 unsigned char *aLen = 0; /* Length of each character in zCharSet */
85440 unsigned char **azChar = 0; /* Individual characters in zCharSet */
85441 int nChar; /* Number of characters in zCharSet */
85443 if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
85444 return;
85446 zIn = sqlite3_value_text(argv[0]);
85447 if( zIn==0 ) return;
85448 nIn = sqlite3_value_bytes(argv[0]);
85449 assert( zIn==sqlite3_value_text(argv[0]) );
85450 if( argc==1 ){
85451 static const unsigned char lenOne[] = { 1 };
85452 static unsigned char * const azOne[] = { (u8*)" " };
85453 nChar = 1;
85454 aLen = (u8*)lenOne;
85455 azChar = (unsigned char **)azOne;
85456 zCharSet = 0;
85457 }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
85458 return;
85459 }else{
85460 const unsigned char *z;
85461 for(z=zCharSet, nChar=0; *z; nChar++){
85462 SQLITE_SKIP_UTF8(z);
85464 if( nChar>0 ){
85465 azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
85466 if( azChar==0 ){
85467 return;
85469 aLen = (unsigned char*)&azChar[nChar];
85470 for(z=zCharSet, nChar=0; *z; nChar++){
85471 azChar[nChar] = (unsigned char *)z;
85472 SQLITE_SKIP_UTF8(z);
85473 aLen[nChar] = (u8)(z - azChar[nChar]);
85477 if( nChar>0 ){
85478 flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
85479 if( flags & 1 ){
85480 while( nIn>0 ){
85481 int len = 0;
85482 for(i=0; i<nChar; i++){
85483 len = aLen[i];
85484 if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
85486 if( i>=nChar ) break;
85487 zIn += len;
85488 nIn -= len;
85491 if( flags & 2 ){
85492 while( nIn>0 ){
85493 int len = 0;
85494 for(i=0; i<nChar; i++){
85495 len = aLen[i];
85496 if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
85498 if( i>=nChar ) break;
85499 nIn -= len;
85502 if( zCharSet ){
85503 sqlite3_free(azChar);
85506 sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
85510 /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
85511 ** is only available if the SQLITE_SOUNDEX compile-time option is used
85512 ** when SQLite is built.
85514 #ifdef SQLITE_SOUNDEX
85516 ** Compute the soundex encoding of a word.
85518 ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
85519 ** soundex encoding of the string X.
85521 static void soundexFunc(
85522 sqlite3_context *context,
85523 int argc,
85524 sqlite3_value **argv
85526 char zResult[8];
85527 const u8 *zIn;
85528 int i, j;
85529 static const unsigned char iCode[] = {
85530 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
85531 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
85532 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
85533 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
85534 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
85535 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
85536 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
85537 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
85539 assert( argc==1 );
85540 zIn = (u8*)sqlite3_value_text(argv[0]);
85541 if( zIn==0 ) zIn = (u8*)"";
85542 for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
85543 if( zIn[i] ){
85544 u8 prevcode = iCode[zIn[i]&0x7f];
85545 zResult[0] = sqlite3Toupper(zIn[i]);
85546 for(j=1; j<4 && zIn[i]; i++){
85547 int code = iCode[zIn[i]&0x7f];
85548 if( code>0 ){
85549 if( code!=prevcode ){
85550 prevcode = code;
85551 zResult[j++] = code + '0';
85553 }else{
85554 prevcode = 0;
85557 while( j<4 ){
85558 zResult[j++] = '0';
85560 zResult[j] = 0;
85561 sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
85562 }else{
85563 /* IMP: R-64894-50321 The string "?000" is returned if the argument
85564 ** is NULL or contains no ASCII alphabetic characters. */
85565 sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
85568 #endif /* SQLITE_SOUNDEX */
85570 #ifndef SQLITE_OMIT_LOAD_EXTENSION
85572 ** A function that loads a shared-library extension then returns NULL.
85574 static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
85575 const char *zFile = (const char *)sqlite3_value_text(argv[0]);
85576 const char *zProc;
85577 sqlite3 *db = sqlite3_context_db_handle(context);
85578 char *zErrMsg = 0;
85580 if( argc==2 ){
85581 zProc = (const char *)sqlite3_value_text(argv[1]);
85582 }else{
85583 zProc = 0;
85585 if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
85586 sqlite3_result_error(context, zErrMsg, -1);
85587 sqlite3_free(zErrMsg);
85590 #endif
85594 ** An instance of the following structure holds the context of a
85595 ** sum() or avg() aggregate computation.
85597 typedef struct SumCtx SumCtx;
85598 struct SumCtx {
85599 double rSum; /* Floating point sum */
85600 i64 iSum; /* Integer sum */
85601 i64 cnt; /* Number of elements summed */
85602 u8 overflow; /* True if integer overflow seen */
85603 u8 approx; /* True if non-integer value was input to the sum */
85607 ** Routines used to compute the sum, average, and total.
85609 ** The SUM() function follows the (broken) SQL standard which means
85610 ** that it returns NULL if it sums over no inputs. TOTAL returns
85611 ** 0.0 in that case. In addition, TOTAL always returns a float where
85612 ** SUM might return an integer if it never encounters a floating point
85613 ** value. TOTAL never fails, but SUM might through an exception if
85614 ** it overflows an integer.
85616 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
85617 SumCtx *p;
85618 int type;
85619 assert( argc==1 );
85620 UNUSED_PARAMETER(argc);
85621 p = sqlite3_aggregate_context(context, sizeof(*p));
85622 type = sqlite3_value_numeric_type(argv[0]);
85623 if( p && type!=SQLITE_NULL ){
85624 p->cnt++;
85625 if( type==SQLITE_INTEGER ){
85626 i64 v = sqlite3_value_int64(argv[0]);
85627 p->rSum += v;
85628 if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
85629 p->overflow = 1;
85631 }else{
85632 p->rSum += sqlite3_value_double(argv[0]);
85633 p->approx = 1;
85637 static void sumFinalize(sqlite3_context *context){
85638 SumCtx *p;
85639 p = sqlite3_aggregate_context(context, 0);
85640 if( p && p->cnt>0 ){
85641 if( p->overflow ){
85642 sqlite3_result_error(context,"integer overflow",-1);
85643 }else if( p->approx ){
85644 sqlite3_result_double(context, p->rSum);
85645 }else{
85646 sqlite3_result_int64(context, p->iSum);
85650 static void avgFinalize(sqlite3_context *context){
85651 SumCtx *p;
85652 p = sqlite3_aggregate_context(context, 0);
85653 if( p && p->cnt>0 ){
85654 sqlite3_result_double(context, p->rSum/(double)p->cnt);
85657 static void totalFinalize(sqlite3_context *context){
85658 SumCtx *p;
85659 p = sqlite3_aggregate_context(context, 0);
85660 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
85661 sqlite3_result_double(context, p ? p->rSum : (double)0);
85665 ** The following structure keeps track of state information for the
85666 ** count() aggregate function.
85668 typedef struct CountCtx CountCtx;
85669 struct CountCtx {
85670 i64 n;
85674 ** Routines to implement the count() aggregate function.
85676 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
85677 CountCtx *p;
85678 p = sqlite3_aggregate_context(context, sizeof(*p));
85679 if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
85680 p->n++;
85683 #ifndef SQLITE_OMIT_DEPRECATED
85684 /* The sqlite3_aggregate_count() function is deprecated. But just to make
85685 ** sure it still operates correctly, verify that its count agrees with our
85686 ** internal count when using count(*) and when the total count can be
85687 ** expressed as a 32-bit integer. */
85688 assert( argc==1 || p==0 || p->n>0x7fffffff
85689 || p->n==sqlite3_aggregate_count(context) );
85690 #endif
85692 static void countFinalize(sqlite3_context *context){
85693 CountCtx *p;
85694 p = sqlite3_aggregate_context(context, 0);
85695 sqlite3_result_int64(context, p ? p->n : 0);
85699 ** Routines to implement min() and max() aggregate functions.
85701 static void minmaxStep(
85702 sqlite3_context *context,
85703 int NotUsed,
85704 sqlite3_value **argv
85706 Mem *pArg = (Mem *)argv[0];
85707 Mem *pBest;
85708 UNUSED_PARAMETER(NotUsed);
85710 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
85711 pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
85712 if( !pBest ) return;
85714 if( pBest->flags ){
85715 int max;
85716 int cmp;
85717 CollSeq *pColl = sqlite3GetFuncCollSeq(context);
85718 /* This step function is used for both the min() and max() aggregates,
85719 ** the only difference between the two being that the sense of the
85720 ** comparison is inverted. For the max() aggregate, the
85721 ** sqlite3_user_data() function returns (void *)-1. For min() it
85722 ** returns (void *)db, where db is the sqlite3* database pointer.
85723 ** Therefore the next statement sets variable 'max' to 1 for the max()
85724 ** aggregate, or 0 for min().
85726 max = sqlite3_user_data(context)!=0;
85727 cmp = sqlite3MemCompare(pBest, pArg, pColl);
85728 if( (max && cmp<0) || (!max && cmp>0) ){
85729 sqlite3VdbeMemCopy(pBest, pArg);
85731 }else{
85732 sqlite3VdbeMemCopy(pBest, pArg);
85735 static void minMaxFinalize(sqlite3_context *context){
85736 sqlite3_value *pRes;
85737 pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
85738 if( pRes ){
85739 if( ALWAYS(pRes->flags) ){
85740 sqlite3_result_value(context, pRes);
85742 sqlite3VdbeMemRelease(pRes);
85747 ** group_concat(EXPR, ?SEPARATOR?)
85749 static void groupConcatStep(
85750 sqlite3_context *context,
85751 int argc,
85752 sqlite3_value **argv
85754 const char *zVal;
85755 StrAccum *pAccum;
85756 const char *zSep;
85757 int nVal, nSep;
85758 assert( argc==1 || argc==2 );
85759 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
85760 pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
85762 if( pAccum ){
85763 sqlite3 *db = sqlite3_context_db_handle(context);
85764 int firstTerm = pAccum->useMalloc==0;
85765 pAccum->useMalloc = 2;
85766 pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
85767 if( !firstTerm ){
85768 if( argc==2 ){
85769 zSep = (char*)sqlite3_value_text(argv[1]);
85770 nSep = sqlite3_value_bytes(argv[1]);
85771 }else{
85772 zSep = ",";
85773 nSep = 1;
85775 sqlite3StrAccumAppend(pAccum, zSep, nSep);
85777 zVal = (char*)sqlite3_value_text(argv[0]);
85778 nVal = sqlite3_value_bytes(argv[0]);
85779 sqlite3StrAccumAppend(pAccum, zVal, nVal);
85782 static void groupConcatFinalize(sqlite3_context *context){
85783 StrAccum *pAccum;
85784 pAccum = sqlite3_aggregate_context(context, 0);
85785 if( pAccum ){
85786 if( pAccum->tooBig ){
85787 sqlite3_result_error_toobig(context);
85788 }else if( pAccum->mallocFailed ){
85789 sqlite3_result_error_nomem(context);
85790 }else{
85791 sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
85792 sqlite3_free);
85798 ** This routine does per-connection function registration. Most
85799 ** of the built-in functions above are part of the global function set.
85800 ** This routine only deals with those that are not global.
85802 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
85803 int rc = sqlite3_overload_function(db, "MATCH", 2);
85804 assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
85805 if( rc==SQLITE_NOMEM ){
85806 db->mallocFailed = 1;
85811 ** Set the LIKEOPT flag on the 2-argument function with the given name.
85813 static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
85814 FuncDef *pDef;
85815 pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
85816 2, SQLITE_UTF8, 0);
85817 if( ALWAYS(pDef) ){
85818 pDef->flags = flagVal;
85823 ** Register the built-in LIKE and GLOB functions. The caseSensitive
85824 ** parameter determines whether or not the LIKE operator is case
85825 ** sensitive. GLOB is always case sensitive.
85827 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
85828 struct compareInfo *pInfo;
85829 if( caseSensitive ){
85830 pInfo = (struct compareInfo*)&likeInfoAlt;
85831 }else{
85832 pInfo = (struct compareInfo*)&likeInfoNorm;
85834 sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
85835 sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
85836 sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
85837 (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
85838 setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
85839 setLikeOptFlag(db, "like",
85840 caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
85844 ** pExpr points to an expression which implements a function. If
85845 ** it is appropriate to apply the LIKE optimization to that function
85846 ** then set aWc[0] through aWc[2] to the wildcard characters and
85847 ** return TRUE. If the function is not a LIKE-style function then
85848 ** return FALSE.
85850 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
85851 FuncDef *pDef;
85852 if( pExpr->op!=TK_FUNCTION
85853 || !pExpr->x.pList
85854 || pExpr->x.pList->nExpr!=2
85856 return 0;
85858 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
85859 pDef = sqlite3FindFunction(db, pExpr->u.zToken,
85860 sqlite3Strlen30(pExpr->u.zToken),
85861 2, SQLITE_UTF8, 0);
85862 if( NEVER(pDef==0) || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){
85863 return 0;
85866 /* The memcpy() statement assumes that the wildcard characters are
85867 ** the first three statements in the compareInfo structure. The
85868 ** asserts() that follow verify that assumption
85870 memcpy(aWc, pDef->pUserData, 3);
85871 assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
85872 assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
85873 assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
85874 *pIsNocase = (pDef->flags & SQLITE_FUNC_CASE)==0;
85875 return 1;
85879 ** All all of the FuncDef structures in the aBuiltinFunc[] array above
85880 ** to the global function hash table. This occurs at start-time (as
85881 ** a consequence of calling sqlite3_initialize()).
85883 ** After this routine runs
85885 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
85887 ** The following array holds FuncDef structures for all of the functions
85888 ** defined in this file.
85890 ** The array cannot be constant since changes are made to the
85891 ** FuncDef.pHash elements at start-time. The elements of this array
85892 ** are read-only after initialization is complete.
85894 static SQLITE_WSD FuncDef aBuiltinFunc[] = {
85895 FUNCTION(ltrim, 1, 1, 0, trimFunc ),
85896 FUNCTION(ltrim, 2, 1, 0, trimFunc ),
85897 FUNCTION(rtrim, 1, 2, 0, trimFunc ),
85898 FUNCTION(rtrim, 2, 2, 0, trimFunc ),
85899 FUNCTION(trim, 1, 3, 0, trimFunc ),
85900 FUNCTION(trim, 2, 3, 0, trimFunc ),
85901 FUNCTION(min, -1, 0, 1, minmaxFunc ),
85902 FUNCTION(min, 0, 0, 1, 0 ),
85903 AGGREGATE(min, 1, 0, 1, minmaxStep, minMaxFinalize ),
85904 FUNCTION(max, -1, 1, 1, minmaxFunc ),
85905 FUNCTION(max, 0, 1, 1, 0 ),
85906 AGGREGATE(max, 1, 1, 1, minmaxStep, minMaxFinalize ),
85907 FUNCTION(typeof, 1, 0, 0, typeofFunc ),
85908 FUNCTION(length, 1, 0, 0, lengthFunc ),
85909 FUNCTION(substr, 2, 0, 0, substrFunc ),
85910 FUNCTION(substr, 3, 0, 0, substrFunc ),
85911 FUNCTION(abs, 1, 0, 0, absFunc ),
85912 #ifndef SQLITE_OMIT_FLOATING_POINT
85913 FUNCTION(round, 1, 0, 0, roundFunc ),
85914 FUNCTION(round, 2, 0, 0, roundFunc ),
85915 #endif
85916 FUNCTION(upper, 1, 0, 0, upperFunc ),
85917 FUNCTION(lower, 1, 0, 0, lowerFunc ),
85918 FUNCTION(coalesce, 1, 0, 0, 0 ),
85919 FUNCTION(coalesce, 0, 0, 0, 0 ),
85920 /* FUNCTION(coalesce, -1, 0, 0, ifnullFunc ), */
85921 {-1,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"coalesce",0,0},
85922 FUNCTION(hex, 1, 0, 0, hexFunc ),
85923 /* FUNCTION(ifnull, 2, 0, 0, ifnullFunc ), */
85924 {2,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"ifnull",0,0},
85925 FUNCTION(random, 0, 0, 0, randomFunc ),
85926 FUNCTION(randomblob, 1, 0, 0, randomBlob ),
85927 FUNCTION(nullif, 2, 0, 1, nullifFunc ),
85928 FUNCTION(sqlite_version, 0, 0, 0, versionFunc ),
85929 FUNCTION(sqlite_source_id, 0, 0, 0, sourceidFunc ),
85930 FUNCTION(sqlite_log, 2, 0, 0, errlogFunc ),
85931 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
85932 FUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc ),
85933 FUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc ),
85934 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
85935 FUNCTION(quote, 1, 0, 0, quoteFunc ),
85936 FUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
85937 FUNCTION(changes, 0, 0, 0, changes ),
85938 FUNCTION(total_changes, 0, 0, 0, total_changes ),
85939 FUNCTION(replace, 3, 0, 0, replaceFunc ),
85940 FUNCTION(zeroblob, 1, 0, 0, zeroblobFunc ),
85941 #ifdef SQLITE_SOUNDEX
85942 FUNCTION(soundex, 1, 0, 0, soundexFunc ),
85943 #endif
85944 #ifndef SQLITE_OMIT_LOAD_EXTENSION
85945 FUNCTION(load_extension, 1, 0, 0, loadExt ),
85946 FUNCTION(load_extension, 2, 0, 0, loadExt ),
85947 #endif
85948 AGGREGATE(sum, 1, 0, 0, sumStep, sumFinalize ),
85949 AGGREGATE(total, 1, 0, 0, sumStep, totalFinalize ),
85950 AGGREGATE(avg, 1, 0, 0, sumStep, avgFinalize ),
85951 /* AGGREGATE(count, 0, 0, 0, countStep, countFinalize ), */
85952 {0,SQLITE_UTF8,SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0,0},
85953 AGGREGATE(count, 1, 0, 0, countStep, countFinalize ),
85954 AGGREGATE(group_concat, 1, 0, 0, groupConcatStep, groupConcatFinalize),
85955 AGGREGATE(group_concat, 2, 0, 0, groupConcatStep, groupConcatFinalize),
85957 LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
85958 #ifdef SQLITE_CASE_SENSITIVE_LIKE
85959 LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
85960 LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
85961 #else
85962 LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
85963 LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
85964 #endif
85967 int i;
85968 FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
85969 FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
85971 for(i=0; i<ArraySize(aBuiltinFunc); i++){
85972 sqlite3FuncDefInsert(pHash, &aFunc[i]);
85974 sqlite3RegisterDateTimeFunctions();
85975 #ifndef SQLITE_OMIT_ALTERTABLE
85976 sqlite3AlterFunctions();
85977 #endif
85980 /************** End of func.c ************************************************/
85981 /************** Begin file fkey.c ********************************************/
85984 ** The author disclaims copyright to this source code. In place of
85985 ** a legal notice, here is a blessing:
85987 ** May you do good and not evil.
85988 ** May you find forgiveness for yourself and forgive others.
85989 ** May you share freely, never taking more than you give.
85991 *************************************************************************
85992 ** This file contains code used by the compiler to add foreign key
85993 ** support to compiled SQL statements.
85996 #ifndef SQLITE_OMIT_FOREIGN_KEY
85997 #ifndef SQLITE_OMIT_TRIGGER
86000 ** Deferred and Immediate FKs
86001 ** --------------------------
86003 ** Foreign keys in SQLite come in two flavours: deferred and immediate.
86004 ** If an immediate foreign key constraint is violated, SQLITE_CONSTRAINT
86005 ** is returned and the current statement transaction rolled back. If a
86006 ** deferred foreign key constraint is violated, no action is taken
86007 ** immediately. However if the application attempts to commit the
86008 ** transaction before fixing the constraint violation, the attempt fails.
86010 ** Deferred constraints are implemented using a simple counter associated
86011 ** with the database handle. The counter is set to zero each time a
86012 ** database transaction is opened. Each time a statement is executed
86013 ** that causes a foreign key violation, the counter is incremented. Each
86014 ** time a statement is executed that removes an existing violation from
86015 ** the database, the counter is decremented. When the transaction is
86016 ** committed, the commit fails if the current value of the counter is
86017 ** greater than zero. This scheme has two big drawbacks:
86019 ** * When a commit fails due to a deferred foreign key constraint,
86020 ** there is no way to tell which foreign constraint is not satisfied,
86021 ** or which row it is not satisfied for.
86023 ** * If the database contains foreign key violations when the
86024 ** transaction is opened, this may cause the mechanism to malfunction.
86026 ** Despite these problems, this approach is adopted as it seems simpler
86027 ** than the alternatives.
86029 ** INSERT operations:
86031 ** I.1) For each FK for which the table is the child table, search
86032 ** the parent table for a match. If none is found increment the
86033 ** constraint counter.
86035 ** I.2) For each FK for which the table is the parent table,
86036 ** search the child table for rows that correspond to the new
86037 ** row in the parent table. Decrement the counter for each row
86038 ** found (as the constraint is now satisfied).
86040 ** DELETE operations:
86042 ** D.1) For each FK for which the table is the child table,
86043 ** search the parent table for a row that corresponds to the
86044 ** deleted row in the child table. If such a row is not found,
86045 ** decrement the counter.
86047 ** D.2) For each FK for which the table is the parent table, search
86048 ** the child table for rows that correspond to the deleted row
86049 ** in the parent table. For each found increment the counter.
86051 ** UPDATE operations:
86053 ** An UPDATE command requires that all 4 steps above are taken, but only
86054 ** for FK constraints for which the affected columns are actually
86055 ** modified (values must be compared at runtime).
86057 ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
86058 ** This simplifies the implementation a bit.
86060 ** For the purposes of immediate FK constraints, the OR REPLACE conflict
86061 ** resolution is considered to delete rows before the new row is inserted.
86062 ** If a delete caused by OR REPLACE violates an FK constraint, an exception
86063 ** is thrown, even if the FK constraint would be satisfied after the new
86064 ** row is inserted.
86066 ** Immediate constraints are usually handled similarly. The only difference
86067 ** is that the counter used is stored as part of each individual statement
86068 ** object (struct Vdbe). If, after the statement has run, its immediate
86069 ** constraint counter is greater than zero, it returns SQLITE_CONSTRAINT
86070 ** and the statement transaction is rolled back. An exception is an INSERT
86071 ** statement that inserts a single row only (no triggers). In this case,
86072 ** instead of using a counter, an exception is thrown immediately if the
86073 ** INSERT violates a foreign key constraint. This is necessary as such
86074 ** an INSERT does not open a statement transaction.
86076 ** TODO: How should dropping a table be handled? How should renaming a
86077 ** table be handled?
86080 ** Query API Notes
86081 ** ---------------
86083 ** Before coding an UPDATE or DELETE row operation, the code-generator
86084 ** for those two operations needs to know whether or not the operation
86085 ** requires any FK processing and, if so, which columns of the original
86086 ** row are required by the FK processing VDBE code (i.e. if FKs were
86087 ** implemented using triggers, which of the old.* columns would be
86088 ** accessed). No information is required by the code-generator before
86089 ** coding an INSERT operation. The functions used by the UPDATE/DELETE
86090 ** generation code to query for this information are:
86092 ** sqlite3FkRequired() - Test to see if FK processing is required.
86093 ** sqlite3FkOldmask() - Query for the set of required old.* columns.
86096 ** Externally accessible module functions
86097 ** --------------------------------------
86099 ** sqlite3FkCheck() - Check for foreign key violations.
86100 ** sqlite3FkActions() - Code triggers for ON UPDATE/ON DELETE actions.
86101 ** sqlite3FkDelete() - Delete an FKey structure.
86105 ** VDBE Calling Convention
86106 ** -----------------------
86108 ** Example:
86110 ** For the following INSERT statement:
86112 ** CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
86113 ** INSERT INTO t1 VALUES(1, 2, 3.1);
86115 ** Register (x): 2 (type integer)
86116 ** Register (x+1): 1 (type integer)
86117 ** Register (x+2): NULL (type NULL)
86118 ** Register (x+3): 3.1 (type real)
86122 ** A foreign key constraint requires that the key columns in the parent
86123 ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
86124 ** Given that pParent is the parent table for foreign key constraint pFKey,
86125 ** search the schema a unique index on the parent key columns.
86127 ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
86128 ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
86129 ** is set to point to the unique index.
86131 ** If the parent key consists of a single column (the foreign key constraint
86132 ** is not a composite foreign key), output variable *paiCol is set to NULL.
86133 ** Otherwise, it is set to point to an allocated array of size N, where
86134 ** N is the number of columns in the parent key. The first element of the
86135 ** array is the index of the child table column that is mapped by the FK
86136 ** constraint to the parent table column stored in the left-most column
86137 ** of index *ppIdx. The second element of the array is the index of the
86138 ** child table column that corresponds to the second left-most column of
86139 ** *ppIdx, and so on.
86141 ** If the required index cannot be found, either because:
86143 ** 1) The named parent key columns do not exist, or
86145 ** 2) The named parent key columns do exist, but are not subject to a
86146 ** UNIQUE or PRIMARY KEY constraint, or
86148 ** 3) No parent key columns were provided explicitly as part of the
86149 ** foreign key definition, and the parent table does not have a
86150 ** PRIMARY KEY, or
86152 ** 4) No parent key columns were provided explicitly as part of the
86153 ** foreign key definition, and the PRIMARY KEY of the parent table
86154 ** consists of a a different number of columns to the child key in
86155 ** the child table.
86157 ** then non-zero is returned, and a "foreign key mismatch" error loaded
86158 ** into pParse. If an OOM error occurs, non-zero is returned and the
86159 ** pParse->db->mallocFailed flag is set.
86161 static int locateFkeyIndex(
86162 Parse *pParse, /* Parse context to store any error in */
86163 Table *pParent, /* Parent table of FK constraint pFKey */
86164 FKey *pFKey, /* Foreign key to find index for */
86165 Index **ppIdx, /* OUT: Unique index on parent table */
86166 int **paiCol /* OUT: Map of index columns in pFKey */
86168 Index *pIdx = 0; /* Value to return via *ppIdx */
86169 int *aiCol = 0; /* Value to return via *paiCol */
86170 int nCol = pFKey->nCol; /* Number of columns in parent key */
86171 char *zKey = pFKey->aCol[0].zCol; /* Name of left-most parent key column */
86173 /* The caller is responsible for zeroing output parameters. */
86174 assert( ppIdx && *ppIdx==0 );
86175 assert( !paiCol || *paiCol==0 );
86176 assert( pParse );
86178 /* If this is a non-composite (single column) foreign key, check if it
86179 ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
86180 ** and *paiCol set to zero and return early.
86182 ** Otherwise, for a composite foreign key (more than one column), allocate
86183 ** space for the aiCol array (returned via output parameter *paiCol).
86184 ** Non-composite foreign keys do not require the aiCol array.
86186 if( nCol==1 ){
86187 /* The FK maps to the IPK if any of the following are true:
86189 ** 1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
86190 ** mapped to the primary key of table pParent, or
86191 ** 2) The FK is explicitly mapped to a column declared as INTEGER
86192 ** PRIMARY KEY.
86194 if( pParent->iPKey>=0 ){
86195 if( !zKey ) return 0;
86196 if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
86198 }else if( paiCol ){
86199 assert( nCol>1 );
86200 aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
86201 if( !aiCol ) return 1;
86202 *paiCol = aiCol;
86205 for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
86206 if( pIdx->nColumn==nCol && pIdx->onError!=OE_None ){
86207 /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
86208 ** of columns. If each indexed column corresponds to a foreign key
86209 ** column of pFKey, then this index is a winner. */
86211 if( zKey==0 ){
86212 /* If zKey is NULL, then this foreign key is implicitly mapped to
86213 ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
86214 ** identified by the test (Index.autoIndex==2). */
86215 if( pIdx->autoIndex==2 ){
86216 if( aiCol ){
86217 int i;
86218 for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
86220 break;
86222 }else{
86223 /* If zKey is non-NULL, then this foreign key was declared to
86224 ** map to an explicit list of columns in table pParent. Check if this
86225 ** index matches those columns. Also, check that the index uses
86226 ** the default collation sequences for each column. */
86227 int i, j;
86228 for(i=0; i<nCol; i++){
86229 int iCol = pIdx->aiColumn[i]; /* Index of column in parent tbl */
86230 char *zDfltColl; /* Def. collation for column */
86231 char *zIdxCol; /* Name of indexed column */
86233 /* If the index uses a collation sequence that is different from
86234 ** the default collation sequence for the column, this index is
86235 ** unusable. Bail out early in this case. */
86236 zDfltColl = pParent->aCol[iCol].zColl;
86237 if( !zDfltColl ){
86238 zDfltColl = "BINARY";
86240 if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
86242 zIdxCol = pParent->aCol[iCol].zName;
86243 for(j=0; j<nCol; j++){
86244 if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
86245 if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
86246 break;
86249 if( j==nCol ) break;
86251 if( i==nCol ) break; /* pIdx is usable */
86256 if( !pIdx ){
86257 if( !pParse->disableTriggers ){
86258 sqlite3ErrorMsg(pParse, "foreign key mismatch");
86260 sqlite3DbFree(pParse->db, aiCol);
86261 return 1;
86264 *ppIdx = pIdx;
86265 return 0;
86269 ** This function is called when a row is inserted into or deleted from the
86270 ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
86271 ** on the child table of pFKey, this function is invoked twice for each row
86272 ** affected - once to "delete" the old row, and then again to "insert" the
86273 ** new row.
86275 ** Each time it is called, this function generates VDBE code to locate the
86276 ** row in the parent table that corresponds to the row being inserted into
86277 ** or deleted from the child table. If the parent row can be found, no
86278 ** special action is taken. Otherwise, if the parent row can *not* be
86279 ** found in the parent table:
86281 ** Operation | FK type | Action taken
86282 ** --------------------------------------------------------------------------
86283 ** INSERT immediate Increment the "immediate constraint counter".
86285 ** DELETE immediate Decrement the "immediate constraint counter".
86287 ** INSERT deferred Increment the "deferred constraint counter".
86289 ** DELETE deferred Decrement the "deferred constraint counter".
86291 ** These operations are identified in the comment at the top of this file
86292 ** (fkey.c) as "I.1" and "D.1".
86294 static void fkLookupParent(
86295 Parse *pParse, /* Parse context */
86296 int iDb, /* Index of database housing pTab */
86297 Table *pTab, /* Parent table of FK pFKey */
86298 Index *pIdx, /* Unique index on parent key columns in pTab */
86299 FKey *pFKey, /* Foreign key constraint */
86300 int *aiCol, /* Map from parent key columns to child table columns */
86301 int regData, /* Address of array containing child table row */
86302 int nIncr, /* Increment constraint counter by this */
86303 int isIgnore /* If true, pretend pTab contains all NULL values */
86305 int i; /* Iterator variable */
86306 Vdbe *v = sqlite3GetVdbe(pParse); /* Vdbe to add code to */
86307 int iCur = pParse->nTab - 1; /* Cursor number to use */
86308 int iOk = sqlite3VdbeMakeLabel(v); /* jump here if parent key found */
86310 /* If nIncr is less than zero, then check at runtime if there are any
86311 ** outstanding constraints to resolve. If there are not, there is no need
86312 ** to check if deleting this row resolves any outstanding violations.
86314 ** Check if any of the key columns in the child table row are NULL. If
86315 ** any are, then the constraint is considered satisfied. No need to
86316 ** search for a matching row in the parent table. */
86317 if( nIncr<0 ){
86318 sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
86320 for(i=0; i<pFKey->nCol; i++){
86321 int iReg = aiCol[i] + regData + 1;
86322 sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk);
86325 if( isIgnore==0 ){
86326 if( pIdx==0 ){
86327 /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
86328 ** column of the parent table (table pTab). */
86329 int iMustBeInt; /* Address of MustBeInt instruction */
86330 int regTemp = sqlite3GetTempReg(pParse);
86332 /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
86333 ** apply the affinity of the parent key). If this fails, then there
86334 ** is no matching parent key. Before using MustBeInt, make a copy of
86335 ** the value. Otherwise, the value inserted into the child key column
86336 ** will have INTEGER affinity applied to it, which may not be correct. */
86337 sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
86338 iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
86340 /* If the parent table is the same as the child table, and we are about
86341 ** to increment the constraint-counter (i.e. this is an INSERT operation),
86342 ** then check if the row being inserted matches itself. If so, do not
86343 ** increment the constraint-counter. */
86344 if( pTab==pFKey->pFrom && nIncr==1 ){
86345 sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp);
86348 sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
86349 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp);
86350 sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
86351 sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
86352 sqlite3VdbeJumpHere(v, iMustBeInt);
86353 sqlite3ReleaseTempReg(pParse, regTemp);
86354 }else{
86355 int nCol = pFKey->nCol;
86356 int regTemp = sqlite3GetTempRange(pParse, nCol);
86357 int regRec = sqlite3GetTempReg(pParse);
86358 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
86360 sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
86361 sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
86362 for(i=0; i<nCol; i++){
86363 sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
86366 /* If the parent table is the same as the child table, and we are about
86367 ** to increment the constraint-counter (i.e. this is an INSERT operation),
86368 ** then check if the row being inserted matches itself. If so, do not
86369 ** increment the constraint-counter.
86371 ** If any of the parent-key values are NULL, then the row cannot match
86372 ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
86373 ** of the parent-key values are NULL (at this point it is known that
86374 ** none of the child key values are).
86376 if( pTab==pFKey->pFrom && nIncr==1 ){
86377 int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
86378 for(i=0; i<nCol; i++){
86379 int iChild = aiCol[i]+1+regData;
86380 int iParent = pIdx->aiColumn[i]+1+regData;
86381 assert( aiCol[i]!=pTab->iPKey );
86382 if( pIdx->aiColumn[i]==pTab->iPKey ){
86383 /* The parent key is a composite key that includes the IPK column */
86384 iParent = regData;
86386 sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent);
86387 sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
86389 sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
86392 sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec);
86393 sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v,pIdx), P4_TRANSIENT);
86394 sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0);
86396 sqlite3ReleaseTempReg(pParse, regRec);
86397 sqlite3ReleaseTempRange(pParse, regTemp, nCol);
86401 if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
86402 /* Special case: If this is an INSERT statement that will insert exactly
86403 ** one row into the table, raise a constraint immediately instead of
86404 ** incrementing a counter. This is necessary as the VM code is being
86405 ** generated for will not open a statement transaction. */
86406 assert( nIncr==1 );
86407 sqlite3HaltConstraint(
86408 pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
86410 }else{
86411 if( nIncr>0 && pFKey->isDeferred==0 ){
86412 sqlite3ParseToplevel(pParse)->mayAbort = 1;
86414 sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
86417 sqlite3VdbeResolveLabel(v, iOk);
86418 sqlite3VdbeAddOp1(v, OP_Close, iCur);
86422 ** This function is called to generate code executed when a row is deleted
86423 ** from the parent table of foreign key constraint pFKey and, if pFKey is
86424 ** deferred, when a row is inserted into the same table. When generating
86425 ** code for an SQL UPDATE operation, this function may be called twice -
86426 ** once to "delete" the old row and once to "insert" the new row.
86428 ** The code generated by this function scans through the rows in the child
86429 ** table that correspond to the parent table row being deleted or inserted.
86430 ** For each child row found, one of the following actions is taken:
86432 ** Operation | FK type | Action taken
86433 ** --------------------------------------------------------------------------
86434 ** DELETE immediate Increment the "immediate constraint counter".
86435 ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
86436 ** throw a "foreign key constraint failed" exception.
86438 ** INSERT immediate Decrement the "immediate constraint counter".
86440 ** DELETE deferred Increment the "deferred constraint counter".
86441 ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
86442 ** throw a "foreign key constraint failed" exception.
86444 ** INSERT deferred Decrement the "deferred constraint counter".
86446 ** These operations are identified in the comment at the top of this file
86447 ** (fkey.c) as "I.2" and "D.2".
86449 static void fkScanChildren(
86450 Parse *pParse, /* Parse context */
86451 SrcList *pSrc, /* SrcList containing the table to scan */
86452 Table *pTab,
86453 Index *pIdx, /* Foreign key index */
86454 FKey *pFKey, /* Foreign key relationship */
86455 int *aiCol, /* Map from pIdx cols to child table cols */
86456 int regData, /* Referenced table data starts here */
86457 int nIncr /* Amount to increment deferred counter by */
86459 sqlite3 *db = pParse->db; /* Database handle */
86460 int i; /* Iterator variable */
86461 Expr *pWhere = 0; /* WHERE clause to scan with */
86462 NameContext sNameContext; /* Context used to resolve WHERE clause */
86463 WhereInfo *pWInfo; /* Context used by sqlite3WhereXXX() */
86464 int iFkIfZero = 0; /* Address of OP_FkIfZero */
86465 Vdbe *v = sqlite3GetVdbe(pParse);
86467 assert( !pIdx || pIdx->pTable==pTab );
86469 if( nIncr<0 ){
86470 iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
86473 /* Create an Expr object representing an SQL expression like:
86475 ** <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
86477 ** The collation sequence used for the comparison should be that of
86478 ** the parent key columns. The affinity of the parent key column should
86479 ** be applied to each child key value before the comparison takes place.
86481 for(i=0; i<pFKey->nCol; i++){
86482 Expr *pLeft; /* Value from parent table row */
86483 Expr *pRight; /* Column ref to child table */
86484 Expr *pEq; /* Expression (pLeft = pRight) */
86485 int iCol; /* Index of column in child table */
86486 const char *zCol; /* Name of column in child table */
86488 pLeft = sqlite3Expr(db, TK_REGISTER, 0);
86489 if( pLeft ){
86490 /* Set the collation sequence and affinity of the LHS of each TK_EQ
86491 ** expression to the parent key column defaults. */
86492 if( pIdx ){
86493 Column *pCol;
86494 iCol = pIdx->aiColumn[i];
86495 pCol = &pTab->aCol[iCol];
86496 if( pTab->iPKey==iCol ) iCol = -1;
86497 pLeft->iTable = regData+iCol+1;
86498 pLeft->affinity = pCol->affinity;
86499 pLeft->pColl = sqlite3LocateCollSeq(pParse, pCol->zColl);
86500 }else{
86501 pLeft->iTable = regData;
86502 pLeft->affinity = SQLITE_AFF_INTEGER;
86505 iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
86506 assert( iCol>=0 );
86507 zCol = pFKey->pFrom->aCol[iCol].zName;
86508 pRight = sqlite3Expr(db, TK_ID, zCol);
86509 pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
86510 pWhere = sqlite3ExprAnd(db, pWhere, pEq);
86513 /* If the child table is the same as the parent table, and this scan
86514 ** is taking place as part of a DELETE operation (operation D.2), omit the
86515 ** row being deleted from the scan by adding ($rowid != rowid) to the WHERE
86516 ** clause, where $rowid is the rowid of the row being deleted. */
86517 if( pTab==pFKey->pFrom && nIncr>0 ){
86518 Expr *pEq; /* Expression (pLeft = pRight) */
86519 Expr *pLeft; /* Value from parent table row */
86520 Expr *pRight; /* Column ref to child table */
86521 pLeft = sqlite3Expr(db, TK_REGISTER, 0);
86522 pRight = sqlite3Expr(db, TK_COLUMN, 0);
86523 if( pLeft && pRight ){
86524 pLeft->iTable = regData;
86525 pLeft->affinity = SQLITE_AFF_INTEGER;
86526 pRight->iTable = pSrc->a[0].iCursor;
86527 pRight->iColumn = -1;
86529 pEq = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
86530 pWhere = sqlite3ExprAnd(db, pWhere, pEq);
86533 /* Resolve the references in the WHERE clause. */
86534 memset(&sNameContext, 0, sizeof(NameContext));
86535 sNameContext.pSrcList = pSrc;
86536 sNameContext.pParse = pParse;
86537 sqlite3ResolveExprNames(&sNameContext, pWhere);
86539 /* Create VDBE to loop through the entries in pSrc that match the WHERE
86540 ** clause. If the constraint is not deferred, throw an exception for
86541 ** each row found. Otherwise, for deferred constraints, increment the
86542 ** deferred constraint counter by nIncr for each row selected. */
86543 pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0);
86544 if( nIncr>0 && pFKey->isDeferred==0 ){
86545 sqlite3ParseToplevel(pParse)->mayAbort = 1;
86547 sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
86548 if( pWInfo ){
86549 sqlite3WhereEnd(pWInfo);
86552 /* Clean up the WHERE clause constructed above. */
86553 sqlite3ExprDelete(db, pWhere);
86554 if( iFkIfZero ){
86555 sqlite3VdbeJumpHere(v, iFkIfZero);
86560 ** This function returns a pointer to the head of a linked list of FK
86561 ** constraints for which table pTab is the parent table. For example,
86562 ** given the following schema:
86564 ** CREATE TABLE t1(a PRIMARY KEY);
86565 ** CREATE TABLE t2(b REFERENCES t1(a);
86567 ** Calling this function with table "t1" as an argument returns a pointer
86568 ** to the FKey structure representing the foreign key constraint on table
86569 ** "t2". Calling this function with "t2" as the argument would return a
86570 ** NULL pointer (as there are no FK constraints for which t2 is the parent
86571 ** table).
86573 SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
86574 int nName = sqlite3Strlen30(pTab->zName);
86575 return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
86579 ** The second argument is a Trigger structure allocated by the
86580 ** fkActionTrigger() routine. This function deletes the Trigger structure
86581 ** and all of its sub-components.
86583 ** The Trigger structure or any of its sub-components may be allocated from
86584 ** the lookaside buffer belonging to database handle dbMem.
86586 static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
86587 if( p ){
86588 TriggerStep *pStep = p->step_list;
86589 sqlite3ExprDelete(dbMem, pStep->pWhere);
86590 sqlite3ExprListDelete(dbMem, pStep->pExprList);
86591 sqlite3SelectDelete(dbMem, pStep->pSelect);
86592 sqlite3ExprDelete(dbMem, p->pWhen);
86593 sqlite3DbFree(dbMem, p);
86598 ** This function is called to generate code that runs when table pTab is
86599 ** being dropped from the database. The SrcList passed as the second argument
86600 ** to this function contains a single entry guaranteed to resolve to
86601 ** table pTab.
86603 ** Normally, no code is required. However, if either
86605 ** (a) The table is the parent table of a FK constraint, or
86606 ** (b) The table is the child table of a deferred FK constraint and it is
86607 ** determined at runtime that there are outstanding deferred FK
86608 ** constraint violations in the database,
86610 ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
86611 ** the table from the database. Triggers are disabled while running this
86612 ** DELETE, but foreign key actions are not.
86614 SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
86615 sqlite3 *db = pParse->db;
86616 if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
86617 int iSkip = 0;
86618 Vdbe *v = sqlite3GetVdbe(pParse);
86620 assert( v ); /* VDBE has already been allocated */
86621 if( sqlite3FkReferences(pTab)==0 ){
86622 /* Search for a deferred foreign key constraint for which this table
86623 ** is the child table. If one cannot be found, return without
86624 ** generating any VDBE code. If one can be found, then jump over
86625 ** the entire DELETE if there are no outstanding deferred constraints
86626 ** when this statement is run. */
86627 FKey *p;
86628 for(p=pTab->pFKey; p; p=p->pNextFrom){
86629 if( p->isDeferred ) break;
86631 if( !p ) return;
86632 iSkip = sqlite3VdbeMakeLabel(v);
86633 sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip);
86636 pParse->disableTriggers = 1;
86637 sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
86638 pParse->disableTriggers = 0;
86640 /* If the DELETE has generated immediate foreign key constraint
86641 ** violations, halt the VDBE and return an error at this point, before
86642 ** any modifications to the schema are made. This is because statement
86643 ** transactions are not able to rollback schema changes. */
86644 sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
86645 sqlite3HaltConstraint(
86646 pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
86649 if( iSkip ){
86650 sqlite3VdbeResolveLabel(v, iSkip);
86656 ** This function is called when inserting, deleting or updating a row of
86657 ** table pTab to generate VDBE code to perform foreign key constraint
86658 ** processing for the operation.
86660 ** For a DELETE operation, parameter regOld is passed the index of the
86661 ** first register in an array of (pTab->nCol+1) registers containing the
86662 ** rowid of the row being deleted, followed by each of the column values
86663 ** of the row being deleted, from left to right. Parameter regNew is passed
86664 ** zero in this case.
86666 ** For an INSERT operation, regOld is passed zero and regNew is passed the
86667 ** first register of an array of (pTab->nCol+1) registers containing the new
86668 ** row data.
86670 ** For an UPDATE operation, this function is called twice. Once before
86671 ** the original record is deleted from the table using the calling convention
86672 ** described for DELETE. Then again after the original record is deleted
86673 ** but before the new record is inserted using the INSERT convention.
86675 SQLITE_PRIVATE void sqlite3FkCheck(
86676 Parse *pParse, /* Parse context */
86677 Table *pTab, /* Row is being deleted from this table */
86678 int regOld, /* Previous row data is stored here */
86679 int regNew /* New row data is stored here */
86681 sqlite3 *db = pParse->db; /* Database handle */
86682 FKey *pFKey; /* Used to iterate through FKs */
86683 int iDb; /* Index of database containing pTab */
86684 const char *zDb; /* Name of database containing pTab */
86685 int isIgnoreErrors = pParse->disableTriggers;
86687 /* Exactly one of regOld and regNew should be non-zero. */
86688 assert( (regOld==0)!=(regNew==0) );
86690 /* If foreign-keys are disabled, this function is a no-op. */
86691 if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
86693 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
86694 zDb = db->aDb[iDb].zName;
86696 /* Loop through all the foreign key constraints for which pTab is the
86697 ** child table (the table that the foreign key definition is part of). */
86698 for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
86699 Table *pTo; /* Parent table of foreign key pFKey */
86700 Index *pIdx = 0; /* Index on key columns in pTo */
86701 int *aiFree = 0;
86702 int *aiCol;
86703 int iCol;
86704 int i;
86705 int isIgnore = 0;
86707 /* Find the parent table of this foreign key. Also find a unique index
86708 ** on the parent key columns in the parent table. If either of these
86709 ** schema items cannot be located, set an error in pParse and return
86710 ** early. */
86711 if( pParse->disableTriggers ){
86712 pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
86713 }else{
86714 pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
86716 if( !pTo || locateFkeyIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
86717 assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
86718 if( !isIgnoreErrors || db->mallocFailed ) return;
86719 if( pTo==0 ){
86720 /* If isIgnoreErrors is true, then a table is being dropped. In this
86721 ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
86722 ** before actually dropping it in order to check FK constraints.
86723 ** If the parent table of an FK constraint on the current table is
86724 ** missing, behave as if it is empty. i.e. decrement the relevant
86725 ** FK counter for each row of the current table with non-NULL keys.
86727 Vdbe *v = sqlite3GetVdbe(pParse);
86728 int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
86729 for(i=0; i<pFKey->nCol; i++){
86730 int iReg = pFKey->aCol[i].iFrom + regOld + 1;
86731 sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump);
86733 sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
86735 continue;
86737 assert( pFKey->nCol==1 || (aiFree && pIdx) );
86739 if( aiFree ){
86740 aiCol = aiFree;
86741 }else{
86742 iCol = pFKey->aCol[0].iFrom;
86743 aiCol = &iCol;
86745 for(i=0; i<pFKey->nCol; i++){
86746 if( aiCol[i]==pTab->iPKey ){
86747 aiCol[i] = -1;
86749 #ifndef SQLITE_OMIT_AUTHORIZATION
86750 /* Request permission to read the parent key columns. If the
86751 ** authorization callback returns SQLITE_IGNORE, behave as if any
86752 ** values read from the parent table are NULL. */
86753 if( db->xAuth ){
86754 int rcauth;
86755 char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
86756 rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
86757 isIgnore = (rcauth==SQLITE_IGNORE);
86759 #endif
86762 /* Take a shared-cache advisory read-lock on the parent table. Allocate
86763 ** a cursor to use to search the unique index on the parent key columns
86764 ** in the parent table. */
86765 sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
86766 pParse->nTab++;
86768 if( regOld!=0 ){
86769 /* A row is being removed from the child table. Search for the parent.
86770 ** If the parent does not exist, removing the child row resolves an
86771 ** outstanding foreign key constraint violation. */
86772 fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore);
86774 if( regNew!=0 ){
86775 /* A row is being added to the child table. If a parent row cannot
86776 ** be found, adding the child row has violated the FK constraint. */
86777 fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);
86780 sqlite3DbFree(db, aiFree);
86783 /* Loop through all the foreign key constraints that refer to this table */
86784 for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
86785 Index *pIdx = 0; /* Foreign key index for pFKey */
86786 SrcList *pSrc;
86787 int *aiCol = 0;
86789 if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
86790 assert( regOld==0 && regNew!=0 );
86791 /* Inserting a single row into a parent table cannot cause an immediate
86792 ** foreign key violation. So do nothing in this case. */
86793 continue;
86796 if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
86797 if( !isIgnoreErrors || db->mallocFailed ) return;
86798 continue;
86800 assert( aiCol || pFKey->nCol==1 );
86802 /* Create a SrcList structure containing a single table (the table
86803 ** the foreign key that refers to this table is attached to). This
86804 ** is required for the sqlite3WhereXXX() interface. */
86805 pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
86806 if( pSrc ){
86807 struct SrcList_item *pItem = pSrc->a;
86808 pItem->pTab = pFKey->pFrom;
86809 pItem->zName = pFKey->pFrom->zName;
86810 pItem->pTab->nRef++;
86811 pItem->iCursor = pParse->nTab++;
86813 if( regNew!=0 ){
86814 fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
86816 if( regOld!=0 ){
86817 /* If there is a RESTRICT action configured for the current operation
86818 ** on the parent table of this FK, then throw an exception
86819 ** immediately if the FK constraint is violated, even if this is a
86820 ** deferred trigger. That's what RESTRICT means. To defer checking
86821 ** the constraint, the FK should specify NO ACTION (represented
86822 ** using OE_None). NO ACTION is the default. */
86823 fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
86825 pItem->zName = 0;
86826 sqlite3SrcListDelete(db, pSrc);
86828 sqlite3DbFree(db, aiCol);
86832 #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
86835 ** This function is called before generating code to update or delete a
86836 ** row contained in table pTab.
86838 SQLITE_PRIVATE u32 sqlite3FkOldmask(
86839 Parse *pParse, /* Parse context */
86840 Table *pTab /* Table being modified */
86842 u32 mask = 0;
86843 if( pParse->db->flags&SQLITE_ForeignKeys ){
86844 FKey *p;
86845 int i;
86846 for(p=pTab->pFKey; p; p=p->pNextFrom){
86847 for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
86849 for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
86850 Index *pIdx = 0;
86851 locateFkeyIndex(pParse, pTab, p, &pIdx, 0);
86852 if( pIdx ){
86853 for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
86857 return mask;
86861 ** This function is called before generating code to update or delete a
86862 ** row contained in table pTab. If the operation is a DELETE, then
86863 ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
86864 ** to an array of size N, where N is the number of columns in table pTab.
86865 ** If the i'th column is not modified by the UPDATE, then the corresponding
86866 ** entry in the aChange[] array is set to -1. If the column is modified,
86867 ** the value is 0 or greater. Parameter chngRowid is set to true if the
86868 ** UPDATE statement modifies the rowid fields of the table.
86870 ** If any foreign key processing will be required, this function returns
86871 ** true. If there is no foreign key related processing, this function
86872 ** returns false.
86874 SQLITE_PRIVATE int sqlite3FkRequired(
86875 Parse *pParse, /* Parse context */
86876 Table *pTab, /* Table being modified */
86877 int *aChange, /* Non-NULL for UPDATE operations */
86878 int chngRowid /* True for UPDATE that affects rowid */
86880 if( pParse->db->flags&SQLITE_ForeignKeys ){
86881 if( !aChange ){
86882 /* A DELETE operation. Foreign key processing is required if the
86883 ** table in question is either the child or parent table for any
86884 ** foreign key constraint. */
86885 return (sqlite3FkReferences(pTab) || pTab->pFKey);
86886 }else{
86887 /* This is an UPDATE. Foreign key processing is only required if the
86888 ** operation modifies one or more child or parent key columns. */
86889 int i;
86890 FKey *p;
86892 /* Check if any child key columns are being modified. */
86893 for(p=pTab->pFKey; p; p=p->pNextFrom){
86894 for(i=0; i<p->nCol; i++){
86895 int iChildKey = p->aCol[i].iFrom;
86896 if( aChange[iChildKey]>=0 ) return 1;
86897 if( iChildKey==pTab->iPKey && chngRowid ) return 1;
86901 /* Check if any parent key columns are being modified. */
86902 for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
86903 for(i=0; i<p->nCol; i++){
86904 char *zKey = p->aCol[i].zCol;
86905 int iKey;
86906 for(iKey=0; iKey<pTab->nCol; iKey++){
86907 Column *pCol = &pTab->aCol[iKey];
86908 if( (zKey ? !sqlite3StrICmp(pCol->zName, zKey) : pCol->isPrimKey) ){
86909 if( aChange[iKey]>=0 ) return 1;
86910 if( iKey==pTab->iPKey && chngRowid ) return 1;
86917 return 0;
86921 ** This function is called when an UPDATE or DELETE operation is being
86922 ** compiled on table pTab, which is the parent table of foreign-key pFKey.
86923 ** If the current operation is an UPDATE, then the pChanges parameter is
86924 ** passed a pointer to the list of columns being modified. If it is a
86925 ** DELETE, pChanges is passed a NULL pointer.
86927 ** It returns a pointer to a Trigger structure containing a trigger
86928 ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
86929 ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
86930 ** returned (these actions require no special handling by the triggers
86931 ** sub-system, code for them is created by fkScanChildren()).
86933 ** For example, if pFKey is the foreign key and pTab is table "p" in
86934 ** the following schema:
86936 ** CREATE TABLE p(pk PRIMARY KEY);
86937 ** CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
86939 ** then the returned trigger structure is equivalent to:
86941 ** CREATE TRIGGER ... DELETE ON p BEGIN
86942 ** DELETE FROM c WHERE ck = old.pk;
86943 ** END;
86945 ** The returned pointer is cached as part of the foreign key object. It
86946 ** is eventually freed along with the rest of the foreign key object by
86947 ** sqlite3FkDelete().
86949 static Trigger *fkActionTrigger(
86950 Parse *pParse, /* Parse context */
86951 Table *pTab, /* Table being updated or deleted from */
86952 FKey *pFKey, /* Foreign key to get action for */
86953 ExprList *pChanges /* Change-list for UPDATE, NULL for DELETE */
86955 sqlite3 *db = pParse->db; /* Database handle */
86956 int action; /* One of OE_None, OE_Cascade etc. */
86957 Trigger *pTrigger; /* Trigger definition to return */
86958 int iAction = (pChanges!=0); /* 1 for UPDATE, 0 for DELETE */
86960 action = pFKey->aAction[iAction];
86961 pTrigger = pFKey->apTrigger[iAction];
86963 if( action!=OE_None && !pTrigger ){
86964 u8 enableLookaside; /* Copy of db->lookaside.bEnabled */
86965 char const *zFrom; /* Name of child table */
86966 int nFrom; /* Length in bytes of zFrom */
86967 Index *pIdx = 0; /* Parent key index for this FK */
86968 int *aiCol = 0; /* child table cols -> parent key cols */
86969 TriggerStep *pStep = 0; /* First (only) step of trigger program */
86970 Expr *pWhere = 0; /* WHERE clause of trigger step */
86971 ExprList *pList = 0; /* Changes list if ON UPDATE CASCADE */
86972 Select *pSelect = 0; /* If RESTRICT, "SELECT RAISE(...)" */
86973 int i; /* Iterator variable */
86974 Expr *pWhen = 0; /* WHEN clause for the trigger */
86976 if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
86977 assert( aiCol || pFKey->nCol==1 );
86979 for(i=0; i<pFKey->nCol; i++){
86980 Token tOld = { "old", 3 }; /* Literal "old" token */
86981 Token tNew = { "new", 3 }; /* Literal "new" token */
86982 Token tFromCol; /* Name of column in child table */
86983 Token tToCol; /* Name of column in parent table */
86984 int iFromCol; /* Idx of column in child table */
86985 Expr *pEq; /* tFromCol = OLD.tToCol */
86987 iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
86988 assert( iFromCol>=0 );
86989 tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
86990 tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
86992 tToCol.n = sqlite3Strlen30(tToCol.z);
86993 tFromCol.n = sqlite3Strlen30(tFromCol.z);
86995 /* Create the expression "OLD.zToCol = zFromCol". It is important
86996 ** that the "OLD.zToCol" term is on the LHS of the = operator, so
86997 ** that the affinity and collation sequence associated with the
86998 ** parent table are used for the comparison. */
86999 pEq = sqlite3PExpr(pParse, TK_EQ,
87000 sqlite3PExpr(pParse, TK_DOT,
87001 sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
87002 sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
87003 , 0),
87004 sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
87005 , 0);
87006 pWhere = sqlite3ExprAnd(db, pWhere, pEq);
87008 /* For ON UPDATE, construct the next term of the WHEN clause.
87009 ** The final WHEN clause will be like this:
87011 ** WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
87013 if( pChanges ){
87014 pEq = sqlite3PExpr(pParse, TK_IS,
87015 sqlite3PExpr(pParse, TK_DOT,
87016 sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
87017 sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
87019 sqlite3PExpr(pParse, TK_DOT,
87020 sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
87021 sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
87024 pWhen = sqlite3ExprAnd(db, pWhen, pEq);
87027 if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
87028 Expr *pNew;
87029 if( action==OE_Cascade ){
87030 pNew = sqlite3PExpr(pParse, TK_DOT,
87031 sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
87032 sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
87033 , 0);
87034 }else if( action==OE_SetDflt ){
87035 Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
87036 if( pDflt ){
87037 pNew = sqlite3ExprDup(db, pDflt, 0);
87038 }else{
87039 pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
87041 }else{
87042 pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
87044 pList = sqlite3ExprListAppend(pParse, pList, pNew);
87045 sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
87048 sqlite3DbFree(db, aiCol);
87050 zFrom = pFKey->pFrom->zName;
87051 nFrom = sqlite3Strlen30(zFrom);
87053 if( action==OE_Restrict ){
87054 Token tFrom;
87055 Expr *pRaise;
87057 tFrom.z = zFrom;
87058 tFrom.n = nFrom;
87059 pRaise = sqlite3Expr(db, TK_RAISE, "foreign key constraint failed");
87060 if( pRaise ){
87061 pRaise->affinity = OE_Abort;
87063 pSelect = sqlite3SelectNew(pParse,
87064 sqlite3ExprListAppend(pParse, 0, pRaise),
87065 sqlite3SrcListAppend(db, 0, &tFrom, 0),
87066 pWhere,
87067 0, 0, 0, 0, 0, 0
87069 pWhere = 0;
87072 /* Disable lookaside memory allocation */
87073 enableLookaside = db->lookaside.bEnabled;
87074 db->lookaside.bEnabled = 0;
87076 pTrigger = (Trigger *)sqlite3DbMallocZero(db,
87077 sizeof(Trigger) + /* struct Trigger */
87078 sizeof(TriggerStep) + /* Single step in trigger program */
87079 nFrom + 1 /* Space for pStep->target.z */
87081 if( pTrigger ){
87082 pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
87083 pStep->target.z = (char *)&pStep[1];
87084 pStep->target.n = nFrom;
87085 memcpy((char *)pStep->target.z, zFrom, nFrom);
87087 pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
87088 pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
87089 pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
87090 if( pWhen ){
87091 pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
87092 pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
87096 /* Re-enable the lookaside buffer, if it was disabled earlier. */
87097 db->lookaside.bEnabled = enableLookaside;
87099 sqlite3ExprDelete(db, pWhere);
87100 sqlite3ExprDelete(db, pWhen);
87101 sqlite3ExprListDelete(db, pList);
87102 sqlite3SelectDelete(db, pSelect);
87103 if( db->mallocFailed==1 ){
87104 fkTriggerDelete(db, pTrigger);
87105 return 0;
87107 assert( pStep!=0 );
87109 switch( action ){
87110 case OE_Restrict:
87111 pStep->op = TK_SELECT;
87112 break;
87113 case OE_Cascade:
87114 if( !pChanges ){
87115 pStep->op = TK_DELETE;
87116 break;
87118 default:
87119 pStep->op = TK_UPDATE;
87121 pStep->pTrig = pTrigger;
87122 pTrigger->pSchema = pTab->pSchema;
87123 pTrigger->pTabSchema = pTab->pSchema;
87124 pFKey->apTrigger[iAction] = pTrigger;
87125 pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
87128 return pTrigger;
87132 ** This function is called when deleting or updating a row to implement
87133 ** any required CASCADE, SET NULL or SET DEFAULT actions.
87135 SQLITE_PRIVATE void sqlite3FkActions(
87136 Parse *pParse, /* Parse context */
87137 Table *pTab, /* Table being updated or deleted from */
87138 ExprList *pChanges, /* Change-list for UPDATE, NULL for DELETE */
87139 int regOld /* Address of array containing old row */
87141 /* If foreign-key support is enabled, iterate through all FKs that
87142 ** refer to table pTab. If there is an action associated with the FK
87143 ** for this operation (either update or delete), invoke the associated
87144 ** trigger sub-program. */
87145 if( pParse->db->flags&SQLITE_ForeignKeys ){
87146 FKey *pFKey; /* Iterator variable */
87147 for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
87148 Trigger *pAction = fkActionTrigger(pParse, pTab, pFKey, pChanges);
87149 if( pAction ){
87150 sqlite3CodeRowTriggerDirect(pParse, pAction, pTab, regOld, OE_Abort, 0);
87156 #endif /* ifndef SQLITE_OMIT_TRIGGER */
87159 ** Free all memory associated with foreign key definitions attached to
87160 ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
87161 ** hash table.
87163 SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
87164 FKey *pFKey; /* Iterator variable */
87165 FKey *pNext; /* Copy of pFKey->pNextFrom */
87167 assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
87168 for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
87170 /* Remove the FK from the fkeyHash hash table. */
87171 if( !db || db->pnBytesFreed==0 ){
87172 if( pFKey->pPrevTo ){
87173 pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
87174 }else{
87175 void *p = (void *)pFKey->pNextTo;
87176 const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
87177 sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), p);
87179 if( pFKey->pNextTo ){
87180 pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
87184 /* EV: R-30323-21917 Each foreign key constraint in SQLite is
87185 ** classified as either immediate or deferred.
87187 assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
87189 /* Delete any triggers created to implement actions for this FK. */
87190 #ifndef SQLITE_OMIT_TRIGGER
87191 fkTriggerDelete(db, pFKey->apTrigger[0]);
87192 fkTriggerDelete(db, pFKey->apTrigger[1]);
87193 #endif
87195 pNext = pFKey->pNextFrom;
87196 sqlite3DbFree(db, pFKey);
87199 #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
87201 /************** End of fkey.c ************************************************/
87202 /************** Begin file insert.c ******************************************/
87204 ** 2001 September 15
87206 ** The author disclaims copyright to this source code. In place of
87207 ** a legal notice, here is a blessing:
87209 ** May you do good and not evil.
87210 ** May you find forgiveness for yourself and forgive others.
87211 ** May you share freely, never taking more than you give.
87213 *************************************************************************
87214 ** This file contains C code routines that are called by the parser
87215 ** to handle INSERT statements in SQLite.
87219 ** Generate code that will open a table for reading.
87221 SQLITE_PRIVATE void sqlite3OpenTable(
87222 Parse *p, /* Generate code into this VDBE */
87223 int iCur, /* The cursor number of the table */
87224 int iDb, /* The database index in sqlite3.aDb[] */
87225 Table *pTab, /* The table to be opened */
87226 int opcode /* OP_OpenRead or OP_OpenWrite */
87228 Vdbe *v;
87229 if( IsVirtual(pTab) ) return;
87230 v = sqlite3GetVdbe(p);
87231 assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
87232 sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
87233 sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
87234 sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32);
87235 VdbeComment((v, "%s", pTab->zName));
87239 ** Return a pointer to the column affinity string associated with index
87240 ** pIdx. A column affinity string has one character for each column in
87241 ** the table, according to the affinity of the column:
87243 ** Character Column affinity
87244 ** ------------------------------
87245 ** 'a' TEXT
87246 ** 'b' NONE
87247 ** 'c' NUMERIC
87248 ** 'd' INTEGER
87249 ** 'e' REAL
87251 ** An extra 'b' is appended to the end of the string to cover the
87252 ** rowid that appears as the last column in every index.
87254 ** Memory for the buffer containing the column index affinity string
87255 ** is managed along with the rest of the Index structure. It will be
87256 ** released when sqlite3DeleteIndex() is called.
87258 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
87259 if( !pIdx->zColAff ){
87260 /* The first time a column affinity string for a particular index is
87261 ** required, it is allocated and populated here. It is then stored as
87262 ** a member of the Index structure for subsequent use.
87264 ** The column affinity string will eventually be deleted by
87265 ** sqliteDeleteIndex() when the Index structure itself is cleaned
87266 ** up.
87268 int n;
87269 Table *pTab = pIdx->pTable;
87270 sqlite3 *db = sqlite3VdbeDb(v);
87271 pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+2);
87272 if( !pIdx->zColAff ){
87273 db->mallocFailed = 1;
87274 return 0;
87276 for(n=0; n<pIdx->nColumn; n++){
87277 pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
87279 pIdx->zColAff[n++] = SQLITE_AFF_NONE;
87280 pIdx->zColAff[n] = 0;
87283 return pIdx->zColAff;
87287 ** Set P4 of the most recently inserted opcode to a column affinity
87288 ** string for table pTab. A column affinity string has one character
87289 ** for each column indexed by the index, according to the affinity of the
87290 ** column:
87292 ** Character Column affinity
87293 ** ------------------------------
87294 ** 'a' TEXT
87295 ** 'b' NONE
87296 ** 'c' NUMERIC
87297 ** 'd' INTEGER
87298 ** 'e' REAL
87300 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
87301 /* The first time a column affinity string for a particular table
87302 ** is required, it is allocated and populated here. It is then
87303 ** stored as a member of the Table structure for subsequent use.
87305 ** The column affinity string will eventually be deleted by
87306 ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
87308 if( !pTab->zColAff ){
87309 char *zColAff;
87310 int i;
87311 sqlite3 *db = sqlite3VdbeDb(v);
87313 zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
87314 if( !zColAff ){
87315 db->mallocFailed = 1;
87316 return;
87319 for(i=0; i<pTab->nCol; i++){
87320 zColAff[i] = pTab->aCol[i].affinity;
87322 zColAff[pTab->nCol] = '\0';
87324 pTab->zColAff = zColAff;
87327 sqlite3VdbeChangeP4(v, -1, pTab->zColAff, P4_TRANSIENT);
87331 ** Return non-zero if the table pTab in database iDb or any of its indices
87332 ** have been opened at any point in the VDBE program beginning at location
87333 ** iStartAddr throught the end of the program. This is used to see if
87334 ** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can
87335 ** run without using temporary table for the results of the SELECT.
87337 static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
87338 Vdbe *v = sqlite3GetVdbe(p);
87339 int i;
87340 int iEnd = sqlite3VdbeCurrentAddr(v);
87341 #ifndef SQLITE_OMIT_VIRTUALTABLE
87342 VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
87343 #endif
87345 for(i=iStartAddr; i<iEnd; i++){
87346 VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
87347 assert( pOp!=0 );
87348 if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
87349 Index *pIndex;
87350 int tnum = pOp->p2;
87351 if( tnum==pTab->tnum ){
87352 return 1;
87354 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
87355 if( tnum==pIndex->tnum ){
87356 return 1;
87360 #ifndef SQLITE_OMIT_VIRTUALTABLE
87361 if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
87362 assert( pOp->p4.pVtab!=0 );
87363 assert( pOp->p4type==P4_VTAB );
87364 return 1;
87366 #endif
87368 return 0;
87371 #ifndef SQLITE_OMIT_AUTOINCREMENT
87373 ** Locate or create an AutoincInfo structure associated with table pTab
87374 ** which is in database iDb. Return the register number for the register
87375 ** that holds the maximum rowid.
87377 ** There is at most one AutoincInfo structure per table even if the
87378 ** same table is autoincremented multiple times due to inserts within
87379 ** triggers. A new AutoincInfo structure is created if this is the
87380 ** first use of table pTab. On 2nd and subsequent uses, the original
87381 ** AutoincInfo structure is used.
87383 ** Three memory locations are allocated:
87385 ** (1) Register to hold the name of the pTab table.
87386 ** (2) Register to hold the maximum ROWID of pTab.
87387 ** (3) Register to hold the rowid in sqlite_sequence of pTab
87389 ** The 2nd register is the one that is returned. That is all the
87390 ** insert routine needs to know about.
87392 static int autoIncBegin(
87393 Parse *pParse, /* Parsing context */
87394 int iDb, /* Index of the database holding pTab */
87395 Table *pTab /* The table we are writing to */
87397 int memId = 0; /* Register holding maximum rowid */
87398 if( pTab->tabFlags & TF_Autoincrement ){
87399 Parse *pToplevel = sqlite3ParseToplevel(pParse);
87400 AutoincInfo *pInfo;
87402 pInfo = pToplevel->pAinc;
87403 while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
87404 if( pInfo==0 ){
87405 pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
87406 if( pInfo==0 ) return 0;
87407 pInfo->pNext = pToplevel->pAinc;
87408 pToplevel->pAinc = pInfo;
87409 pInfo->pTab = pTab;
87410 pInfo->iDb = iDb;
87411 pToplevel->nMem++; /* Register to hold name of table */
87412 pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */
87413 pToplevel->nMem++; /* Rowid in sqlite_sequence */
87415 memId = pInfo->regCtr;
87417 return memId;
87421 ** This routine generates code that will initialize all of the
87422 ** register used by the autoincrement tracker.
87424 SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
87425 AutoincInfo *p; /* Information about an AUTOINCREMENT */
87426 sqlite3 *db = pParse->db; /* The database connection */
87427 Db *pDb; /* Database only autoinc table */
87428 int memId; /* Register holding max rowid */
87429 int addr; /* A VDBE address */
87430 Vdbe *v = pParse->pVdbe; /* VDBE under construction */
87432 /* This routine is never called during trigger-generation. It is
87433 ** only called from the top-level */
87434 assert( pParse->pTriggerTab==0 );
87435 assert( pParse==sqlite3ParseToplevel(pParse) );
87437 assert( v ); /* We failed long ago if this is not so */
87438 for(p = pParse->pAinc; p; p = p->pNext){
87439 pDb = &db->aDb[p->iDb];
87440 memId = p->regCtr;
87441 assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
87442 sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
87443 addr = sqlite3VdbeCurrentAddr(v);
87444 sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
87445 sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
87446 sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
87447 sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
87448 sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
87449 sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
87450 sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
87451 sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
87452 sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);
87453 sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
87454 sqlite3VdbeAddOp0(v, OP_Close);
87459 ** Update the maximum rowid for an autoincrement calculation.
87461 ** This routine should be called when the top of the stack holds a
87462 ** new rowid that is about to be inserted. If that new rowid is
87463 ** larger than the maximum rowid in the memId memory cell, then the
87464 ** memory cell is updated. The stack is unchanged.
87466 static void autoIncStep(Parse *pParse, int memId, int regRowid){
87467 if( memId>0 ){
87468 sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
87473 ** This routine generates the code needed to write autoincrement
87474 ** maximum rowid values back into the sqlite_sequence register.
87475 ** Every statement that might do an INSERT into an autoincrement
87476 ** table (either directly or through triggers) needs to call this
87477 ** routine just before the "exit" code.
87479 SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
87480 AutoincInfo *p;
87481 Vdbe *v = pParse->pVdbe;
87482 sqlite3 *db = pParse->db;
87484 assert( v );
87485 for(p = pParse->pAinc; p; p = p->pNext){
87486 Db *pDb = &db->aDb[p->iDb];
87487 int j1, j2, j3, j4, j5;
87488 int iRec;
87489 int memId = p->regCtr;
87491 iRec = sqlite3GetTempReg(pParse);
87492 assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
87493 sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
87494 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
87495 j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
87496 j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
87497 j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
87498 sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
87499 sqlite3VdbeJumpHere(v, j2);
87500 sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
87501 j5 = sqlite3VdbeAddOp0(v, OP_Goto);
87502 sqlite3VdbeJumpHere(v, j4);
87503 sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
87504 sqlite3VdbeJumpHere(v, j1);
87505 sqlite3VdbeJumpHere(v, j5);
87506 sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
87507 sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
87508 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
87509 sqlite3VdbeAddOp0(v, OP_Close);
87510 sqlite3ReleaseTempReg(pParse, iRec);
87513 #else
87515 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
87516 ** above are all no-ops
87518 # define autoIncBegin(A,B,C) (0)
87519 # define autoIncStep(A,B,C)
87520 #endif /* SQLITE_OMIT_AUTOINCREMENT */
87523 /* Forward declaration */
87524 static int xferOptimization(
87525 Parse *pParse, /* Parser context */
87526 Table *pDest, /* The table we are inserting into */
87527 Select *pSelect, /* A SELECT statement to use as the data source */
87528 int onError, /* How to handle constraint errors */
87529 int iDbDest /* The database of pDest */
87533 ** This routine is call to handle SQL of the following forms:
87535 ** insert into TABLE (IDLIST) values(EXPRLIST)
87536 ** insert into TABLE (IDLIST) select
87538 ** The IDLIST following the table name is always optional. If omitted,
87539 ** then a list of all columns for the table is substituted. The IDLIST
87540 ** appears in the pColumn parameter. pColumn is NULL if IDLIST is omitted.
87542 ** The pList parameter holds EXPRLIST in the first form of the INSERT
87543 ** statement above, and pSelect is NULL. For the second form, pList is
87544 ** NULL and pSelect is a pointer to the select statement used to generate
87545 ** data for the insert.
87547 ** The code generated follows one of four templates. For a simple
87548 ** select with data coming from a VALUES clause, the code executes
87549 ** once straight down through. Pseudo-code follows (we call this
87550 ** the "1st template"):
87552 ** open write cursor to <table> and its indices
87553 ** puts VALUES clause expressions onto the stack
87554 ** write the resulting record into <table>
87555 ** cleanup
87557 ** The three remaining templates assume the statement is of the form
87559 ** INSERT INTO <table> SELECT ...
87561 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
87562 ** in other words if the SELECT pulls all columns from a single table
87563 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
87564 ** if <table2> and <table1> are distinct tables but have identical
87565 ** schemas, including all the same indices, then a special optimization
87566 ** is invoked that copies raw records from <table2> over to <table1>.
87567 ** See the xferOptimization() function for the implementation of this
87568 ** template. This is the 2nd template.
87570 ** open a write cursor to <table>
87571 ** open read cursor on <table2>
87572 ** transfer all records in <table2> over to <table>
87573 ** close cursors
87574 ** foreach index on <table>
87575 ** open a write cursor on the <table> index
87576 ** open a read cursor on the corresponding <table2> index
87577 ** transfer all records from the read to the write cursors
87578 ** close cursors
87579 ** end foreach
87581 ** The 3rd template is for when the second template does not apply
87582 ** and the SELECT clause does not read from <table> at any time.
87583 ** The generated code follows this template:
87585 ** EOF <- 0
87586 ** X <- A
87587 ** goto B
87588 ** A: setup for the SELECT
87589 ** loop over the rows in the SELECT
87590 ** load values into registers R..R+n
87591 ** yield X
87592 ** end loop
87593 ** cleanup after the SELECT
87594 ** EOF <- 1
87595 ** yield X
87596 ** goto A
87597 ** B: open write cursor to <table> and its indices
87598 ** C: yield X
87599 ** if EOF goto D
87600 ** insert the select result into <table> from R..R+n
87601 ** goto C
87602 ** D: cleanup
87604 ** The 4th template is used if the insert statement takes its
87605 ** values from a SELECT but the data is being inserted into a table
87606 ** that is also read as part of the SELECT. In the third form,
87607 ** we have to use a intermediate table to store the results of
87608 ** the select. The template is like this:
87610 ** EOF <- 0
87611 ** X <- A
87612 ** goto B
87613 ** A: setup for the SELECT
87614 ** loop over the tables in the SELECT
87615 ** load value into register R..R+n
87616 ** yield X
87617 ** end loop
87618 ** cleanup after the SELECT
87619 ** EOF <- 1
87620 ** yield X
87621 ** halt-error
87622 ** B: open temp table
87623 ** L: yield X
87624 ** if EOF goto M
87625 ** insert row from R..R+n into temp table
87626 ** goto L
87627 ** M: open write cursor to <table> and its indices
87628 ** rewind temp table
87629 ** C: loop over rows of intermediate table
87630 ** transfer values form intermediate table into <table>
87631 ** end loop
87632 ** D: cleanup
87634 SQLITE_PRIVATE void sqlite3Insert(
87635 Parse *pParse, /* Parser context */
87636 SrcList *pTabList, /* Name of table into which we are inserting */
87637 ExprList *pList, /* List of values to be inserted */
87638 Select *pSelect, /* A SELECT statement to use as the data source */
87639 IdList *pColumn, /* Column names corresponding to IDLIST. */
87640 int onError /* How to handle constraint errors */
87642 sqlite3 *db; /* The main database structure */
87643 Table *pTab; /* The table to insert into. aka TABLE */
87644 char *zTab; /* Name of the table into which we are inserting */
87645 const char *zDb; /* Name of the database holding this table */
87646 int i, j, idx; /* Loop counters */
87647 Vdbe *v; /* Generate code into this virtual machine */
87648 Index *pIdx; /* For looping over indices of the table */
87649 int nColumn; /* Number of columns in the data */
87650 int nHidden = 0; /* Number of hidden columns if TABLE is virtual */
87651 int baseCur = 0; /* VDBE Cursor number for pTab */
87652 int keyColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
87653 int endOfLoop; /* Label for the end of the insertion loop */
87654 int useTempTable = 0; /* Store SELECT results in intermediate table */
87655 int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
87656 int addrInsTop = 0; /* Jump to label "D" */
87657 int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */
87658 int addrSelect = 0; /* Address of coroutine that implements the SELECT */
87659 SelectDest dest; /* Destination for SELECT on rhs of INSERT */
87660 int iDb; /* Index of database holding TABLE */
87661 Db *pDb; /* The database containing table being inserted into */
87662 int appendFlag = 0; /* True if the insert is likely to be an append */
87664 /* Register allocations */
87665 int regFromSelect = 0;/* Base register for data coming from SELECT */
87666 int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */
87667 int regRowCount = 0; /* Memory cell used for the row counter */
87668 int regIns; /* Block of regs holding rowid+data being inserted */
87669 int regRowid; /* registers holding insert rowid */
87670 int regData; /* register holding first column to insert */
87671 int regEof = 0; /* Register recording end of SELECT data */
87672 int *aRegIdx = 0; /* One register allocated to each index */
87674 #ifndef SQLITE_OMIT_TRIGGER
87675 int isView; /* True if attempting to insert into a view */
87676 Trigger *pTrigger; /* List of triggers on pTab, if required */
87677 int tmask; /* Mask of trigger times */
87678 #endif
87680 db = pParse->db;
87681 memset(&dest, 0, sizeof(dest));
87682 if( pParse->nErr || db->mallocFailed ){
87683 goto insert_cleanup;
87686 /* Locate the table into which we will be inserting new information.
87688 assert( pTabList->nSrc==1 );
87689 zTab = pTabList->a[0].zName;
87690 if( NEVER(zTab==0) ) goto insert_cleanup;
87691 pTab = sqlite3SrcListLookup(pParse, pTabList);
87692 if( pTab==0 ){
87693 goto insert_cleanup;
87695 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
87696 assert( iDb<db->nDb );
87697 pDb = &db->aDb[iDb];
87698 zDb = pDb->zName;
87699 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
87700 goto insert_cleanup;
87703 /* Figure out if we have any triggers and if the table being
87704 ** inserted into is a view
87706 #ifndef SQLITE_OMIT_TRIGGER
87707 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
87708 isView = pTab->pSelect!=0;
87709 #else
87710 # define pTrigger 0
87711 # define tmask 0
87712 # define isView 0
87713 #endif
87714 #ifdef SQLITE_OMIT_VIEW
87715 # undef isView
87716 # define isView 0
87717 #endif
87718 assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
87720 /* If pTab is really a view, make sure it has been initialized.
87721 ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
87722 ** module table).
87724 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
87725 goto insert_cleanup;
87728 /* Ensure that:
87729 * (a) the table is not read-only,
87730 * (b) that if it is a view then ON INSERT triggers exist
87732 if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
87733 goto insert_cleanup;
87736 /* Allocate a VDBE
87738 v = sqlite3GetVdbe(pParse);
87739 if( v==0 ) goto insert_cleanup;
87740 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
87741 sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
87743 #ifndef SQLITE_OMIT_XFER_OPT
87744 /* If the statement is of the form
87746 ** INSERT INTO <table1> SELECT * FROM <table2>;
87748 ** Then special optimizations can be applied that make the transfer
87749 ** very fast and which reduce fragmentation of indices.
87751 ** This is the 2nd template.
87753 if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
87754 assert( !pTrigger );
87755 assert( pList==0 );
87756 goto insert_end;
87758 #endif /* SQLITE_OMIT_XFER_OPT */
87760 /* If this is an AUTOINCREMENT table, look up the sequence number in the
87761 ** sqlite_sequence table and store it in memory cell regAutoinc.
87763 regAutoinc = autoIncBegin(pParse, iDb, pTab);
87765 /* Figure out how many columns of data are supplied. If the data
87766 ** is coming from a SELECT statement, then generate a co-routine that
87767 ** produces a single row of the SELECT on each invocation. The
87768 ** co-routine is the common header to the 3rd and 4th templates.
87770 if( pSelect ){
87771 /* Data is coming from a SELECT. Generate code to implement that SELECT
87772 ** as a co-routine. The code is common to both the 3rd and 4th
87773 ** templates:
87775 ** EOF <- 0
87776 ** X <- A
87777 ** goto B
87778 ** A: setup for the SELECT
87779 ** loop over the tables in the SELECT
87780 ** load value into register R..R+n
87781 ** yield X
87782 ** end loop
87783 ** cleanup after the SELECT
87784 ** EOF <- 1
87785 ** yield X
87786 ** halt-error
87788 ** On each invocation of the co-routine, it puts a single row of the
87789 ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1.
87790 ** (These output registers are allocated by sqlite3Select().) When
87791 ** the SELECT completes, it sets the EOF flag stored in regEof.
87793 int rc, j1;
87795 regEof = ++pParse->nMem;
87796 sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof); /* EOF <- 0 */
87797 VdbeComment((v, "SELECT eof flag"));
87798 sqlite3SelectDestInit(&dest, SRT_Coroutine, ++pParse->nMem);
87799 addrSelect = sqlite3VdbeCurrentAddr(v)+2;
87800 sqlite3VdbeAddOp2(v, OP_Integer, addrSelect-1, dest.iParm);
87801 j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
87802 VdbeComment((v, "Jump over SELECT coroutine"));
87804 /* Resolve the expressions in the SELECT statement and execute it. */
87805 rc = sqlite3Select(pParse, pSelect, &dest);
87806 assert( pParse->nErr==0 || rc );
87807 if( rc || NEVER(pParse->nErr) || db->mallocFailed ){
87808 goto insert_cleanup;
87810 sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof); /* EOF <- 1 */
87811 sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm); /* yield X */
87812 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
87813 VdbeComment((v, "End of SELECT coroutine"));
87814 sqlite3VdbeJumpHere(v, j1); /* label B: */
87816 regFromSelect = dest.iMem;
87817 assert( pSelect->pEList );
87818 nColumn = pSelect->pEList->nExpr;
87819 assert( dest.nMem==nColumn );
87821 /* Set useTempTable to TRUE if the result of the SELECT statement
87822 ** should be written into a temporary table (template 4). Set to
87823 ** FALSE if each* row of the SELECT can be written directly into
87824 ** the destination table (template 3).
87826 ** A temp table must be used if the table being updated is also one
87827 ** of the tables being read by the SELECT statement. Also use a
87828 ** temp table in the case of row triggers.
87830 if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
87831 useTempTable = 1;
87834 if( useTempTable ){
87835 /* Invoke the coroutine to extract information from the SELECT
87836 ** and add it to a transient table srcTab. The code generated
87837 ** here is from the 4th template:
87839 ** B: open temp table
87840 ** L: yield X
87841 ** if EOF goto M
87842 ** insert row from R..R+n into temp table
87843 ** goto L
87844 ** M: ...
87846 int regRec; /* Register to hold packed record */
87847 int regTempRowid; /* Register to hold temp table ROWID */
87848 int addrTop; /* Label "L" */
87849 int addrIf; /* Address of jump to M */
87851 srcTab = pParse->nTab++;
87852 regRec = sqlite3GetTempReg(pParse);
87853 regTempRowid = sqlite3GetTempReg(pParse);
87854 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
87855 addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
87856 addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
87857 sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
87858 sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
87859 sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
87860 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
87861 sqlite3VdbeJumpHere(v, addrIf);
87862 sqlite3ReleaseTempReg(pParse, regRec);
87863 sqlite3ReleaseTempReg(pParse, regTempRowid);
87865 }else{
87866 /* This is the case if the data for the INSERT is coming from a VALUES
87867 ** clause
87869 NameContext sNC;
87870 memset(&sNC, 0, sizeof(sNC));
87871 sNC.pParse = pParse;
87872 srcTab = -1;
87873 assert( useTempTable==0 );
87874 nColumn = pList ? pList->nExpr : 0;
87875 for(i=0; i<nColumn; i++){
87876 if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
87877 goto insert_cleanup;
87882 /* Make sure the number of columns in the source data matches the number
87883 ** of columns to be inserted into the table.
87885 if( IsVirtual(pTab) ){
87886 for(i=0; i<pTab->nCol; i++){
87887 nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
87890 if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
87891 sqlite3ErrorMsg(pParse,
87892 "table %S has %d columns but %d values were supplied",
87893 pTabList, 0, pTab->nCol-nHidden, nColumn);
87894 goto insert_cleanup;
87896 if( pColumn!=0 && nColumn!=pColumn->nId ){
87897 sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
87898 goto insert_cleanup;
87901 /* If the INSERT statement included an IDLIST term, then make sure
87902 ** all elements of the IDLIST really are columns of the table and
87903 ** remember the column indices.
87905 ** If the table has an INTEGER PRIMARY KEY column and that column
87906 ** is named in the IDLIST, then record in the keyColumn variable
87907 ** the index into IDLIST of the primary key column. keyColumn is
87908 ** the index of the primary key as it appears in IDLIST, not as
87909 ** is appears in the original table. (The index of the primary
87910 ** key in the original table is pTab->iPKey.)
87912 if( pColumn ){
87913 for(i=0; i<pColumn->nId; i++){
87914 pColumn->a[i].idx = -1;
87916 for(i=0; i<pColumn->nId; i++){
87917 for(j=0; j<pTab->nCol; j++){
87918 if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
87919 pColumn->a[i].idx = j;
87920 if( j==pTab->iPKey ){
87921 keyColumn = i;
87923 break;
87926 if( j>=pTab->nCol ){
87927 if( sqlite3IsRowid(pColumn->a[i].zName) ){
87928 keyColumn = i;
87929 }else{
87930 sqlite3ErrorMsg(pParse, "table %S has no column named %s",
87931 pTabList, 0, pColumn->a[i].zName);
87932 pParse->checkSchema = 1;
87933 goto insert_cleanup;
87939 /* If there is no IDLIST term but the table has an integer primary
87940 ** key, the set the keyColumn variable to the primary key column index
87941 ** in the original table definition.
87943 if( pColumn==0 && nColumn>0 ){
87944 keyColumn = pTab->iPKey;
87947 /* Initialize the count of rows to be inserted
87949 if( db->flags & SQLITE_CountRows ){
87950 regRowCount = ++pParse->nMem;
87951 sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
87954 /* If this is not a view, open the table and and all indices */
87955 if( !isView ){
87956 int nIdx;
87958 baseCur = pParse->nTab;
87959 nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
87960 aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
87961 if( aRegIdx==0 ){
87962 goto insert_cleanup;
87964 for(i=0; i<nIdx; i++){
87965 aRegIdx[i] = ++pParse->nMem;
87969 /* This is the top of the main insertion loop */
87970 if( useTempTable ){
87971 /* This block codes the top of loop only. The complete loop is the
87972 ** following pseudocode (template 4):
87974 ** rewind temp table
87975 ** C: loop over rows of intermediate table
87976 ** transfer values form intermediate table into <table>
87977 ** end loop
87978 ** D: ...
87980 addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
87981 addrCont = sqlite3VdbeCurrentAddr(v);
87982 }else if( pSelect ){
87983 /* This block codes the top of loop only. The complete loop is the
87984 ** following pseudocode (template 3):
87986 ** C: yield X
87987 ** if EOF goto D
87988 ** insert the select result into <table> from R..R+n
87989 ** goto C
87990 ** D: ...
87992 addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
87993 addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
87996 /* Allocate registers for holding the rowid of the new row,
87997 ** the content of the new row, and the assemblied row record.
87999 regRowid = regIns = pParse->nMem+1;
88000 pParse->nMem += pTab->nCol + 1;
88001 if( IsVirtual(pTab) ){
88002 regRowid++;
88003 pParse->nMem++;
88005 regData = regRowid+1;
88007 /* Run the BEFORE and INSTEAD OF triggers, if there are any
88009 endOfLoop = sqlite3VdbeMakeLabel(v);
88010 if( tmask & TRIGGER_BEFORE ){
88011 int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
88013 /* build the NEW.* reference row. Note that if there is an INTEGER
88014 ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
88015 ** translated into a unique ID for the row. But on a BEFORE trigger,
88016 ** we do not know what the unique ID will be (because the insert has
88017 ** not happened yet) so we substitute a rowid of -1
88019 if( keyColumn<0 ){
88020 sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
88021 }else{
88022 int j1;
88023 if( useTempTable ){
88024 sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols);
88025 }else{
88026 assert( pSelect==0 ); /* Otherwise useTempTable is true */
88027 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols);
88029 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
88030 sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
88031 sqlite3VdbeJumpHere(v, j1);
88032 sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
88035 /* Cannot have triggers on a virtual table. If it were possible,
88036 ** this block would have to account for hidden column.
88038 assert( !IsVirtual(pTab) );
88040 /* Create the new column data
88042 for(i=0; i<pTab->nCol; i++){
88043 if( pColumn==0 ){
88044 j = i;
88045 }else{
88046 for(j=0; j<pColumn->nId; j++){
88047 if( pColumn->a[j].idx==i ) break;
88050 if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
88051 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
88052 }else if( useTempTable ){
88053 sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
88054 }else{
88055 assert( pSelect==0 ); /* Otherwise useTempTable is true */
88056 sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
88060 /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
88061 ** do not attempt any conversions before assembling the record.
88062 ** If this is a real table, attempt conversions as required by the
88063 ** table column affinities.
88065 if( !isView ){
88066 sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
88067 sqlite3TableAffinityStr(v, pTab);
88070 /* Fire BEFORE or INSTEAD OF triggers */
88071 sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
88072 pTab, regCols-pTab->nCol-1, onError, endOfLoop);
88074 sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
88077 /* Push the record number for the new entry onto the stack. The
88078 ** record number is a randomly generate integer created by NewRowid
88079 ** except when the table has an INTEGER PRIMARY KEY column, in which
88080 ** case the record number is the same as that column.
88082 if( !isView ){
88083 if( IsVirtual(pTab) ){
88084 /* The row that the VUpdate opcode will delete: none */
88085 sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
88087 if( keyColumn>=0 ){
88088 if( useTempTable ){
88089 sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
88090 }else if( pSelect ){
88091 sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
88092 }else{
88093 VdbeOp *pOp;
88094 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
88095 pOp = sqlite3VdbeGetOp(v, -1);
88096 if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
88097 appendFlag = 1;
88098 pOp->opcode = OP_NewRowid;
88099 pOp->p1 = baseCur;
88100 pOp->p2 = regRowid;
88101 pOp->p3 = regAutoinc;
88104 /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
88105 ** to generate a unique primary key value.
88107 if( !appendFlag ){
88108 int j1;
88109 if( !IsVirtual(pTab) ){
88110 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
88111 sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
88112 sqlite3VdbeJumpHere(v, j1);
88113 }else{
88114 j1 = sqlite3VdbeCurrentAddr(v);
88115 sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
88117 sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
88119 }else if( IsVirtual(pTab) ){
88120 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
88121 }else{
88122 sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
88123 appendFlag = 1;
88125 autoIncStep(pParse, regAutoinc, regRowid);
88127 /* Push onto the stack, data for all columns of the new entry, beginning
88128 ** with the first column.
88130 nHidden = 0;
88131 for(i=0; i<pTab->nCol; i++){
88132 int iRegStore = regRowid+1+i;
88133 if( i==pTab->iPKey ){
88134 /* The value of the INTEGER PRIMARY KEY column is always a NULL.
88135 ** Whenever this column is read, the record number will be substituted
88136 ** in its place. So will fill this column with a NULL to avoid
88137 ** taking up data space with information that will never be used. */
88138 sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
88139 continue;
88141 if( pColumn==0 ){
88142 if( IsHiddenColumn(&pTab->aCol[i]) ){
88143 assert( IsVirtual(pTab) );
88144 j = -1;
88145 nHidden++;
88146 }else{
88147 j = i - nHidden;
88149 }else{
88150 for(j=0; j<pColumn->nId; j++){
88151 if( pColumn->a[j].idx==i ) break;
88154 if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
88155 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
88156 }else if( useTempTable ){
88157 sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
88158 }else if( pSelect ){
88159 sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
88160 }else{
88161 sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
88165 /* Generate code to check constraints and generate index keys and
88166 ** do the insertion.
88168 #ifndef SQLITE_OMIT_VIRTUALTABLE
88169 if( IsVirtual(pTab) ){
88170 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
88171 sqlite3VtabMakeWritable(pParse, pTab);
88172 sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
88173 sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
88174 sqlite3MayAbort(pParse);
88175 }else
88176 #endif
88178 int isReplace; /* Set to true if constraints may cause a replace */
88179 sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
88180 keyColumn>=0, 0, onError, endOfLoop, &isReplace
88182 sqlite3FkCheck(pParse, pTab, 0, regIns);
88183 sqlite3CompleteInsertion(
88184 pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0
88189 /* Update the count of rows that are inserted
88191 if( (db->flags & SQLITE_CountRows)!=0 ){
88192 sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
88195 if( pTrigger ){
88196 /* Code AFTER triggers */
88197 sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
88198 pTab, regData-2-pTab->nCol, onError, endOfLoop);
88201 /* The bottom of the main insertion loop, if the data source
88202 ** is a SELECT statement.
88204 sqlite3VdbeResolveLabel(v, endOfLoop);
88205 if( useTempTable ){
88206 sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
88207 sqlite3VdbeJumpHere(v, addrInsTop);
88208 sqlite3VdbeAddOp1(v, OP_Close, srcTab);
88209 }else if( pSelect ){
88210 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
88211 sqlite3VdbeJumpHere(v, addrInsTop);
88214 if( !IsVirtual(pTab) && !isView ){
88215 /* Close all tables opened */
88216 sqlite3VdbeAddOp1(v, OP_Close, baseCur);
88217 for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
88218 sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
88222 insert_end:
88223 /* Update the sqlite_sequence table by storing the content of the
88224 ** maximum rowid counter values recorded while inserting into
88225 ** autoincrement tables.
88227 if( pParse->nested==0 && pParse->pTriggerTab==0 ){
88228 sqlite3AutoincrementEnd(pParse);
88232 ** Return the number of rows inserted. If this routine is
88233 ** generating code because of a call to sqlite3NestedParse(), do not
88234 ** invoke the callback function.
88236 if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
88237 sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
88238 sqlite3VdbeSetNumCols(v, 1);
88239 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
88242 insert_cleanup:
88243 sqlite3SrcListDelete(db, pTabList);
88244 sqlite3ExprListDelete(db, pList);
88245 sqlite3SelectDelete(db, pSelect);
88246 sqlite3IdListDelete(db, pColumn);
88247 sqlite3DbFree(db, aRegIdx);
88250 /* Make sure "isView" and other macros defined above are undefined. Otherwise
88251 ** thely may interfere with compilation of other functions in this file
88252 ** (or in another file, if this file becomes part of the amalgamation). */
88253 #ifdef isView
88254 #undef isView
88255 #endif
88256 #ifdef pTrigger
88257 #undef pTrigger
88258 #endif
88259 #ifdef tmask
88260 #undef tmask
88261 #endif
88265 ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
88267 ** The input is a range of consecutive registers as follows:
88269 ** 1. The rowid of the row after the update.
88271 ** 2. The data in the first column of the entry after the update.
88273 ** i. Data from middle columns...
88275 ** N. The data in the last column of the entry after the update.
88277 ** The regRowid parameter is the index of the register containing (1).
88279 ** If isUpdate is true and rowidChng is non-zero, then rowidChng contains
88280 ** the address of a register containing the rowid before the update takes
88281 ** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate
88282 ** is false, indicating an INSERT statement, then a non-zero rowidChng
88283 ** indicates that the rowid was explicitly specified as part of the
88284 ** INSERT statement. If rowidChng is false, it means that the rowid is
88285 ** computed automatically in an insert or that the rowid value is not
88286 ** modified by an update.
88288 ** The code generated by this routine store new index entries into
88289 ** registers identified by aRegIdx[]. No index entry is created for
88290 ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is
88291 ** the same as the order of indices on the linked list of indices
88292 ** attached to the table.
88294 ** This routine also generates code to check constraints. NOT NULL,
88295 ** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
88296 ** then the appropriate action is performed. There are five possible
88297 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
88299 ** Constraint type Action What Happens
88300 ** --------------- ---------- ----------------------------------------
88301 ** any ROLLBACK The current transaction is rolled back and
88302 ** sqlite3_exec() returns immediately with a
88303 ** return code of SQLITE_CONSTRAINT.
88305 ** any ABORT Back out changes from the current command
88306 ** only (do not do a complete rollback) then
88307 ** cause sqlite3_exec() to return immediately
88308 ** with SQLITE_CONSTRAINT.
88310 ** any FAIL Sqlite_exec() returns immediately with a
88311 ** return code of SQLITE_CONSTRAINT. The
88312 ** transaction is not rolled back and any
88313 ** prior changes are retained.
88315 ** any IGNORE The record number and data is popped from
88316 ** the stack and there is an immediate jump
88317 ** to label ignoreDest.
88319 ** NOT NULL REPLACE The NULL value is replace by the default
88320 ** value for that column. If the default value
88321 ** is NULL, the action is the same as ABORT.
88323 ** UNIQUE REPLACE The other row that conflicts with the row
88324 ** being inserted is removed.
88326 ** CHECK REPLACE Illegal. The results in an exception.
88328 ** Which action to take is determined by the overrideError parameter.
88329 ** Or if overrideError==OE_Default, then the pParse->onError parameter
88330 ** is used. Or if pParse->onError==OE_Default then the onError value
88331 ** for the constraint is used.
88333 ** The calling routine must open a read/write cursor for pTab with
88334 ** cursor number "baseCur". All indices of pTab must also have open
88335 ** read/write cursors with cursor number baseCur+i for the i-th cursor.
88336 ** Except, if there is no possibility of a REPLACE action then
88337 ** cursors do not need to be open for indices where aRegIdx[i]==0.
88339 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
88340 Parse *pParse, /* The parser context */
88341 Table *pTab, /* the table into which we are inserting */
88342 int baseCur, /* Index of a read/write cursor pointing at pTab */
88343 int regRowid, /* Index of the range of input registers */
88344 int *aRegIdx, /* Register used by each index. 0 for unused indices */
88345 int rowidChng, /* True if the rowid might collide with existing entry */
88346 int isUpdate, /* True for UPDATE, False for INSERT */
88347 int overrideError, /* Override onError to this if not OE_Default */
88348 int ignoreDest, /* Jump to this label on an OE_Ignore resolution */
88349 int *pbMayReplace /* OUT: Set to true if constraint may cause a replace */
88351 int i; /* loop counter */
88352 Vdbe *v; /* VDBE under constrution */
88353 int nCol; /* Number of columns */
88354 int onError; /* Conflict resolution strategy */
88355 int j1; /* Addresss of jump instruction */
88356 int j2 = 0, j3; /* Addresses of jump instructions */
88357 int regData; /* Register containing first data column */
88358 int iCur; /* Table cursor number */
88359 Index *pIdx; /* Pointer to one of the indices */
88360 int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
88361 int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid;
88363 v = sqlite3GetVdbe(pParse);
88364 assert( v!=0 );
88365 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
88366 nCol = pTab->nCol;
88367 regData = regRowid + 1;
88369 /* Test all NOT NULL constraints.
88371 for(i=0; i<nCol; i++){
88372 if( i==pTab->iPKey ){
88373 continue;
88375 onError = pTab->aCol[i].notNull;
88376 if( onError==OE_None ) continue;
88377 if( overrideError!=OE_Default ){
88378 onError = overrideError;
88379 }else if( onError==OE_Default ){
88380 onError = OE_Abort;
88382 if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
88383 onError = OE_Abort;
88385 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
88386 || onError==OE_Ignore || onError==OE_Replace );
88387 switch( onError ){
88388 case OE_Abort:
88389 sqlite3MayAbort(pParse);
88390 case OE_Rollback:
88391 case OE_Fail: {
88392 char *zMsg;
88393 sqlite3VdbeAddOp3(v, OP_HaltIfNull,
88394 SQLITE_CONSTRAINT, onError, regData+i);
88395 zMsg = sqlite3MPrintf(pParse->db, "%s.%s may not be NULL",
88396 pTab->zName, pTab->aCol[i].zName);
88397 sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
88398 break;
88400 case OE_Ignore: {
88401 sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
88402 break;
88404 default: {
88405 assert( onError==OE_Replace );
88406 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
88407 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
88408 sqlite3VdbeJumpHere(v, j1);
88409 break;
88414 /* Test all CHECK constraints
88416 #ifndef SQLITE_OMIT_CHECK
88417 if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
88418 int allOk = sqlite3VdbeMakeLabel(v);
88419 pParse->ckBase = regData;
88420 sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL);
88421 onError = overrideError!=OE_Default ? overrideError : OE_Abort;
88422 if( onError==OE_Ignore ){
88423 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
88424 }else{
88425 if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
88426 sqlite3HaltConstraint(pParse, onError, 0, 0);
88428 sqlite3VdbeResolveLabel(v, allOk);
88430 #endif /* !defined(SQLITE_OMIT_CHECK) */
88432 /* If we have an INTEGER PRIMARY KEY, make sure the primary key
88433 ** of the new record does not previously exist. Except, if this
88434 ** is an UPDATE and the primary key is not changing, that is OK.
88436 if( rowidChng ){
88437 onError = pTab->keyConf;
88438 if( overrideError!=OE_Default ){
88439 onError = overrideError;
88440 }else if( onError==OE_Default ){
88441 onError = OE_Abort;
88444 if( isUpdate ){
88445 j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng);
88447 j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
88448 switch( onError ){
88449 default: {
88450 onError = OE_Abort;
88451 /* Fall thru into the next case */
88453 case OE_Rollback:
88454 case OE_Abort:
88455 case OE_Fail: {
88456 sqlite3HaltConstraint(
88457 pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
88458 break;
88460 case OE_Replace: {
88461 /* If there are DELETE triggers on this table and the
88462 ** recursive-triggers flag is set, call GenerateRowDelete() to
88463 ** remove the conflicting row from the the table. This will fire
88464 ** the triggers and remove both the table and index b-tree entries.
88466 ** Otherwise, if there are no triggers or the recursive-triggers
88467 ** flag is not set, but the table has one or more indexes, call
88468 ** GenerateRowIndexDelete(). This removes the index b-tree entries
88469 ** only. The table b-tree entry will be replaced by the new entry
88470 ** when it is inserted.
88472 ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
88473 ** also invoke MultiWrite() to indicate that this VDBE may require
88474 ** statement rollback (if the statement is aborted after the delete
88475 ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
88476 ** but being more selective here allows statements like:
88478 ** REPLACE INTO t(rowid) VALUES($newrowid)
88480 ** to run without a statement journal if there are no indexes on the
88481 ** table.
88483 Trigger *pTrigger = 0;
88484 if( pParse->db->flags&SQLITE_RecTriggers ){
88485 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
88487 if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
88488 sqlite3MultiWrite(pParse);
88489 sqlite3GenerateRowDelete(
88490 pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace
88492 }else if( pTab->pIndex ){
88493 sqlite3MultiWrite(pParse);
88494 sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
88496 seenReplace = 1;
88497 break;
88499 case OE_Ignore: {
88500 assert( seenReplace==0 );
88501 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
88502 break;
88505 sqlite3VdbeJumpHere(v, j3);
88506 if( isUpdate ){
88507 sqlite3VdbeJumpHere(v, j2);
88511 /* Test all UNIQUE constraints by creating entries for each UNIQUE
88512 ** index and making sure that duplicate entries do not already exist.
88513 ** Add the new records to the indices as we go.
88515 for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
88516 int regIdx;
88517 int regR;
88519 if( aRegIdx[iCur]==0 ) continue; /* Skip unused indices */
88521 /* Create a key for accessing the index entry */
88522 regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
88523 for(i=0; i<pIdx->nColumn; i++){
88524 int idx = pIdx->aiColumn[i];
88525 if( idx==pTab->iPKey ){
88526 sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
88527 }else{
88528 sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
88531 sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
88532 sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
88533 sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), P4_TRANSIENT);
88534 sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
88536 /* Find out what action to take in case there is an indexing conflict */
88537 onError = pIdx->onError;
88538 if( onError==OE_None ){
88539 sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
88540 continue; /* pIdx is not a UNIQUE index */
88542 if( overrideError!=OE_Default ){
88543 onError = overrideError;
88544 }else if( onError==OE_Default ){
88545 onError = OE_Abort;
88547 if( seenReplace ){
88548 if( onError==OE_Ignore ) onError = OE_Replace;
88549 else if( onError==OE_Fail ) onError = OE_Abort;
88552 /* Check to see if the new index entry will be unique */
88553 regR = sqlite3GetTempReg(pParse);
88554 sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR);
88555 j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
88556 regR, SQLITE_INT_TO_PTR(regIdx),
88557 P4_INT32);
88558 sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
88560 /* Generate code that executes if the new index entry is not unique */
88561 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
88562 || onError==OE_Ignore || onError==OE_Replace );
88563 switch( onError ){
88564 case OE_Rollback:
88565 case OE_Abort:
88566 case OE_Fail: {
88567 int j;
88568 StrAccum errMsg;
88569 const char *zSep;
88570 char *zErr;
88572 sqlite3StrAccumInit(&errMsg, 0, 0, 200);
88573 errMsg.db = pParse->db;
88574 zSep = pIdx->nColumn>1 ? "columns " : "column ";
88575 for(j=0; j<pIdx->nColumn; j++){
88576 char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
88577 sqlite3StrAccumAppend(&errMsg, zSep, -1);
88578 zSep = ", ";
88579 sqlite3StrAccumAppend(&errMsg, zCol, -1);
88581 sqlite3StrAccumAppend(&errMsg,
88582 pIdx->nColumn>1 ? " are not unique" : " is not unique", -1);
88583 zErr = sqlite3StrAccumFinish(&errMsg);
88584 sqlite3HaltConstraint(pParse, onError, zErr, 0);
88585 sqlite3DbFree(errMsg.db, zErr);
88586 break;
88588 case OE_Ignore: {
88589 assert( seenReplace==0 );
88590 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
88591 break;
88593 default: {
88594 Trigger *pTrigger = 0;
88595 assert( onError==OE_Replace );
88596 sqlite3MultiWrite(pParse);
88597 if( pParse->db->flags&SQLITE_RecTriggers ){
88598 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
88600 sqlite3GenerateRowDelete(
88601 pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace
88603 seenReplace = 1;
88604 break;
88607 sqlite3VdbeJumpHere(v, j3);
88608 sqlite3ReleaseTempReg(pParse, regR);
88611 if( pbMayReplace ){
88612 *pbMayReplace = seenReplace;
88617 ** This routine generates code to finish the INSERT or UPDATE operation
88618 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
88619 ** A consecutive range of registers starting at regRowid contains the
88620 ** rowid and the content to be inserted.
88622 ** The arguments to this routine should be the same as the first six
88623 ** arguments to sqlite3GenerateConstraintChecks.
88625 SQLITE_PRIVATE void sqlite3CompleteInsertion(
88626 Parse *pParse, /* The parser context */
88627 Table *pTab, /* the table into which we are inserting */
88628 int baseCur, /* Index of a read/write cursor pointing at pTab */
88629 int regRowid, /* Range of content */
88630 int *aRegIdx, /* Register used by each index. 0 for unused indices */
88631 int isUpdate, /* True for UPDATE, False for INSERT */
88632 int appendBias, /* True if this is likely to be an append */
88633 int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
88635 int i;
88636 Vdbe *v;
88637 int nIdx;
88638 Index *pIdx;
88639 u8 pik_flags;
88640 int regData;
88641 int regRec;
88643 v = sqlite3GetVdbe(pParse);
88644 assert( v!=0 );
88645 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
88646 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
88647 for(i=nIdx-1; i>=0; i--){
88648 if( aRegIdx[i]==0 ) continue;
88649 sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
88650 if( useSeekResult ){
88651 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
88654 regData = regRowid + 1;
88655 regRec = sqlite3GetTempReg(pParse);
88656 sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
88657 sqlite3TableAffinityStr(v, pTab);
88658 sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
88659 if( pParse->nested ){
88660 pik_flags = 0;
88661 }else{
88662 pik_flags = OPFLAG_NCHANGE;
88663 pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
88665 if( appendBias ){
88666 pik_flags |= OPFLAG_APPEND;
88668 if( useSeekResult ){
88669 pik_flags |= OPFLAG_USESEEKRESULT;
88671 sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
88672 if( !pParse->nested ){
88673 sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
88675 sqlite3VdbeChangeP5(v, pik_flags);
88679 ** Generate code that will open cursors for a table and for all
88680 ** indices of that table. The "baseCur" parameter is the cursor number used
88681 ** for the table. Indices are opened on subsequent cursors.
88683 ** Return the number of indices on the table.
88685 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
88686 Parse *pParse, /* Parsing context */
88687 Table *pTab, /* Table to be opened */
88688 int baseCur, /* Cursor number assigned to the table */
88689 int op /* OP_OpenRead or OP_OpenWrite */
88691 int i;
88692 int iDb;
88693 Index *pIdx;
88694 Vdbe *v;
88696 if( IsVirtual(pTab) ) return 0;
88697 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
88698 v = sqlite3GetVdbe(pParse);
88699 assert( v!=0 );
88700 sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
88701 for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
88702 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
88703 assert( pIdx->pSchema==pTab->pSchema );
88704 sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
88705 (char*)pKey, P4_KEYINFO_HANDOFF);
88706 VdbeComment((v, "%s", pIdx->zName));
88708 if( pParse->nTab<baseCur+i ){
88709 pParse->nTab = baseCur+i;
88711 return i-1;
88715 #ifdef SQLITE_TEST
88717 ** The following global variable is incremented whenever the
88718 ** transfer optimization is used. This is used for testing
88719 ** purposes only - to make sure the transfer optimization really
88720 ** is happening when it is suppose to.
88722 SQLITE_API int sqlite3_xferopt_count;
88723 #endif /* SQLITE_TEST */
88726 #ifndef SQLITE_OMIT_XFER_OPT
88728 ** Check to collation names to see if they are compatible.
88730 static int xferCompatibleCollation(const char *z1, const char *z2){
88731 if( z1==0 ){
88732 return z2==0;
88734 if( z2==0 ){
88735 return 0;
88737 return sqlite3StrICmp(z1, z2)==0;
88742 ** Check to see if index pSrc is compatible as a source of data
88743 ** for index pDest in an insert transfer optimization. The rules
88744 ** for a compatible index:
88746 ** * The index is over the same set of columns
88747 ** * The same DESC and ASC markings occurs on all columns
88748 ** * The same onError processing (OE_Abort, OE_Ignore, etc)
88749 ** * The same collating sequence on each column
88751 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
88752 int i;
88753 assert( pDest && pSrc );
88754 assert( pDest->pTable!=pSrc->pTable );
88755 if( pDest->nColumn!=pSrc->nColumn ){
88756 return 0; /* Different number of columns */
88758 if( pDest->onError!=pSrc->onError ){
88759 return 0; /* Different conflict resolution strategies */
88761 for(i=0; i<pSrc->nColumn; i++){
88762 if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
88763 return 0; /* Different columns indexed */
88765 if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
88766 return 0; /* Different sort orders */
88768 if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
88769 return 0; /* Different collating sequences */
88773 /* If no test above fails then the indices must be compatible */
88774 return 1;
88778 ** Attempt the transfer optimization on INSERTs of the form
88780 ** INSERT INTO tab1 SELECT * FROM tab2;
88782 ** This optimization is only attempted if
88784 ** (1) tab1 and tab2 have identical schemas including all the
88785 ** same indices and constraints
88787 ** (2) tab1 and tab2 are different tables
88789 ** (3) There must be no triggers on tab1
88791 ** (4) The result set of the SELECT statement is "*"
88793 ** (5) The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
88794 ** or LIMIT clause.
88796 ** (6) The SELECT statement is a simple (not a compound) select that
88797 ** contains only tab2 in its FROM clause
88799 ** This method for implementing the INSERT transfers raw records from
88800 ** tab2 over to tab1. The columns are not decoded. Raw records from
88801 ** the indices of tab2 are transfered to tab1 as well. In so doing,
88802 ** the resulting tab1 has much less fragmentation.
88804 ** This routine returns TRUE if the optimization is attempted. If any
88805 ** of the conditions above fail so that the optimization should not
88806 ** be attempted, then this routine returns FALSE.
88808 static int xferOptimization(
88809 Parse *pParse, /* Parser context */
88810 Table *pDest, /* The table we are inserting into */
88811 Select *pSelect, /* A SELECT statement to use as the data source */
88812 int onError, /* How to handle constraint errors */
88813 int iDbDest /* The database of pDest */
88815 ExprList *pEList; /* The result set of the SELECT */
88816 Table *pSrc; /* The table in the FROM clause of SELECT */
88817 Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
88818 struct SrcList_item *pItem; /* An element of pSelect->pSrc */
88819 int i; /* Loop counter */
88820 int iDbSrc; /* The database of pSrc */
88821 int iSrc, iDest; /* Cursors from source and destination */
88822 int addr1, addr2; /* Loop addresses */
88823 int emptyDestTest; /* Address of test for empty pDest */
88824 int emptySrcTest; /* Address of test for empty pSrc */
88825 Vdbe *v; /* The VDBE we are building */
88826 KeyInfo *pKey; /* Key information for an index */
88827 int regAutoinc; /* Memory register used by AUTOINC */
88828 int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
88829 int regData, regRowid; /* Registers holding data and rowid */
88831 if( pSelect==0 ){
88832 return 0; /* Must be of the form INSERT INTO ... SELECT ... */
88834 if( sqlite3TriggerList(pParse, pDest) ){
88835 return 0; /* tab1 must not have triggers */
88837 #ifndef SQLITE_OMIT_VIRTUALTABLE
88838 if( pDest->tabFlags & TF_Virtual ){
88839 return 0; /* tab1 must not be a virtual table */
88841 #endif
88842 if( onError==OE_Default ){
88843 onError = OE_Abort;
88845 if( onError!=OE_Abort && onError!=OE_Rollback ){
88846 return 0; /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
88848 assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
88849 if( pSelect->pSrc->nSrc!=1 ){
88850 return 0; /* FROM clause must have exactly one term */
88852 if( pSelect->pSrc->a[0].pSelect ){
88853 return 0; /* FROM clause cannot contain a subquery */
88855 if( pSelect->pWhere ){
88856 return 0; /* SELECT may not have a WHERE clause */
88858 if( pSelect->pOrderBy ){
88859 return 0; /* SELECT may not have an ORDER BY clause */
88861 /* Do not need to test for a HAVING clause. If HAVING is present but
88862 ** there is no ORDER BY, we will get an error. */
88863 if( pSelect->pGroupBy ){
88864 return 0; /* SELECT may not have a GROUP BY clause */
88866 if( pSelect->pLimit ){
88867 return 0; /* SELECT may not have a LIMIT clause */
88869 assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */
88870 if( pSelect->pPrior ){
88871 return 0; /* SELECT may not be a compound query */
88873 if( pSelect->selFlags & SF_Distinct ){
88874 return 0; /* SELECT may not be DISTINCT */
88876 pEList = pSelect->pEList;
88877 assert( pEList!=0 );
88878 if( pEList->nExpr!=1 ){
88879 return 0; /* The result set must have exactly one column */
88881 assert( pEList->a[0].pExpr );
88882 if( pEList->a[0].pExpr->op!=TK_ALL ){
88883 return 0; /* The result set must be the special operator "*" */
88886 /* At this point we have established that the statement is of the
88887 ** correct syntactic form to participate in this optimization. Now
88888 ** we have to check the semantics.
88890 pItem = pSelect->pSrc->a;
88891 pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
88892 if( pSrc==0 ){
88893 return 0; /* FROM clause does not contain a real table */
88895 if( pSrc==pDest ){
88896 return 0; /* tab1 and tab2 may not be the same table */
88898 #ifndef SQLITE_OMIT_VIRTUALTABLE
88899 if( pSrc->tabFlags & TF_Virtual ){
88900 return 0; /* tab2 must not be a virtual table */
88902 #endif
88903 if( pSrc->pSelect ){
88904 return 0; /* tab2 may not be a view */
88906 if( pDest->nCol!=pSrc->nCol ){
88907 return 0; /* Number of columns must be the same in tab1 and tab2 */
88909 if( pDest->iPKey!=pSrc->iPKey ){
88910 return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
88912 for(i=0; i<pDest->nCol; i++){
88913 if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
88914 return 0; /* Affinity must be the same on all columns */
88916 if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
88917 return 0; /* Collating sequence must be the same on all columns */
88919 if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
88920 return 0; /* tab2 must be NOT NULL if tab1 is */
88923 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
88924 if( pDestIdx->onError!=OE_None ){
88925 destHasUniqueIdx = 1;
88927 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
88928 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
88930 if( pSrcIdx==0 ){
88931 return 0; /* pDestIdx has no corresponding index in pSrc */
88934 #ifndef SQLITE_OMIT_CHECK
88935 if( pDest->pCheck && sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
88936 return 0; /* Tables have different CHECK constraints. Ticket #2252 */
88938 #endif
88939 #ifndef SQLITE_OMIT_FOREIGN_KEY
88940 /* Disallow the transfer optimization if the destination table constains
88941 ** any foreign key constraints. This is more restrictive than necessary.
88942 ** But the main beneficiary of the transfer optimization is the VACUUM
88943 ** command, and the VACUUM command disables foreign key constraints. So
88944 ** the extra complication to make this rule less restrictive is probably
88945 ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
88947 if( (pParse->db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
88948 return 0;
88950 #endif
88951 if( (pParse->db->flags & SQLITE_CountRows)!=0 ){
88952 return 0;
88955 /* If we get this far, it means either:
88957 ** * We can always do the transfer if the table contains an
88958 ** an integer primary key
88960 ** * We can conditionally do the transfer if the destination
88961 ** table is empty.
88963 #ifdef SQLITE_TEST
88964 sqlite3_xferopt_count++;
88965 #endif
88966 iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
88967 v = sqlite3GetVdbe(pParse);
88968 sqlite3CodeVerifySchema(pParse, iDbSrc);
88969 iSrc = pParse->nTab++;
88970 iDest = pParse->nTab++;
88971 regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
88972 sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
88973 if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
88974 /* If tables do not have an INTEGER PRIMARY KEY and there
88975 ** are indices to be copied and the destination is not empty,
88976 ** we have to disallow the transfer optimization because the
88977 ** the rowids might change which will mess up indexing.
88979 ** Or if the destination has a UNIQUE index and is not empty,
88980 ** we also disallow the transfer optimization because we cannot
88981 ** insure that all entries in the union of DEST and SRC will be
88982 ** unique.
88984 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
88985 emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
88986 sqlite3VdbeJumpHere(v, addr1);
88987 }else{
88988 emptyDestTest = 0;
88990 sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
88991 emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
88992 regData = sqlite3GetTempReg(pParse);
88993 regRowid = sqlite3GetTempReg(pParse);
88994 if( pDest->iPKey>=0 ){
88995 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
88996 addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
88997 sqlite3HaltConstraint(
88998 pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
88999 sqlite3VdbeJumpHere(v, addr2);
89000 autoIncStep(pParse, regAutoinc, regRowid);
89001 }else if( pDest->pIndex==0 ){
89002 addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
89003 }else{
89004 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
89005 assert( (pDest->tabFlags & TF_Autoincrement)==0 );
89007 sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
89008 sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
89009 sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
89010 sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
89011 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
89012 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
89013 for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
89014 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
89016 assert( pSrcIdx );
89017 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
89018 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
89019 pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
89020 sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
89021 (char*)pKey, P4_KEYINFO_HANDOFF);
89022 VdbeComment((v, "%s", pSrcIdx->zName));
89023 pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
89024 sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
89025 (char*)pKey, P4_KEYINFO_HANDOFF);
89026 VdbeComment((v, "%s", pDestIdx->zName));
89027 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
89028 sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
89029 sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
89030 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
89031 sqlite3VdbeJumpHere(v, addr1);
89033 sqlite3VdbeJumpHere(v, emptySrcTest);
89034 sqlite3ReleaseTempReg(pParse, regRowid);
89035 sqlite3ReleaseTempReg(pParse, regData);
89036 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
89037 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
89038 if( emptyDestTest ){
89039 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
89040 sqlite3VdbeJumpHere(v, emptyDestTest);
89041 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
89042 return 0;
89043 }else{
89044 return 1;
89047 #endif /* SQLITE_OMIT_XFER_OPT */
89049 /************** End of insert.c **********************************************/
89050 /************** Begin file legacy.c ******************************************/
89052 ** 2001 September 15
89054 ** The author disclaims copyright to this source code. In place of
89055 ** a legal notice, here is a blessing:
89057 ** May you do good and not evil.
89058 ** May you find forgiveness for yourself and forgive others.
89059 ** May you share freely, never taking more than you give.
89061 *************************************************************************
89062 ** Main file for the SQLite library. The routines in this file
89063 ** implement the programmer interface to the library. Routines in
89064 ** other files are for internal use by SQLite and should not be
89065 ** accessed by users of the library.
89070 ** Execute SQL code. Return one of the SQLITE_ success/failure
89071 ** codes. Also write an error message into memory obtained from
89072 ** malloc() and make *pzErrMsg point to that message.
89074 ** If the SQL is a query, then for each row in the query result
89075 ** the xCallback() function is called. pArg becomes the first
89076 ** argument to xCallback(). If xCallback=NULL then no callback
89077 ** is invoked, even for queries.
89079 SQLITE_API int sqlite3_exec(
89080 sqlite3 *db, /* The database on which the SQL executes */
89081 const char *zSql, /* The SQL to be executed */
89082 sqlite3_callback xCallback, /* Invoke this callback routine */
89083 void *pArg, /* First argument to xCallback() */
89084 char **pzErrMsg /* Write error messages here */
89086 int rc = SQLITE_OK; /* Return code */
89087 const char *zLeftover; /* Tail of unprocessed SQL */
89088 sqlite3_stmt *pStmt = 0; /* The current SQL statement */
89089 char **azCols = 0; /* Names of result columns */
89090 int nRetry = 0; /* Number of retry attempts */
89091 int callbackIsInit; /* True if callback data is initialized */
89093 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
89094 if( zSql==0 ) zSql = "";
89096 sqlite3_mutex_enter(db->mutex);
89097 sqlite3Error(db, SQLITE_OK, 0);
89098 while( (rc==SQLITE_OK || (rc==SQLITE_SCHEMA && (++nRetry)<2)) && zSql[0] ){
89099 int nCol;
89100 char **azVals = 0;
89102 pStmt = 0;
89103 rc = sqlite3_prepare(db, zSql, -1, &pStmt, &zLeftover);
89104 assert( rc==SQLITE_OK || pStmt==0 );
89105 if( rc!=SQLITE_OK ){
89106 continue;
89108 if( !pStmt ){
89109 /* this happens for a comment or white-space */
89110 zSql = zLeftover;
89111 continue;
89114 callbackIsInit = 0;
89115 nCol = sqlite3_column_count(pStmt);
89117 while( 1 ){
89118 int i;
89119 rc = sqlite3_step(pStmt);
89121 /* Invoke the callback function if required */
89122 if( xCallback && (SQLITE_ROW==rc ||
89123 (SQLITE_DONE==rc && !callbackIsInit
89124 && db->flags&SQLITE_NullCallback)) ){
89125 if( !callbackIsInit ){
89126 azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
89127 if( azCols==0 ){
89128 goto exec_out;
89130 for(i=0; i<nCol; i++){
89131 azCols[i] = (char *)sqlite3_column_name(pStmt, i);
89132 /* sqlite3VdbeSetColName() installs column names as UTF8
89133 ** strings so there is no way for sqlite3_column_name() to fail. */
89134 assert( azCols[i]!=0 );
89136 callbackIsInit = 1;
89138 if( rc==SQLITE_ROW ){
89139 azVals = &azCols[nCol];
89140 for(i=0; i<nCol; i++){
89141 azVals[i] = (char *)sqlite3_column_text(pStmt, i);
89142 if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
89143 db->mallocFailed = 1;
89144 goto exec_out;
89148 if( xCallback(pArg, nCol, azVals, azCols) ){
89149 rc = SQLITE_ABORT;
89150 sqlite3VdbeFinalize((Vdbe *)pStmt);
89151 pStmt = 0;
89152 sqlite3Error(db, SQLITE_ABORT, 0);
89153 goto exec_out;
89157 if( rc!=SQLITE_ROW ){
89158 rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
89159 pStmt = 0;
89160 if( rc!=SQLITE_SCHEMA ){
89161 nRetry = 0;
89162 zSql = zLeftover;
89163 while( sqlite3Isspace(zSql[0]) ) zSql++;
89165 break;
89169 sqlite3DbFree(db, azCols);
89170 azCols = 0;
89173 exec_out:
89174 if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
89175 sqlite3DbFree(db, azCols);
89177 rc = sqlite3ApiExit(db, rc);
89178 if( rc!=SQLITE_OK && ALWAYS(rc==sqlite3_errcode(db)) && pzErrMsg ){
89179 int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
89180 *pzErrMsg = sqlite3Malloc(nErrMsg);
89181 if( *pzErrMsg ){
89182 memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
89183 }else{
89184 rc = SQLITE_NOMEM;
89185 sqlite3Error(db, SQLITE_NOMEM, 0);
89187 }else if( pzErrMsg ){
89188 *pzErrMsg = 0;
89191 assert( (rc&db->errMask)==rc );
89192 sqlite3_mutex_leave(db->mutex);
89193 return rc;
89196 /************** End of legacy.c **********************************************/
89197 /************** Begin file loadext.c *****************************************/
89199 ** 2006 June 7
89201 ** The author disclaims copyright to this source code. In place of
89202 ** a legal notice, here is a blessing:
89204 ** May you do good and not evil.
89205 ** May you find forgiveness for yourself and forgive others.
89206 ** May you share freely, never taking more than you give.
89208 *************************************************************************
89209 ** This file contains code used to dynamically load extensions into
89210 ** the SQLite library.
89213 #ifndef SQLITE_CORE
89214 #define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */
89215 #endif
89216 /************** Include sqlite3ext.h in the middle of loadext.c **************/
89217 /************** Begin file sqlite3ext.h **************************************/
89219 ** 2006 June 7
89221 ** The author disclaims copyright to this source code. In place of
89222 ** a legal notice, here is a blessing:
89224 ** May you do good and not evil.
89225 ** May you find forgiveness for yourself and forgive others.
89226 ** May you share freely, never taking more than you give.
89228 *************************************************************************
89229 ** This header file defines the SQLite interface for use by
89230 ** shared libraries that want to be imported as extensions into
89231 ** an SQLite instance. Shared libraries that intend to be loaded
89232 ** as extensions by SQLite should #include this file instead of
89233 ** sqlite3.h.
89235 #ifndef _SQLITE3EXT_H_
89236 #define _SQLITE3EXT_H_
89238 typedef struct sqlite3_api_routines sqlite3_api_routines;
89241 ** The following structure holds pointers to all of the SQLite API
89242 ** routines.
89244 ** WARNING: In order to maintain backwards compatibility, add new
89245 ** interfaces to the end of this structure only. If you insert new
89246 ** interfaces in the middle of this structure, then older different
89247 ** versions of SQLite will not be able to load each others' shared
89248 ** libraries!
89250 struct sqlite3_api_routines {
89251 void * (*aggregate_context)(sqlite3_context*,int nBytes);
89252 int (*aggregate_count)(sqlite3_context*);
89253 int (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
89254 int (*bind_double)(sqlite3_stmt*,int,double);
89255 int (*bind_int)(sqlite3_stmt*,int,int);
89256 int (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
89257 int (*bind_null)(sqlite3_stmt*,int);
89258 int (*bind_parameter_count)(sqlite3_stmt*);
89259 int (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
89260 const char * (*bind_parameter_name)(sqlite3_stmt*,int);
89261 int (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
89262 int (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
89263 int (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
89264 int (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
89265 int (*busy_timeout)(sqlite3*,int ms);
89266 int (*changes)(sqlite3*);
89267 int (*close)(sqlite3*);
89268 int (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
89269 int eTextRep,const char*));
89270 int (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
89271 int eTextRep,const void*));
89272 const void * (*column_blob)(sqlite3_stmt*,int iCol);
89273 int (*column_bytes)(sqlite3_stmt*,int iCol);
89274 int (*column_bytes16)(sqlite3_stmt*,int iCol);
89275 int (*column_count)(sqlite3_stmt*pStmt);
89276 const char * (*column_database_name)(sqlite3_stmt*,int);
89277 const void * (*column_database_name16)(sqlite3_stmt*,int);
89278 const char * (*column_decltype)(sqlite3_stmt*,int i);
89279 const void * (*column_decltype16)(sqlite3_stmt*,int);
89280 double (*column_double)(sqlite3_stmt*,int iCol);
89281 int (*column_int)(sqlite3_stmt*,int iCol);
89282 sqlite_int64 (*column_int64)(sqlite3_stmt*,int iCol);
89283 const char * (*column_name)(sqlite3_stmt*,int);
89284 const void * (*column_name16)(sqlite3_stmt*,int);
89285 const char * (*column_origin_name)(sqlite3_stmt*,int);
89286 const void * (*column_origin_name16)(sqlite3_stmt*,int);
89287 const char * (*column_table_name)(sqlite3_stmt*,int);
89288 const void * (*column_table_name16)(sqlite3_stmt*,int);
89289 const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
89290 const void * (*column_text16)(sqlite3_stmt*,int iCol);
89291 int (*column_type)(sqlite3_stmt*,int iCol);
89292 sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
89293 void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
89294 int (*complete)(const char*sql);
89295 int (*complete16)(const void*sql);
89296 int (*create_collation)(sqlite3*,const char*,int,void*,
89297 int(*)(void*,int,const void*,int,const void*));
89298 int (*create_collation16)(sqlite3*,const void*,int,void*,
89299 int(*)(void*,int,const void*,int,const void*));
89300 int (*create_function)(sqlite3*,const char*,int,int,void*,
89301 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
89302 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
89303 void (*xFinal)(sqlite3_context*));
89304 int (*create_function16)(sqlite3*,const void*,int,int,void*,
89305 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
89306 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
89307 void (*xFinal)(sqlite3_context*));
89308 int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
89309 int (*data_count)(sqlite3_stmt*pStmt);
89310 sqlite3 * (*db_handle)(sqlite3_stmt*);
89311 int (*declare_vtab)(sqlite3*,const char*);
89312 int (*enable_shared_cache)(int);
89313 int (*errcode)(sqlite3*db);
89314 const char * (*errmsg)(sqlite3*);
89315 const void * (*errmsg16)(sqlite3*);
89316 int (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
89317 int (*expired)(sqlite3_stmt*);
89318 int (*finalize)(sqlite3_stmt*pStmt);
89319 void (*free)(void*);
89320 void (*free_table)(char**result);
89321 int (*get_autocommit)(sqlite3*);
89322 void * (*get_auxdata)(sqlite3_context*,int);
89323 int (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
89324 int (*global_recover)(void);
89325 void (*interruptx)(sqlite3*);
89326 sqlite_int64 (*last_insert_rowid)(sqlite3*);
89327 const char * (*libversion)(void);
89328 int (*libversion_number)(void);
89329 void *(*malloc)(int);
89330 char * (*mprintf)(const char*,...);
89331 int (*open)(const char*,sqlite3**);
89332 int (*open16)(const void*,sqlite3**);
89333 int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
89334 int (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
89335 void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
89336 void (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
89337 void *(*realloc)(void*,int);
89338 int (*reset)(sqlite3_stmt*pStmt);
89339 void (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
89340 void (*result_double)(sqlite3_context*,double);
89341 void (*result_error)(sqlite3_context*,const char*,int);
89342 void (*result_error16)(sqlite3_context*,const void*,int);
89343 void (*result_int)(sqlite3_context*,int);
89344 void (*result_int64)(sqlite3_context*,sqlite_int64);
89345 void (*result_null)(sqlite3_context*);
89346 void (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
89347 void (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
89348 void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
89349 void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
89350 void (*result_value)(sqlite3_context*,sqlite3_value*);
89351 void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
89352 int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
89353 const char*,const char*),void*);
89354 void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
89355 char * (*snprintf)(int,char*,const char*,...);
89356 int (*step)(sqlite3_stmt*);
89357 int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
89358 char const**,char const**,int*,int*,int*);
89359 void (*thread_cleanup)(void);
89360 int (*total_changes)(sqlite3*);
89361 void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
89362 int (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
89363 void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
89364 sqlite_int64),void*);
89365 void * (*user_data)(sqlite3_context*);
89366 const void * (*value_blob)(sqlite3_value*);
89367 int (*value_bytes)(sqlite3_value*);
89368 int (*value_bytes16)(sqlite3_value*);
89369 double (*value_double)(sqlite3_value*);
89370 int (*value_int)(sqlite3_value*);
89371 sqlite_int64 (*value_int64)(sqlite3_value*);
89372 int (*value_numeric_type)(sqlite3_value*);
89373 const unsigned char * (*value_text)(sqlite3_value*);
89374 const void * (*value_text16)(sqlite3_value*);
89375 const void * (*value_text16be)(sqlite3_value*);
89376 const void * (*value_text16le)(sqlite3_value*);
89377 int (*value_type)(sqlite3_value*);
89378 char *(*vmprintf)(const char*,va_list);
89379 /* Added ??? */
89380 int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
89381 /* Added by 3.3.13 */
89382 int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
89383 int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
89384 int (*clear_bindings)(sqlite3_stmt*);
89385 /* Added by 3.4.1 */
89386 int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
89387 void (*xDestroy)(void *));
89388 /* Added by 3.5.0 */
89389 int (*bind_zeroblob)(sqlite3_stmt*,int,int);
89390 int (*blob_bytes)(sqlite3_blob*);
89391 int (*blob_close)(sqlite3_blob*);
89392 int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
89393 int,sqlite3_blob**);
89394 int (*blob_read)(sqlite3_blob*,void*,int,int);
89395 int (*blob_write)(sqlite3_blob*,const void*,int,int);
89396 int (*create_collation_v2)(sqlite3*,const char*,int,void*,
89397 int(*)(void*,int,const void*,int,const void*),
89398 void(*)(void*));
89399 int (*file_control)(sqlite3*,const char*,int,void*);
89400 sqlite3_int64 (*memory_highwater)(int);
89401 sqlite3_int64 (*memory_used)(void);
89402 sqlite3_mutex *(*mutex_alloc)(int);
89403 void (*mutex_enter)(sqlite3_mutex*);
89404 void (*mutex_free)(sqlite3_mutex*);
89405 void (*mutex_leave)(sqlite3_mutex*);
89406 int (*mutex_try)(sqlite3_mutex*);
89407 int (*open_v2)(const char*,sqlite3**,int,const char*);
89408 int (*release_memory)(int);
89409 void (*result_error_nomem)(sqlite3_context*);
89410 void (*result_error_toobig)(sqlite3_context*);
89411 int (*sleep)(int);
89412 void (*soft_heap_limit)(int);
89413 sqlite3_vfs *(*vfs_find)(const char*);
89414 int (*vfs_register)(sqlite3_vfs*,int);
89415 int (*vfs_unregister)(sqlite3_vfs*);
89416 int (*xthreadsafe)(void);
89417 void (*result_zeroblob)(sqlite3_context*,int);
89418 void (*result_error_code)(sqlite3_context*,int);
89419 int (*test_control)(int, ...);
89420 void (*randomness)(int,void*);
89421 sqlite3 *(*context_db_handle)(sqlite3_context*);
89422 int (*extended_result_codes)(sqlite3*,int);
89423 int (*limit)(sqlite3*,int,int);
89424 sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
89425 const char *(*sql)(sqlite3_stmt*);
89426 int (*status)(int,int*,int*,int);
89427 int (*backup_finish)(sqlite3_backup*);
89428 sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
89429 int (*backup_pagecount)(sqlite3_backup*);
89430 int (*backup_remaining)(sqlite3_backup*);
89431 int (*backup_step)(sqlite3_backup*,int);
89432 const char *(*compileoption_get)(int);
89433 int (*compileoption_used)(const char*);
89434 int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
89435 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
89436 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
89437 void (*xFinal)(sqlite3_context*),
89438 void(*xDestroy)(void*));
89439 int (*db_config)(sqlite3*,int,...);
89440 sqlite3_mutex *(*db_mutex)(sqlite3*);
89441 int (*db_status)(sqlite3*,int,int*,int*,int);
89442 int (*extended_errcode)(sqlite3*);
89443 void (*log)(int,const char*,...);
89444 sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
89445 const char *(*sourceid)(void);
89446 int (*stmt_status)(sqlite3_stmt*,int,int);
89447 int (*strnicmp)(const char*,const char*,int);
89448 int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
89449 int (*wal_autocheckpoint)(sqlite3*,int);
89450 int (*wal_checkpoint)(sqlite3*,const char*);
89451 void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
89452 int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
89453 int (*vtab_config)(sqlite3*,int op,...);
89454 int (*vtab_on_conflict)(sqlite3*);
89458 ** The following macros redefine the API routines so that they are
89459 ** redirected throught the global sqlite3_api structure.
89461 ** This header file is also used by the loadext.c source file
89462 ** (part of the main SQLite library - not an extension) so that
89463 ** it can get access to the sqlite3_api_routines structure
89464 ** definition. But the main library does not want to redefine
89465 ** the API. So the redefinition macros are only valid if the
89466 ** SQLITE_CORE macros is undefined.
89468 #ifndef SQLITE_CORE
89469 #define sqlite3_aggregate_context sqlite3_api->aggregate_context
89470 #ifndef SQLITE_OMIT_DEPRECATED
89471 #define sqlite3_aggregate_count sqlite3_api->aggregate_count
89472 #endif
89473 #define sqlite3_bind_blob sqlite3_api->bind_blob
89474 #define sqlite3_bind_double sqlite3_api->bind_double
89475 #define sqlite3_bind_int sqlite3_api->bind_int
89476 #define sqlite3_bind_int64 sqlite3_api->bind_int64
89477 #define sqlite3_bind_null sqlite3_api->bind_null
89478 #define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count
89479 #define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index
89480 #define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name
89481 #define sqlite3_bind_text sqlite3_api->bind_text
89482 #define sqlite3_bind_text16 sqlite3_api->bind_text16
89483 #define sqlite3_bind_value sqlite3_api->bind_value
89484 #define sqlite3_busy_handler sqlite3_api->busy_handler
89485 #define sqlite3_busy_timeout sqlite3_api->busy_timeout
89486 #define sqlite3_changes sqlite3_api->changes
89487 #define sqlite3_close sqlite3_api->close
89488 #define sqlite3_collation_needed sqlite3_api->collation_needed
89489 #define sqlite3_collation_needed16 sqlite3_api->collation_needed16
89490 #define sqlite3_column_blob sqlite3_api->column_blob
89491 #define sqlite3_column_bytes sqlite3_api->column_bytes
89492 #define sqlite3_column_bytes16 sqlite3_api->column_bytes16
89493 #define sqlite3_column_count sqlite3_api->column_count
89494 #define sqlite3_column_database_name sqlite3_api->column_database_name
89495 #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
89496 #define sqlite3_column_decltype sqlite3_api->column_decltype
89497 #define sqlite3_column_decltype16 sqlite3_api->column_decltype16
89498 #define sqlite3_column_double sqlite3_api->column_double
89499 #define sqlite3_column_int sqlite3_api->column_int
89500 #define sqlite3_column_int64 sqlite3_api->column_int64
89501 #define sqlite3_column_name sqlite3_api->column_name
89502 #define sqlite3_column_name16 sqlite3_api->column_name16
89503 #define sqlite3_column_origin_name sqlite3_api->column_origin_name
89504 #define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16
89505 #define sqlite3_column_table_name sqlite3_api->column_table_name
89506 #define sqlite3_column_table_name16 sqlite3_api->column_table_name16
89507 #define sqlite3_column_text sqlite3_api->column_text
89508 #define sqlite3_column_text16 sqlite3_api->column_text16
89509 #define sqlite3_column_type sqlite3_api->column_type
89510 #define sqlite3_column_value sqlite3_api->column_value
89511 #define sqlite3_commit_hook sqlite3_api->commit_hook
89512 #define sqlite3_complete sqlite3_api->complete
89513 #define sqlite3_complete16 sqlite3_api->complete16
89514 #define sqlite3_create_collation sqlite3_api->create_collation
89515 #define sqlite3_create_collation16 sqlite3_api->create_collation16
89516 #define sqlite3_create_function sqlite3_api->create_function
89517 #define sqlite3_create_function16 sqlite3_api->create_function16
89518 #define sqlite3_create_module sqlite3_api->create_module
89519 #define sqlite3_create_module_v2 sqlite3_api->create_module_v2
89520 #define sqlite3_data_count sqlite3_api->data_count
89521 #define sqlite3_db_handle sqlite3_api->db_handle
89522 #define sqlite3_declare_vtab sqlite3_api->declare_vtab
89523 #define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache
89524 #define sqlite3_errcode sqlite3_api->errcode
89525 #define sqlite3_errmsg sqlite3_api->errmsg
89526 #define sqlite3_errmsg16 sqlite3_api->errmsg16
89527 #define sqlite3_exec sqlite3_api->exec
89528 #ifndef SQLITE_OMIT_DEPRECATED
89529 #define sqlite3_expired sqlite3_api->expired
89530 #endif
89531 #define sqlite3_finalize sqlite3_api->finalize
89532 #define sqlite3_free sqlite3_api->free
89533 #define sqlite3_free_table sqlite3_api->free_table
89534 #define sqlite3_get_autocommit sqlite3_api->get_autocommit
89535 #define sqlite3_get_auxdata sqlite3_api->get_auxdata
89536 #define sqlite3_get_table sqlite3_api->get_table
89537 #ifndef SQLITE_OMIT_DEPRECATED
89538 #define sqlite3_global_recover sqlite3_api->global_recover
89539 #endif
89540 #define sqlite3_interrupt sqlite3_api->interruptx
89541 #define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid
89542 #define sqlite3_libversion sqlite3_api->libversion
89543 #define sqlite3_libversion_number sqlite3_api->libversion_number
89544 #define sqlite3_malloc sqlite3_api->malloc
89545 #define sqlite3_mprintf sqlite3_api->mprintf
89546 #define sqlite3_open sqlite3_api->open
89547 #define sqlite3_open16 sqlite3_api->open16
89548 #define sqlite3_prepare sqlite3_api->prepare
89549 #define sqlite3_prepare16 sqlite3_api->prepare16
89550 #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
89551 #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
89552 #define sqlite3_profile sqlite3_api->profile
89553 #define sqlite3_progress_handler sqlite3_api->progress_handler
89554 #define sqlite3_realloc sqlite3_api->realloc
89555 #define sqlite3_reset sqlite3_api->reset
89556 #define sqlite3_result_blob sqlite3_api->result_blob
89557 #define sqlite3_result_double sqlite3_api->result_double
89558 #define sqlite3_result_error sqlite3_api->result_error
89559 #define sqlite3_result_error16 sqlite3_api->result_error16
89560 #define sqlite3_result_int sqlite3_api->result_int
89561 #define sqlite3_result_int64 sqlite3_api->result_int64
89562 #define sqlite3_result_null sqlite3_api->result_null
89563 #define sqlite3_result_text sqlite3_api->result_text
89564 #define sqlite3_result_text16 sqlite3_api->result_text16
89565 #define sqlite3_result_text16be sqlite3_api->result_text16be
89566 #define sqlite3_result_text16le sqlite3_api->result_text16le
89567 #define sqlite3_result_value sqlite3_api->result_value
89568 #define sqlite3_rollback_hook sqlite3_api->rollback_hook
89569 #define sqlite3_set_authorizer sqlite3_api->set_authorizer
89570 #define sqlite3_set_auxdata sqlite3_api->set_auxdata
89571 #define sqlite3_snprintf sqlite3_api->snprintf
89572 #define sqlite3_step sqlite3_api->step
89573 #define sqlite3_table_column_metadata sqlite3_api->table_column_metadata
89574 #define sqlite3_thread_cleanup sqlite3_api->thread_cleanup
89575 #define sqlite3_total_changes sqlite3_api->total_changes
89576 #define sqlite3_trace sqlite3_api->trace
89577 #ifndef SQLITE_OMIT_DEPRECATED
89578 #define sqlite3_transfer_bindings sqlite3_api->transfer_bindings
89579 #endif
89580 #define sqlite3_update_hook sqlite3_api->update_hook
89581 #define sqlite3_user_data sqlite3_api->user_data
89582 #define sqlite3_value_blob sqlite3_api->value_blob
89583 #define sqlite3_value_bytes sqlite3_api->value_bytes
89584 #define sqlite3_value_bytes16 sqlite3_api->value_bytes16
89585 #define sqlite3_value_double sqlite3_api->value_double
89586 #define sqlite3_value_int sqlite3_api->value_int
89587 #define sqlite3_value_int64 sqlite3_api->value_int64
89588 #define sqlite3_value_numeric_type sqlite3_api->value_numeric_type
89589 #define sqlite3_value_text sqlite3_api->value_text
89590 #define sqlite3_value_text16 sqlite3_api->value_text16
89591 #define sqlite3_value_text16be sqlite3_api->value_text16be
89592 #define sqlite3_value_text16le sqlite3_api->value_text16le
89593 #define sqlite3_value_type sqlite3_api->value_type
89594 #define sqlite3_vmprintf sqlite3_api->vmprintf
89595 #define sqlite3_overload_function sqlite3_api->overload_function
89596 #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
89597 #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
89598 #define sqlite3_clear_bindings sqlite3_api->clear_bindings
89599 #define sqlite3_bind_zeroblob sqlite3_api->bind_zeroblob
89600 #define sqlite3_blob_bytes sqlite3_api->blob_bytes
89601 #define sqlite3_blob_close sqlite3_api->blob_close
89602 #define sqlite3_blob_open sqlite3_api->blob_open
89603 #define sqlite3_blob_read sqlite3_api->blob_read
89604 #define sqlite3_blob_write sqlite3_api->blob_write
89605 #define sqlite3_create_collation_v2 sqlite3_api->create_collation_v2
89606 #define sqlite3_file_control sqlite3_api->file_control
89607 #define sqlite3_memory_highwater sqlite3_api->memory_highwater
89608 #define sqlite3_memory_used sqlite3_api->memory_used
89609 #define sqlite3_mutex_alloc sqlite3_api->mutex_alloc
89610 #define sqlite3_mutex_enter sqlite3_api->mutex_enter
89611 #define sqlite3_mutex_free sqlite3_api->mutex_free
89612 #define sqlite3_mutex_leave sqlite3_api->mutex_leave
89613 #define sqlite3_mutex_try sqlite3_api->mutex_try
89614 #define sqlite3_open_v2 sqlite3_api->open_v2
89615 #define sqlite3_release_memory sqlite3_api->release_memory
89616 #define sqlite3_result_error_nomem sqlite3_api->result_error_nomem
89617 #define sqlite3_result_error_toobig sqlite3_api->result_error_toobig
89618 #define sqlite3_sleep sqlite3_api->sleep
89619 #define sqlite3_soft_heap_limit sqlite3_api->soft_heap_limit
89620 #define sqlite3_vfs_find sqlite3_api->vfs_find
89621 #define sqlite3_vfs_register sqlite3_api->vfs_register
89622 #define sqlite3_vfs_unregister sqlite3_api->vfs_unregister
89623 #define sqlite3_threadsafe sqlite3_api->xthreadsafe
89624 #define sqlite3_result_zeroblob sqlite3_api->result_zeroblob
89625 #define sqlite3_result_error_code sqlite3_api->result_error_code
89626 #define sqlite3_test_control sqlite3_api->test_control
89627 #define sqlite3_randomness sqlite3_api->randomness
89628 #define sqlite3_context_db_handle sqlite3_api->context_db_handle
89629 #define sqlite3_extended_result_codes sqlite3_api->extended_result_codes
89630 #define sqlite3_limit sqlite3_api->limit
89631 #define sqlite3_next_stmt sqlite3_api->next_stmt
89632 #define sqlite3_sql sqlite3_api->sql
89633 #define sqlite3_status sqlite3_api->status
89634 #define sqlite3_backup_finish sqlite3_api->backup_finish
89635 #define sqlite3_backup_init sqlite3_api->backup_init
89636 #define sqlite3_backup_pagecount sqlite3_api->backup_pagecount
89637 #define sqlite3_backup_remaining sqlite3_api->backup_remaining
89638 #define sqlite3_backup_step sqlite3_api->backup_step
89639 #define sqlite3_compileoption_get sqlite3_api->compileoption_get
89640 #define sqlite3_compileoption_used sqlite3_api->compileoption_used
89641 #define sqlite3_create_function_v2 sqlite3_api->create_function_v2
89642 #define sqlite3_db_config sqlite3_api->db_config
89643 #define sqlite3_db_mutex sqlite3_api->db_mutex
89644 #define sqlite3_db_status sqlite3_api->db_status
89645 #define sqlite3_extended_errcode sqlite3_api->extended_errcode
89646 #define sqlite3_log sqlite3_api->log
89647 #define sqlite3_soft_heap_limit64 sqlite3_api->soft_heap_limit64
89648 #define sqlite3_sourceid sqlite3_api->sourceid
89649 #define sqlite3_stmt_status sqlite3_api->stmt_status
89650 #define sqlite3_strnicmp sqlite3_api->strnicmp
89651 #define sqlite3_unlock_notify sqlite3_api->unlock_notify
89652 #define sqlite3_wal_autocheckpoint sqlite3_api->wal_autocheckpoint
89653 #define sqlite3_wal_checkpoint sqlite3_api->wal_checkpoint
89654 #define sqlite3_wal_hook sqlite3_api->wal_hook
89655 #define sqlite3_blob_reopen sqlite3_api->blob_reopen
89656 #define sqlite3_vtab_config sqlite3_api->vtab_config
89657 #define sqlite3_vtab_on_conflict sqlite3_api->vtab_on_conflict
89658 #endif /* SQLITE_CORE */
89660 #define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api = 0;
89661 #define SQLITE_EXTENSION_INIT2(v) sqlite3_api = v;
89663 #endif /* _SQLITE3EXT_H_ */
89665 /************** End of sqlite3ext.h ******************************************/
89666 /************** Continuing where we left off in loadext.c ********************/
89667 /* #include <string.h> */
89669 #ifndef SQLITE_OMIT_LOAD_EXTENSION
89672 ** Some API routines are omitted when various features are
89673 ** excluded from a build of SQLite. Substitute a NULL pointer
89674 ** for any missing APIs.
89676 #ifndef SQLITE_ENABLE_COLUMN_METADATA
89677 # define sqlite3_column_database_name 0
89678 # define sqlite3_column_database_name16 0
89679 # define sqlite3_column_table_name 0
89680 # define sqlite3_column_table_name16 0
89681 # define sqlite3_column_origin_name 0
89682 # define sqlite3_column_origin_name16 0
89683 # define sqlite3_table_column_metadata 0
89684 #endif
89686 #ifdef SQLITE_OMIT_AUTHORIZATION
89687 # define sqlite3_set_authorizer 0
89688 #endif
89690 #ifdef SQLITE_OMIT_UTF16
89691 # define sqlite3_bind_text16 0
89692 # define sqlite3_collation_needed16 0
89693 # define sqlite3_column_decltype16 0
89694 # define sqlite3_column_name16 0
89695 # define sqlite3_column_text16 0
89696 # define sqlite3_complete16 0
89697 # define sqlite3_create_collation16 0
89698 # define sqlite3_create_function16 0
89699 # define sqlite3_errmsg16 0
89700 # define sqlite3_open16 0
89701 # define sqlite3_prepare16 0
89702 # define sqlite3_prepare16_v2 0
89703 # define sqlite3_result_error16 0
89704 # define sqlite3_result_text16 0
89705 # define sqlite3_result_text16be 0
89706 # define sqlite3_result_text16le 0
89707 # define sqlite3_value_text16 0
89708 # define sqlite3_value_text16be 0
89709 # define sqlite3_value_text16le 0
89710 # define sqlite3_column_database_name16 0
89711 # define sqlite3_column_table_name16 0
89712 # define sqlite3_column_origin_name16 0
89713 #endif
89715 #ifdef SQLITE_OMIT_COMPLETE
89716 # define sqlite3_complete 0
89717 # define sqlite3_complete16 0
89718 #endif
89720 #ifdef SQLITE_OMIT_DECLTYPE
89721 # define sqlite3_column_decltype16 0
89722 # define sqlite3_column_decltype 0
89723 #endif
89725 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
89726 # define sqlite3_progress_handler 0
89727 #endif
89729 #ifdef SQLITE_OMIT_VIRTUALTABLE
89730 # define sqlite3_create_module 0
89731 # define sqlite3_create_module_v2 0
89732 # define sqlite3_declare_vtab 0
89733 # define sqlite3_vtab_config 0
89734 # define sqlite3_vtab_on_conflict 0
89735 #endif
89737 #ifdef SQLITE_OMIT_SHARED_CACHE
89738 # define sqlite3_enable_shared_cache 0
89739 #endif
89741 #ifdef SQLITE_OMIT_TRACE
89742 # define sqlite3_profile 0
89743 # define sqlite3_trace 0
89744 #endif
89746 #ifdef SQLITE_OMIT_GET_TABLE
89747 # define sqlite3_free_table 0
89748 # define sqlite3_get_table 0
89749 #endif
89751 #ifdef SQLITE_OMIT_INCRBLOB
89752 #define sqlite3_bind_zeroblob 0
89753 #define sqlite3_blob_bytes 0
89754 #define sqlite3_blob_close 0
89755 #define sqlite3_blob_open 0
89756 #define sqlite3_blob_read 0
89757 #define sqlite3_blob_write 0
89758 #define sqlite3_blob_reopen 0
89759 #endif
89762 ** The following structure contains pointers to all SQLite API routines.
89763 ** A pointer to this structure is passed into extensions when they are
89764 ** loaded so that the extension can make calls back into the SQLite
89765 ** library.
89767 ** When adding new APIs, add them to the bottom of this structure
89768 ** in order to preserve backwards compatibility.
89770 ** Extensions that use newer APIs should first call the
89771 ** sqlite3_libversion_number() to make sure that the API they
89772 ** intend to use is supported by the library. Extensions should
89773 ** also check to make sure that the pointer to the function is
89774 ** not NULL before calling it.
89776 static const sqlite3_api_routines sqlite3Apis = {
89777 sqlite3_aggregate_context,
89778 #ifndef SQLITE_OMIT_DEPRECATED
89779 sqlite3_aggregate_count,
89780 #else
89782 #endif
89783 sqlite3_bind_blob,
89784 sqlite3_bind_double,
89785 sqlite3_bind_int,
89786 sqlite3_bind_int64,
89787 sqlite3_bind_null,
89788 sqlite3_bind_parameter_count,
89789 sqlite3_bind_parameter_index,
89790 sqlite3_bind_parameter_name,
89791 sqlite3_bind_text,
89792 sqlite3_bind_text16,
89793 sqlite3_bind_value,
89794 sqlite3_busy_handler,
89795 sqlite3_busy_timeout,
89796 sqlite3_changes,
89797 sqlite3_close,
89798 sqlite3_collation_needed,
89799 sqlite3_collation_needed16,
89800 sqlite3_column_blob,
89801 sqlite3_column_bytes,
89802 sqlite3_column_bytes16,
89803 sqlite3_column_count,
89804 sqlite3_column_database_name,
89805 sqlite3_column_database_name16,
89806 sqlite3_column_decltype,
89807 sqlite3_column_decltype16,
89808 sqlite3_column_double,
89809 sqlite3_column_int,
89810 sqlite3_column_int64,
89811 sqlite3_column_name,
89812 sqlite3_column_name16,
89813 sqlite3_column_origin_name,
89814 sqlite3_column_origin_name16,
89815 sqlite3_column_table_name,
89816 sqlite3_column_table_name16,
89817 sqlite3_column_text,
89818 sqlite3_column_text16,
89819 sqlite3_column_type,
89820 sqlite3_column_value,
89821 sqlite3_commit_hook,
89822 sqlite3_complete,
89823 sqlite3_complete16,
89824 sqlite3_create_collation,
89825 sqlite3_create_collation16,
89826 sqlite3_create_function,
89827 sqlite3_create_function16,
89828 sqlite3_create_module,
89829 sqlite3_data_count,
89830 sqlite3_db_handle,
89831 sqlite3_declare_vtab,
89832 sqlite3_enable_shared_cache,
89833 sqlite3_errcode,
89834 sqlite3_errmsg,
89835 sqlite3_errmsg16,
89836 sqlite3_exec,
89837 #ifndef SQLITE_OMIT_DEPRECATED
89838 sqlite3_expired,
89839 #else
89841 #endif
89842 sqlite3_finalize,
89843 sqlite3_free,
89844 sqlite3_free_table,
89845 sqlite3_get_autocommit,
89846 sqlite3_get_auxdata,
89847 sqlite3_get_table,
89848 0, /* Was sqlite3_global_recover(), but that function is deprecated */
89849 sqlite3_interrupt,
89850 sqlite3_last_insert_rowid,
89851 sqlite3_libversion,
89852 sqlite3_libversion_number,
89853 sqlite3_malloc,
89854 sqlite3_mprintf,
89855 sqlite3_open,
89856 sqlite3_open16,
89857 sqlite3_prepare,
89858 sqlite3_prepare16,
89859 sqlite3_profile,
89860 sqlite3_progress_handler,
89861 sqlite3_realloc,
89862 sqlite3_reset,
89863 sqlite3_result_blob,
89864 sqlite3_result_double,
89865 sqlite3_result_error,
89866 sqlite3_result_error16,
89867 sqlite3_result_int,
89868 sqlite3_result_int64,
89869 sqlite3_result_null,
89870 sqlite3_result_text,
89871 sqlite3_result_text16,
89872 sqlite3_result_text16be,
89873 sqlite3_result_text16le,
89874 sqlite3_result_value,
89875 sqlite3_rollback_hook,
89876 sqlite3_set_authorizer,
89877 sqlite3_set_auxdata,
89878 sqlite3_snprintf,
89879 sqlite3_step,
89880 sqlite3_table_column_metadata,
89881 #ifndef SQLITE_OMIT_DEPRECATED
89882 sqlite3_thread_cleanup,
89883 #else
89885 #endif
89886 sqlite3_total_changes,
89887 sqlite3_trace,
89888 #ifndef SQLITE_OMIT_DEPRECATED
89889 sqlite3_transfer_bindings,
89890 #else
89892 #endif
89893 sqlite3_update_hook,
89894 sqlite3_user_data,
89895 sqlite3_value_blob,
89896 sqlite3_value_bytes,
89897 sqlite3_value_bytes16,
89898 sqlite3_value_double,
89899 sqlite3_value_int,
89900 sqlite3_value_int64,
89901 sqlite3_value_numeric_type,
89902 sqlite3_value_text,
89903 sqlite3_value_text16,
89904 sqlite3_value_text16be,
89905 sqlite3_value_text16le,
89906 sqlite3_value_type,
89907 sqlite3_vmprintf,
89909 ** The original API set ends here. All extensions can call any
89910 ** of the APIs above provided that the pointer is not NULL. But
89911 ** before calling APIs that follow, extension should check the
89912 ** sqlite3_libversion_number() to make sure they are dealing with
89913 ** a library that is new enough to support that API.
89914 *************************************************************************
89916 sqlite3_overload_function,
89919 ** Added after 3.3.13
89921 sqlite3_prepare_v2,
89922 sqlite3_prepare16_v2,
89923 sqlite3_clear_bindings,
89926 ** Added for 3.4.1
89928 sqlite3_create_module_v2,
89931 ** Added for 3.5.0
89933 sqlite3_bind_zeroblob,
89934 sqlite3_blob_bytes,
89935 sqlite3_blob_close,
89936 sqlite3_blob_open,
89937 sqlite3_blob_read,
89938 sqlite3_blob_write,
89939 sqlite3_create_collation_v2,
89940 sqlite3_file_control,
89941 sqlite3_memory_highwater,
89942 sqlite3_memory_used,
89943 #ifdef SQLITE_MUTEX_OMIT
89949 #else
89950 sqlite3_mutex_alloc,
89951 sqlite3_mutex_enter,
89952 sqlite3_mutex_free,
89953 sqlite3_mutex_leave,
89954 sqlite3_mutex_try,
89955 #endif
89956 sqlite3_open_v2,
89957 sqlite3_release_memory,
89958 sqlite3_result_error_nomem,
89959 sqlite3_result_error_toobig,
89960 sqlite3_sleep,
89961 sqlite3_soft_heap_limit,
89962 sqlite3_vfs_find,
89963 sqlite3_vfs_register,
89964 sqlite3_vfs_unregister,
89967 ** Added for 3.5.8
89969 sqlite3_threadsafe,
89970 sqlite3_result_zeroblob,
89971 sqlite3_result_error_code,
89972 sqlite3_test_control,
89973 sqlite3_randomness,
89974 sqlite3_context_db_handle,
89977 ** Added for 3.6.0
89979 sqlite3_extended_result_codes,
89980 sqlite3_limit,
89981 sqlite3_next_stmt,
89982 sqlite3_sql,
89983 sqlite3_status,
89986 ** Added for 3.7.4
89988 sqlite3_backup_finish,
89989 sqlite3_backup_init,
89990 sqlite3_backup_pagecount,
89991 sqlite3_backup_remaining,
89992 sqlite3_backup_step,
89993 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
89994 sqlite3_compileoption_get,
89995 sqlite3_compileoption_used,
89996 #else
89999 #endif
90000 sqlite3_create_function_v2,
90001 sqlite3_db_config,
90002 sqlite3_db_mutex,
90003 sqlite3_db_status,
90004 sqlite3_extended_errcode,
90005 sqlite3_log,
90006 sqlite3_soft_heap_limit64,
90007 sqlite3_sourceid,
90008 sqlite3_stmt_status,
90009 sqlite3_strnicmp,
90010 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
90011 sqlite3_unlock_notify,
90012 #else
90014 #endif
90015 #ifndef SQLITE_OMIT_WAL
90016 sqlite3_wal_autocheckpoint,
90017 sqlite3_wal_checkpoint,
90018 sqlite3_wal_hook,
90019 #else
90023 #endif
90024 sqlite3_blob_reopen,
90025 sqlite3_vtab_config,
90026 sqlite3_vtab_on_conflict,
90030 ** Attempt to load an SQLite extension library contained in the file
90031 ** zFile. The entry point is zProc. zProc may be 0 in which case a
90032 ** default entry point name (sqlite3_extension_init) is used. Use
90033 ** of the default name is recommended.
90035 ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
90037 ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
90038 ** error message text. The calling function should free this memory
90039 ** by calling sqlite3DbFree(db, ).
90041 static int sqlite3LoadExtension(
90042 sqlite3 *db, /* Load the extension into this database connection */
90043 const char *zFile, /* Name of the shared library containing extension */
90044 const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
90045 char **pzErrMsg /* Put error message here if not 0 */
90047 sqlite3_vfs *pVfs = db->pVfs;
90048 void *handle;
90049 int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
90050 char *zErrmsg = 0;
90051 void **aHandle;
90052 int nMsg = 300 + sqlite3Strlen30(zFile);
90054 if( pzErrMsg ) *pzErrMsg = 0;
90056 /* Ticket #1863. To avoid a creating security problems for older
90057 ** applications that relink against newer versions of SQLite, the
90058 ** ability to run load_extension is turned off by default. One
90059 ** must call sqlite3_enable_load_extension() to turn on extension
90060 ** loading. Otherwise you get the following error.
90062 if( (db->flags & SQLITE_LoadExtension)==0 ){
90063 if( pzErrMsg ){
90064 *pzErrMsg = sqlite3_mprintf("not authorized");
90066 return SQLITE_ERROR;
90069 if( zProc==0 ){
90070 zProc = "sqlite3_extension_init";
90073 handle = sqlite3OsDlOpen(pVfs, zFile);
90074 if( handle==0 ){
90075 if( pzErrMsg ){
90076 *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
90077 if( zErrmsg ){
90078 sqlite3_snprintf(nMsg, zErrmsg,
90079 "unable to open shared library [%s]", zFile);
90080 sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
90083 return SQLITE_ERROR;
90085 xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
90086 sqlite3OsDlSym(pVfs, handle, zProc);
90087 if( xInit==0 ){
90088 if( pzErrMsg ){
90089 nMsg += sqlite3Strlen30(zProc);
90090 *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
90091 if( zErrmsg ){
90092 sqlite3_snprintf(nMsg, zErrmsg,
90093 "no entry point [%s] in shared library [%s]", zProc,zFile);
90094 sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
90096 sqlite3OsDlClose(pVfs, handle);
90098 return SQLITE_ERROR;
90099 }else if( xInit(db, &zErrmsg, &sqlite3Apis) ){
90100 if( pzErrMsg ){
90101 *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
90103 sqlite3_free(zErrmsg);
90104 sqlite3OsDlClose(pVfs, handle);
90105 return SQLITE_ERROR;
90108 /* Append the new shared library handle to the db->aExtension array. */
90109 aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
90110 if( aHandle==0 ){
90111 return SQLITE_NOMEM;
90113 if( db->nExtension>0 ){
90114 memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
90116 sqlite3DbFree(db, db->aExtension);
90117 db->aExtension = aHandle;
90119 db->aExtension[db->nExtension++] = handle;
90120 return SQLITE_OK;
90122 SQLITE_API int sqlite3_load_extension(
90123 sqlite3 *db, /* Load the extension into this database connection */
90124 const char *zFile, /* Name of the shared library containing extension */
90125 const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
90126 char **pzErrMsg /* Put error message here if not 0 */
90128 int rc;
90129 sqlite3_mutex_enter(db->mutex);
90130 rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
90131 rc = sqlite3ApiExit(db, rc);
90132 sqlite3_mutex_leave(db->mutex);
90133 return rc;
90137 ** Call this routine when the database connection is closing in order
90138 ** to clean up loaded extensions
90140 SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
90141 int i;
90142 assert( sqlite3_mutex_held(db->mutex) );
90143 for(i=0; i<db->nExtension; i++){
90144 sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
90146 sqlite3DbFree(db, db->aExtension);
90150 ** Enable or disable extension loading. Extension loading is disabled by
90151 ** default so as not to open security holes in older applications.
90153 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
90154 sqlite3_mutex_enter(db->mutex);
90155 if( onoff ){
90156 db->flags |= SQLITE_LoadExtension;
90157 }else{
90158 db->flags &= ~SQLITE_LoadExtension;
90160 sqlite3_mutex_leave(db->mutex);
90161 return SQLITE_OK;
90164 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
90167 ** The auto-extension code added regardless of whether or not extension
90168 ** loading is supported. We need a dummy sqlite3Apis pointer for that
90169 ** code if regular extension loading is not available. This is that
90170 ** dummy pointer.
90172 #ifdef SQLITE_OMIT_LOAD_EXTENSION
90173 static const sqlite3_api_routines sqlite3Apis = { 0 };
90174 #endif
90178 ** The following object holds the list of automatically loaded
90179 ** extensions.
90181 ** This list is shared across threads. The SQLITE_MUTEX_STATIC_MASTER
90182 ** mutex must be held while accessing this list.
90184 typedef struct sqlite3AutoExtList sqlite3AutoExtList;
90185 static SQLITE_WSD struct sqlite3AutoExtList {
90186 int nExt; /* Number of entries in aExt[] */
90187 void (**aExt)(void); /* Pointers to the extension init functions */
90188 } sqlite3Autoext = { 0, 0 };
90190 /* The "wsdAutoext" macro will resolve to the autoextension
90191 ** state vector. If writable static data is unsupported on the target,
90192 ** we have to locate the state vector at run-time. In the more common
90193 ** case where writable static data is supported, wsdStat can refer directly
90194 ** to the "sqlite3Autoext" state vector declared above.
90196 #ifdef SQLITE_OMIT_WSD
90197 # define wsdAutoextInit \
90198 sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
90199 # define wsdAutoext x[0]
90200 #else
90201 # define wsdAutoextInit
90202 # define wsdAutoext sqlite3Autoext
90203 #endif
90207 ** Register a statically linked extension that is automatically
90208 ** loaded by every new database connection.
90210 SQLITE_API int sqlite3_auto_extension(void (*xInit)(void)){
90211 int rc = SQLITE_OK;
90212 #ifndef SQLITE_OMIT_AUTOINIT
90213 rc = sqlite3_initialize();
90214 if( rc ){
90215 return rc;
90216 }else
90217 #endif
90219 int i;
90220 #if SQLITE_THREADSAFE
90221 sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
90222 #endif
90223 wsdAutoextInit;
90224 sqlite3_mutex_enter(mutex);
90225 for(i=0; i<wsdAutoext.nExt; i++){
90226 if( wsdAutoext.aExt[i]==xInit ) break;
90228 if( i==wsdAutoext.nExt ){
90229 int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
90230 void (**aNew)(void);
90231 aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
90232 if( aNew==0 ){
90233 rc = SQLITE_NOMEM;
90234 }else{
90235 wsdAutoext.aExt = aNew;
90236 wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
90237 wsdAutoext.nExt++;
90240 sqlite3_mutex_leave(mutex);
90241 assert( (rc&0xff)==rc );
90242 return rc;
90247 ** Reset the automatic extension loading mechanism.
90249 SQLITE_API void sqlite3_reset_auto_extension(void){
90250 #ifndef SQLITE_OMIT_AUTOINIT
90251 if( sqlite3_initialize()==SQLITE_OK )
90252 #endif
90254 #if SQLITE_THREADSAFE
90255 sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
90256 #endif
90257 wsdAutoextInit;
90258 sqlite3_mutex_enter(mutex);
90259 sqlite3_free(wsdAutoext.aExt);
90260 wsdAutoext.aExt = 0;
90261 wsdAutoext.nExt = 0;
90262 sqlite3_mutex_leave(mutex);
90267 ** Load all automatic extensions.
90269 ** If anything goes wrong, set an error in the database connection.
90271 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
90272 int i;
90273 int go = 1;
90274 int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
90276 wsdAutoextInit;
90277 if( wsdAutoext.nExt==0 ){
90278 /* Common case: early out without every having to acquire a mutex */
90279 return;
90281 for(i=0; go; i++){
90282 char *zErrmsg;
90283 #if SQLITE_THREADSAFE
90284 sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
90285 #endif
90286 sqlite3_mutex_enter(mutex);
90287 if( i>=wsdAutoext.nExt ){
90288 xInit = 0;
90289 go = 0;
90290 }else{
90291 xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
90292 wsdAutoext.aExt[i];
90294 sqlite3_mutex_leave(mutex);
90295 zErrmsg = 0;
90296 if( xInit && xInit(db, &zErrmsg, &sqlite3Apis) ){
90297 sqlite3Error(db, SQLITE_ERROR,
90298 "automatic extension loading failed: %s", zErrmsg);
90299 go = 0;
90301 sqlite3_free(zErrmsg);
90305 /************** End of loadext.c *********************************************/
90306 /************** Begin file pragma.c ******************************************/
90308 ** 2003 April 6
90310 ** The author disclaims copyright to this source code. In place of
90311 ** a legal notice, here is a blessing:
90313 ** May you do good and not evil.
90314 ** May you find forgiveness for yourself and forgive others.
90315 ** May you share freely, never taking more than you give.
90317 *************************************************************************
90318 ** This file contains code used to implement the PRAGMA command.
90322 ** Interpret the given string as a safety level. Return 0 for OFF,
90323 ** 1 for ON or NORMAL and 2 for FULL. Return 1 for an empty or
90324 ** unrecognized string argument.
90326 ** Note that the values returned are one less that the values that
90327 ** should be passed into sqlite3BtreeSetSafetyLevel(). The is done
90328 ** to support legacy SQL code. The safety level used to be boolean
90329 ** and older scripts may have used numbers 0 for OFF and 1 for ON.
90331 static u8 getSafetyLevel(const char *z){
90332 /* 123456789 123456789 */
90333 static const char zText[] = "onoffalseyestruefull";
90334 static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
90335 static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
90336 static const u8 iValue[] = {1, 0, 0, 0, 1, 1, 2};
90337 int i, n;
90338 if( sqlite3Isdigit(*z) ){
90339 return (u8)sqlite3Atoi(z);
90341 n = sqlite3Strlen30(z);
90342 for(i=0; i<ArraySize(iLength); i++){
90343 if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
90344 return iValue[i];
90347 return 1;
90351 ** Interpret the given string as a boolean value.
90353 SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z){
90354 return getSafetyLevel(z)&1;
90357 /* The sqlite3GetBoolean() function is used by other modules but the
90358 ** remainder of this file is specific to PRAGMA processing. So omit
90359 ** the rest of the file if PRAGMAs are omitted from the build.
90361 #if !defined(SQLITE_OMIT_PRAGMA)
90364 ** Interpret the given string as a locking mode value.
90366 static int getLockingMode(const char *z){
90367 if( z ){
90368 if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
90369 if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
90371 return PAGER_LOCKINGMODE_QUERY;
90374 #ifndef SQLITE_OMIT_AUTOVACUUM
90376 ** Interpret the given string as an auto-vacuum mode value.
90378 ** The following strings, "none", "full" and "incremental" are
90379 ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
90381 static int getAutoVacuum(const char *z){
90382 int i;
90383 if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
90384 if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
90385 if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
90386 i = sqlite3Atoi(z);
90387 return (u8)((i>=0&&i<=2)?i:0);
90389 #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
90391 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
90393 ** Interpret the given string as a temp db location. Return 1 for file
90394 ** backed temporary databases, 2 for the Red-Black tree in memory database
90395 ** and 0 to use the compile-time default.
90397 static int getTempStore(const char *z){
90398 if( z[0]>='0' && z[0]<='2' ){
90399 return z[0] - '0';
90400 }else if( sqlite3StrICmp(z, "file")==0 ){
90401 return 1;
90402 }else if( sqlite3StrICmp(z, "memory")==0 ){
90403 return 2;
90404 }else{
90405 return 0;
90408 #endif /* SQLITE_PAGER_PRAGMAS */
90410 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
90412 ** Invalidate temp storage, either when the temp storage is changed
90413 ** from default, or when 'file' and the temp_store_directory has changed
90415 static int invalidateTempStorage(Parse *pParse){
90416 sqlite3 *db = pParse->db;
90417 if( db->aDb[1].pBt!=0 ){
90418 if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
90419 sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
90420 "from within a transaction");
90421 return SQLITE_ERROR;
90423 sqlite3BtreeClose(db->aDb[1].pBt);
90424 db->aDb[1].pBt = 0;
90425 sqlite3ResetInternalSchema(db, -1);
90427 return SQLITE_OK;
90429 #endif /* SQLITE_PAGER_PRAGMAS */
90431 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
90433 ** If the TEMP database is open, close it and mark the database schema
90434 ** as needing reloading. This must be done when using the SQLITE_TEMP_STORE
90435 ** or DEFAULT_TEMP_STORE pragmas.
90437 static int changeTempStorage(Parse *pParse, const char *zStorageType){
90438 int ts = getTempStore(zStorageType);
90439 sqlite3 *db = pParse->db;
90440 if( db->temp_store==ts ) return SQLITE_OK;
90441 if( invalidateTempStorage( pParse ) != SQLITE_OK ){
90442 return SQLITE_ERROR;
90444 db->temp_store = (u8)ts;
90445 return SQLITE_OK;
90447 #endif /* SQLITE_PAGER_PRAGMAS */
90450 ** Generate code to return a single integer value.
90452 static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
90453 Vdbe *v = sqlite3GetVdbe(pParse);
90454 int mem = ++pParse->nMem;
90455 i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
90456 if( pI64 ){
90457 memcpy(pI64, &value, sizeof(value));
90459 sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);
90460 sqlite3VdbeSetNumCols(v, 1);
90461 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
90462 sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
90465 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
90467 ** Check to see if zRight and zLeft refer to a pragma that queries
90468 ** or changes one of the flags in db->flags. Return 1 if so and 0 if not.
90469 ** Also, implement the pragma.
90471 static int flagPragma(Parse *pParse, const char *zLeft, const char *zRight){
90472 static const struct sPragmaType {
90473 const char *zName; /* Name of the pragma */
90474 int mask; /* Mask for the db->flags value */
90475 } aPragma[] = {
90476 { "full_column_names", SQLITE_FullColNames },
90477 { "short_column_names", SQLITE_ShortColNames },
90478 { "count_changes", SQLITE_CountRows },
90479 { "empty_result_callbacks", SQLITE_NullCallback },
90480 { "legacy_file_format", SQLITE_LegacyFileFmt },
90481 { "fullfsync", SQLITE_FullFSync },
90482 { "checkpoint_fullfsync", SQLITE_CkptFullFSync },
90483 { "reverse_unordered_selects", SQLITE_ReverseOrder },
90484 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
90485 { "automatic_index", SQLITE_AutoIndex },
90486 #endif
90487 #ifdef SQLITE_DEBUG
90488 { "sql_trace", SQLITE_SqlTrace },
90489 { "vdbe_listing", SQLITE_VdbeListing },
90490 { "vdbe_trace", SQLITE_VdbeTrace },
90491 #endif
90492 #ifndef SQLITE_OMIT_CHECK
90493 { "ignore_check_constraints", SQLITE_IgnoreChecks },
90494 #endif
90495 /* The following is VERY experimental */
90496 { "writable_schema", SQLITE_WriteSchema|SQLITE_RecoveryMode },
90497 { "omit_readlock", SQLITE_NoReadlock },
90499 /* TODO: Maybe it shouldn't be possible to change the ReadUncommitted
90500 ** flag if there are any active statements. */
90501 { "read_uncommitted", SQLITE_ReadUncommitted },
90502 { "recursive_triggers", SQLITE_RecTriggers },
90504 /* This flag may only be set if both foreign-key and trigger support
90505 ** are present in the build. */
90506 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
90507 { "foreign_keys", SQLITE_ForeignKeys },
90508 #endif
90510 int i;
90511 const struct sPragmaType *p;
90512 for(i=0, p=aPragma; i<ArraySize(aPragma); i++, p++){
90513 if( sqlite3StrICmp(zLeft, p->zName)==0 ){
90514 sqlite3 *db = pParse->db;
90515 Vdbe *v;
90516 v = sqlite3GetVdbe(pParse);
90517 assert( v!=0 ); /* Already allocated by sqlite3Pragma() */
90518 if( ALWAYS(v) ){
90519 if( zRight==0 ){
90520 returnSingleInt(pParse, p->zName, (db->flags & p->mask)!=0 );
90521 }else{
90522 int mask = p->mask; /* Mask of bits to set or clear. */
90523 if( db->autoCommit==0 ){
90524 /* Foreign key support may not be enabled or disabled while not
90525 ** in auto-commit mode. */
90526 mask &= ~(SQLITE_ForeignKeys);
90529 if( sqlite3GetBoolean(zRight) ){
90530 db->flags |= mask;
90531 }else{
90532 db->flags &= ~mask;
90535 /* Many of the flag-pragmas modify the code generated by the SQL
90536 ** compiler (eg. count_changes). So add an opcode to expire all
90537 ** compiled SQL statements after modifying a pragma value.
90539 sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
90543 return 1;
90546 return 0;
90548 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
90551 ** Return a human-readable name for a constraint resolution action.
90553 #ifndef SQLITE_OMIT_FOREIGN_KEY
90554 static const char *actionName(u8 action){
90555 const char *zName;
90556 switch( action ){
90557 case OE_SetNull: zName = "SET NULL"; break;
90558 case OE_SetDflt: zName = "SET DEFAULT"; break;
90559 case OE_Cascade: zName = "CASCADE"; break;
90560 case OE_Restrict: zName = "RESTRICT"; break;
90561 default: zName = "NO ACTION";
90562 assert( action==OE_None ); break;
90564 return zName;
90566 #endif
90570 ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
90571 ** defined in pager.h. This function returns the associated lowercase
90572 ** journal-mode name.
90574 SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
90575 static char * const azModeName[] = {
90576 "delete", "persist", "off", "truncate", "memory"
90577 #ifndef SQLITE_OMIT_WAL
90578 , "wal"
90579 #endif
90581 assert( PAGER_JOURNALMODE_DELETE==0 );
90582 assert( PAGER_JOURNALMODE_PERSIST==1 );
90583 assert( PAGER_JOURNALMODE_OFF==2 );
90584 assert( PAGER_JOURNALMODE_TRUNCATE==3 );
90585 assert( PAGER_JOURNALMODE_MEMORY==4 );
90586 assert( PAGER_JOURNALMODE_WAL==5 );
90587 assert( eMode>=0 && eMode<=ArraySize(azModeName) );
90589 if( eMode==ArraySize(azModeName) ) return 0;
90590 return azModeName[eMode];
90594 ** Process a pragma statement.
90596 ** Pragmas are of this form:
90598 ** PRAGMA [database.]id [= value]
90600 ** The identifier might also be a string. The value is a string, and
90601 ** identifier, or a number. If minusFlag is true, then the value is
90602 ** a number that was preceded by a minus sign.
90604 ** If the left side is "database.id" then pId1 is the database name
90605 ** and pId2 is the id. If the left side is just "id" then pId1 is the
90606 ** id and pId2 is any empty string.
90608 SQLITE_PRIVATE void sqlite3Pragma(
90609 Parse *pParse,
90610 Token *pId1, /* First part of [database.]id field */
90611 Token *pId2, /* Second part of [database.]id field, or NULL */
90612 Token *pValue, /* Token for <value>, or NULL */
90613 int minusFlag /* True if a '-' sign preceded <value> */
90615 char *zLeft = 0; /* Nul-terminated UTF-8 string <id> */
90616 char *zRight = 0; /* Nul-terminated UTF-8 string <value>, or NULL */
90617 const char *zDb = 0; /* The database name */
90618 Token *pId; /* Pointer to <id> token */
90619 int iDb; /* Database index for <database> */
90620 sqlite3 *db = pParse->db;
90621 Db *pDb;
90622 Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(db);
90623 if( v==0 ) return;
90624 sqlite3VdbeRunOnlyOnce(v);
90625 pParse->nMem = 2;
90627 /* Interpret the [database.] part of the pragma statement. iDb is the
90628 ** index of the database this pragma is being applied to in db.aDb[]. */
90629 iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
90630 if( iDb<0 ) return;
90631 pDb = &db->aDb[iDb];
90633 /* If the temp database has been explicitly named as part of the
90634 ** pragma, make sure it is open.
90636 if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
90637 return;
90640 zLeft = sqlite3NameFromToken(db, pId);
90641 if( !zLeft ) return;
90642 if( minusFlag ){
90643 zRight = sqlite3MPrintf(db, "-%T", pValue);
90644 }else{
90645 zRight = sqlite3NameFromToken(db, pValue);
90648 assert( pId2 );
90649 zDb = pId2->n>0 ? pDb->zName : 0;
90650 if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
90651 goto pragma_out;
90654 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
90656 ** PRAGMA [database.]default_cache_size
90657 ** PRAGMA [database.]default_cache_size=N
90659 ** The first form reports the current persistent setting for the
90660 ** page cache size. The value returned is the maximum number of
90661 ** pages in the page cache. The second form sets both the current
90662 ** page cache size value and the persistent page cache size value
90663 ** stored in the database file.
90665 ** Older versions of SQLite would set the default cache size to a
90666 ** negative number to indicate synchronous=OFF. These days, synchronous
90667 ** is always on by default regardless of the sign of the default cache
90668 ** size. But continue to take the absolute value of the default cache
90669 ** size of historical compatibility.
90671 if( sqlite3StrICmp(zLeft,"default_cache_size")==0 ){
90672 static const VdbeOpList getCacheSize[] = {
90673 { OP_Transaction, 0, 0, 0}, /* 0 */
90674 { OP_ReadCookie, 0, 1, BTREE_DEFAULT_CACHE_SIZE}, /* 1 */
90675 { OP_IfPos, 1, 7, 0},
90676 { OP_Integer, 0, 2, 0},
90677 { OP_Subtract, 1, 2, 1},
90678 { OP_IfPos, 1, 7, 0},
90679 { OP_Integer, 0, 1, 0}, /* 6 */
90680 { OP_ResultRow, 1, 1, 0},
90682 int addr;
90683 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
90684 sqlite3VdbeUsesBtree(v, iDb);
90685 if( !zRight ){
90686 sqlite3VdbeSetNumCols(v, 1);
90687 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
90688 pParse->nMem += 2;
90689 addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
90690 sqlite3VdbeChangeP1(v, addr, iDb);
90691 sqlite3VdbeChangeP1(v, addr+1, iDb);
90692 sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
90693 }else{
90694 int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
90695 sqlite3BeginWriteOperation(pParse, 0, iDb);
90696 sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
90697 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
90698 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
90699 pDb->pSchema->cache_size = size;
90700 sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
90702 }else
90705 ** PRAGMA [database.]page_size
90706 ** PRAGMA [database.]page_size=N
90708 ** The first form reports the current setting for the
90709 ** database page size in bytes. The second form sets the
90710 ** database page size value. The value can only be set if
90711 ** the database has not yet been created.
90713 if( sqlite3StrICmp(zLeft,"page_size")==0 ){
90714 Btree *pBt = pDb->pBt;
90715 assert( pBt!=0 );
90716 if( !zRight ){
90717 int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
90718 returnSingleInt(pParse, "page_size", size);
90719 }else{
90720 /* Malloc may fail when setting the page-size, as there is an internal
90721 ** buffer that the pager module resizes using sqlite3_realloc().
90723 db->nextPagesize = sqlite3Atoi(zRight);
90724 if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
90725 db->mallocFailed = 1;
90728 }else
90731 ** PRAGMA [database.]secure_delete
90732 ** PRAGMA [database.]secure_delete=ON/OFF
90734 ** The first form reports the current setting for the
90735 ** secure_delete flag. The second form changes the secure_delete
90736 ** flag setting and reports thenew value.
90738 if( sqlite3StrICmp(zLeft,"secure_delete")==0 ){
90739 Btree *pBt = pDb->pBt;
90740 int b = -1;
90741 assert( pBt!=0 );
90742 if( zRight ){
90743 b = sqlite3GetBoolean(zRight);
90745 if( pId2->n==0 && b>=0 ){
90746 int ii;
90747 for(ii=0; ii<db->nDb; ii++){
90748 sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
90751 b = sqlite3BtreeSecureDelete(pBt, b);
90752 returnSingleInt(pParse, "secure_delete", b);
90753 }else
90756 ** PRAGMA [database.]max_page_count
90757 ** PRAGMA [database.]max_page_count=N
90759 ** The first form reports the current setting for the
90760 ** maximum number of pages in the database file. The
90761 ** second form attempts to change this setting. Both
90762 ** forms return the current setting.
90764 ** PRAGMA [database.]page_count
90766 ** Return the number of pages in the specified database.
90768 if( sqlite3StrICmp(zLeft,"page_count")==0
90769 || sqlite3StrICmp(zLeft,"max_page_count")==0
90771 int iReg;
90772 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
90773 sqlite3CodeVerifySchema(pParse, iDb);
90774 iReg = ++pParse->nMem;
90775 if( sqlite3Tolower(zLeft[0])=='p' ){
90776 sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
90777 }else{
90778 sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg, sqlite3Atoi(zRight));
90780 sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
90781 sqlite3VdbeSetNumCols(v, 1);
90782 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
90783 }else
90786 ** PRAGMA [database.]locking_mode
90787 ** PRAGMA [database.]locking_mode = (normal|exclusive)
90789 if( sqlite3StrICmp(zLeft,"locking_mode")==0 ){
90790 const char *zRet = "normal";
90791 int eMode = getLockingMode(zRight);
90793 if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
90794 /* Simple "PRAGMA locking_mode;" statement. This is a query for
90795 ** the current default locking mode (which may be different to
90796 ** the locking-mode of the main database).
90798 eMode = db->dfltLockMode;
90799 }else{
90800 Pager *pPager;
90801 if( pId2->n==0 ){
90802 /* This indicates that no database name was specified as part
90803 ** of the PRAGMA command. In this case the locking-mode must be
90804 ** set on all attached databases, as well as the main db file.
90806 ** Also, the sqlite3.dfltLockMode variable is set so that
90807 ** any subsequently attached databases also use the specified
90808 ** locking mode.
90810 int ii;
90811 assert(pDb==&db->aDb[0]);
90812 for(ii=2; ii<db->nDb; ii++){
90813 pPager = sqlite3BtreePager(db->aDb[ii].pBt);
90814 sqlite3PagerLockingMode(pPager, eMode);
90816 db->dfltLockMode = (u8)eMode;
90818 pPager = sqlite3BtreePager(pDb->pBt);
90819 eMode = sqlite3PagerLockingMode(pPager, eMode);
90822 assert(eMode==PAGER_LOCKINGMODE_NORMAL||eMode==PAGER_LOCKINGMODE_EXCLUSIVE);
90823 if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
90824 zRet = "exclusive";
90826 sqlite3VdbeSetNumCols(v, 1);
90827 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
90828 sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
90829 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
90830 }else
90833 ** PRAGMA [database.]journal_mode
90834 ** PRAGMA [database.]journal_mode =
90835 ** (delete|persist|off|truncate|memory|wal|off)
90837 if( sqlite3StrICmp(zLeft,"journal_mode")==0 ){
90838 int eMode; /* One of the PAGER_JOURNALMODE_XXX symbols */
90839 int ii; /* Loop counter */
90841 /* Force the schema to be loaded on all databases. This causes all
90842 ** database files to be opened and the journal_modes set. This is
90843 ** necessary because subsequent processing must know if the databases
90844 ** are in WAL mode. */
90845 if( sqlite3ReadSchema(pParse) ){
90846 goto pragma_out;
90849 sqlite3VdbeSetNumCols(v, 1);
90850 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
90852 if( zRight==0 ){
90853 /* If there is no "=MODE" part of the pragma, do a query for the
90854 ** current mode */
90855 eMode = PAGER_JOURNALMODE_QUERY;
90856 }else{
90857 const char *zMode;
90858 int n = sqlite3Strlen30(zRight);
90859 for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
90860 if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
90862 if( !zMode ){
90863 /* If the "=MODE" part does not match any known journal mode,
90864 ** then do a query */
90865 eMode = PAGER_JOURNALMODE_QUERY;
90868 if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
90869 /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
90870 iDb = 0;
90871 pId2->n = 1;
90873 for(ii=db->nDb-1; ii>=0; ii--){
90874 if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
90875 sqlite3VdbeUsesBtree(v, ii);
90876 sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
90879 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
90880 }else
90883 ** PRAGMA [database.]journal_size_limit
90884 ** PRAGMA [database.]journal_size_limit=N
90886 ** Get or set the size limit on rollback journal files.
90888 if( sqlite3StrICmp(zLeft,"journal_size_limit")==0 ){
90889 Pager *pPager = sqlite3BtreePager(pDb->pBt);
90890 i64 iLimit = -2;
90891 if( zRight ){
90892 sqlite3Atoi64(zRight, &iLimit, 1000000, SQLITE_UTF8);
90893 if( iLimit<-1 ) iLimit = -1;
90895 iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
90896 returnSingleInt(pParse, "journal_size_limit", iLimit);
90897 }else
90899 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
90902 ** PRAGMA [database.]auto_vacuum
90903 ** PRAGMA [database.]auto_vacuum=N
90905 ** Get or set the value of the database 'auto-vacuum' parameter.
90906 ** The value is one of: 0 NONE 1 FULL 2 INCREMENTAL
90908 #ifndef SQLITE_OMIT_AUTOVACUUM
90909 if( sqlite3StrICmp(zLeft,"auto_vacuum")==0 ){
90910 Btree *pBt = pDb->pBt;
90911 assert( pBt!=0 );
90912 if( sqlite3ReadSchema(pParse) ){
90913 goto pragma_out;
90915 if( !zRight ){
90916 int auto_vacuum;
90917 if( ALWAYS(pBt) ){
90918 auto_vacuum = sqlite3BtreeGetAutoVacuum(pBt);
90919 }else{
90920 auto_vacuum = SQLITE_DEFAULT_AUTOVACUUM;
90922 returnSingleInt(pParse, "auto_vacuum", auto_vacuum);
90923 }else{
90924 int eAuto = getAutoVacuum(zRight);
90925 assert( eAuto>=0 && eAuto<=2 );
90926 db->nextAutovac = (u8)eAuto;
90927 if( ALWAYS(eAuto>=0) ){
90928 /* Call SetAutoVacuum() to set initialize the internal auto and
90929 ** incr-vacuum flags. This is required in case this connection
90930 ** creates the database file. It is important that it is created
90931 ** as an auto-vacuum capable db.
90933 int rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
90934 if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
90935 /* When setting the auto_vacuum mode to either "full" or
90936 ** "incremental", write the value of meta[6] in the database
90937 ** file. Before writing to meta[6], check that meta[3] indicates
90938 ** that this really is an auto-vacuum capable database.
90940 static const VdbeOpList setMeta6[] = {
90941 { OP_Transaction, 0, 1, 0}, /* 0 */
90942 { OP_ReadCookie, 0, 1, BTREE_LARGEST_ROOT_PAGE},
90943 { OP_If, 1, 0, 0}, /* 2 */
90944 { OP_Halt, SQLITE_OK, OE_Abort, 0}, /* 3 */
90945 { OP_Integer, 0, 1, 0}, /* 4 */
90946 { OP_SetCookie, 0, BTREE_INCR_VACUUM, 1}, /* 5 */
90948 int iAddr;
90949 iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
90950 sqlite3VdbeChangeP1(v, iAddr, iDb);
90951 sqlite3VdbeChangeP1(v, iAddr+1, iDb);
90952 sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
90953 sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
90954 sqlite3VdbeChangeP1(v, iAddr+5, iDb);
90955 sqlite3VdbeUsesBtree(v, iDb);
90959 }else
90960 #endif
90963 ** PRAGMA [database.]incremental_vacuum(N)
90965 ** Do N steps of incremental vacuuming on a database.
90967 #ifndef SQLITE_OMIT_AUTOVACUUM
90968 if( sqlite3StrICmp(zLeft,"incremental_vacuum")==0 ){
90969 int iLimit, addr;
90970 if( sqlite3ReadSchema(pParse) ){
90971 goto pragma_out;
90973 if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
90974 iLimit = 0x7fffffff;
90976 sqlite3BeginWriteOperation(pParse, 0, iDb);
90977 sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
90978 addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb);
90979 sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
90980 sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
90981 sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr);
90982 sqlite3VdbeJumpHere(v, addr);
90983 }else
90984 #endif
90986 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
90988 ** PRAGMA [database.]cache_size
90989 ** PRAGMA [database.]cache_size=N
90991 ** The first form reports the current local setting for the
90992 ** page cache size. The local setting can be different from
90993 ** the persistent cache size value that is stored in the database
90994 ** file itself. The value returned is the maximum number of
90995 ** pages in the page cache. The second form sets the local
90996 ** page cache size value. It does not change the persistent
90997 ** cache size stored on the disk so the cache size will revert
90998 ** to its default value when the database is closed and reopened.
90999 ** N should be a positive integer.
91001 if( sqlite3StrICmp(zLeft,"cache_size")==0 ){
91002 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
91003 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
91004 if( !zRight ){
91005 returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
91006 }else{
91007 int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
91008 pDb->pSchema->cache_size = size;
91009 sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
91011 }else
91014 ** PRAGMA temp_store
91015 ** PRAGMA temp_store = "default"|"memory"|"file"
91017 ** Return or set the local value of the temp_store flag. Changing
91018 ** the local value does not make changes to the disk file and the default
91019 ** value will be restored the next time the database is opened.
91021 ** Note that it is possible for the library compile-time options to
91022 ** override this setting
91024 if( sqlite3StrICmp(zLeft, "temp_store")==0 ){
91025 if( !zRight ){
91026 returnSingleInt(pParse, "temp_store", db->temp_store);
91027 }else{
91028 changeTempStorage(pParse, zRight);
91030 }else
91033 ** PRAGMA temp_store_directory
91034 ** PRAGMA temp_store_directory = ""|"directory_name"
91036 ** Return or set the local value of the temp_store_directory flag. Changing
91037 ** the value sets a specific directory to be used for temporary files.
91038 ** Setting to a null string reverts to the default temporary directory search.
91039 ** If temporary directory is changed, then invalidateTempStorage.
91042 if( sqlite3StrICmp(zLeft, "temp_store_directory")==0 ){
91043 if( !zRight ){
91044 if( sqlite3_temp_directory ){
91045 sqlite3VdbeSetNumCols(v, 1);
91046 sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
91047 "temp_store_directory", SQLITE_STATIC);
91048 sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
91049 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
91051 }else{
91052 #ifndef SQLITE_OMIT_WSD
91053 if( zRight[0] ){
91054 int rc;
91055 int res;
91056 rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
91057 if( rc!=SQLITE_OK || res==0 ){
91058 sqlite3ErrorMsg(pParse, "not a writable directory");
91059 goto pragma_out;
91062 if( SQLITE_TEMP_STORE==0
91063 || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
91064 || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
91066 invalidateTempStorage(pParse);
91068 sqlite3_free(sqlite3_temp_directory);
91069 if( zRight[0] ){
91070 sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
91071 }else{
91072 sqlite3_temp_directory = 0;
91074 #endif /* SQLITE_OMIT_WSD */
91076 }else
91078 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
91079 # if defined(__APPLE__)
91080 # define SQLITE_ENABLE_LOCKING_STYLE 1
91081 # else
91082 # define SQLITE_ENABLE_LOCKING_STYLE 0
91083 # endif
91084 #endif
91085 #if SQLITE_ENABLE_LOCKING_STYLE
91087 ** PRAGMA [database.]lock_proxy_file
91088 ** PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
91090 ** Return or set the value of the lock_proxy_file flag. Changing
91091 ** the value sets a specific file to be used for database access locks.
91094 if( sqlite3StrICmp(zLeft, "lock_proxy_file")==0 ){
91095 if( !zRight ){
91096 Pager *pPager = sqlite3BtreePager(pDb->pBt);
91097 char *proxy_file_path = NULL;
91098 sqlite3_file *pFile = sqlite3PagerFile(pPager);
91099 sqlite3OsFileControl(pFile, SQLITE_GET_LOCKPROXYFILE,
91100 &proxy_file_path);
91102 if( proxy_file_path ){
91103 sqlite3VdbeSetNumCols(v, 1);
91104 sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
91105 "lock_proxy_file", SQLITE_STATIC);
91106 sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
91107 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
91109 }else{
91110 Pager *pPager = sqlite3BtreePager(pDb->pBt);
91111 sqlite3_file *pFile = sqlite3PagerFile(pPager);
91112 int res;
91113 if( zRight[0] ){
91114 res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
91115 zRight);
91116 } else {
91117 res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
91118 NULL);
91120 if( res!=SQLITE_OK ){
91121 sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
91122 goto pragma_out;
91125 }else
91126 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
91129 ** PRAGMA [database.]synchronous
91130 ** PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
91132 ** Return or set the local value of the synchronous flag. Changing
91133 ** the local value does not make changes to the disk file and the
91134 ** default value will be restored the next time the database is
91135 ** opened.
91137 if( sqlite3StrICmp(zLeft,"synchronous")==0 ){
91138 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
91139 if( !zRight ){
91140 returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
91141 }else{
91142 if( !db->autoCommit ){
91143 sqlite3ErrorMsg(pParse,
91144 "Safety level may not be changed inside a transaction");
91145 }else{
91146 pDb->safety_level = getSafetyLevel(zRight)+1;
91149 }else
91150 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
91152 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
91153 if( flagPragma(pParse, zLeft, zRight) ){
91154 /* The flagPragma() subroutine also generates any necessary code
91155 ** there is nothing more to do here */
91156 }else
91157 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
91159 #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
91161 ** PRAGMA table_info(<table>)
91163 ** Return a single row for each column of the named table. The columns of
91164 ** the returned data set are:
91166 ** cid: Column id (numbered from left to right, starting at 0)
91167 ** name: Column name
91168 ** type: Column declaration type.
91169 ** notnull: True if 'NOT NULL' is part of column declaration
91170 ** dflt_value: The default value for the column, if any.
91172 if( sqlite3StrICmp(zLeft, "table_info")==0 && zRight ){
91173 Table *pTab;
91174 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
91175 pTab = sqlite3FindTable(db, zRight, zDb);
91176 if( pTab ){
91177 int i;
91178 int nHidden = 0;
91179 Column *pCol;
91180 sqlite3VdbeSetNumCols(v, 6);
91181 pParse->nMem = 6;
91182 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
91183 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
91184 sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
91185 sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
91186 sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
91187 sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
91188 sqlite3ViewGetColumnNames(pParse, pTab);
91189 for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
91190 if( IsHiddenColumn(pCol) ){
91191 nHidden++;
91192 continue;
91194 sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
91195 sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
91196 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
91197 pCol->zType ? pCol->zType : "", 0);
91198 sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
91199 if( pCol->zDflt ){
91200 sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
91201 }else{
91202 sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
91204 sqlite3VdbeAddOp2(v, OP_Integer, pCol->isPrimKey, 6);
91205 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
91208 }else
91210 if( sqlite3StrICmp(zLeft, "index_info")==0 && zRight ){
91211 Index *pIdx;
91212 Table *pTab;
91213 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
91214 pIdx = sqlite3FindIndex(db, zRight, zDb);
91215 if( pIdx ){
91216 int i;
91217 pTab = pIdx->pTable;
91218 sqlite3VdbeSetNumCols(v, 3);
91219 pParse->nMem = 3;
91220 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
91221 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
91222 sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
91223 for(i=0; i<pIdx->nColumn; i++){
91224 int cnum = pIdx->aiColumn[i];
91225 sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
91226 sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
91227 assert( pTab->nCol>cnum );
91228 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
91229 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
91232 }else
91234 if( sqlite3StrICmp(zLeft, "index_list")==0 && zRight ){
91235 Index *pIdx;
91236 Table *pTab;
91237 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
91238 pTab = sqlite3FindTable(db, zRight, zDb);
91239 if( pTab ){
91240 v = sqlite3GetVdbe(pParse);
91241 pIdx = pTab->pIndex;
91242 if( pIdx ){
91243 int i = 0;
91244 sqlite3VdbeSetNumCols(v, 3);
91245 pParse->nMem = 3;
91246 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
91247 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
91248 sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
91249 while(pIdx){
91250 sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
91251 sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
91252 sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
91253 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
91254 ++i;
91255 pIdx = pIdx->pNext;
91259 }else
91261 if( sqlite3StrICmp(zLeft, "database_list")==0 ){
91262 int i;
91263 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
91264 sqlite3VdbeSetNumCols(v, 3);
91265 pParse->nMem = 3;
91266 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
91267 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
91268 sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
91269 for(i=0; i<db->nDb; i++){
91270 if( db->aDb[i].pBt==0 ) continue;
91271 assert( db->aDb[i].zName!=0 );
91272 sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
91273 sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
91274 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
91275 sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
91276 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
91278 }else
91280 if( sqlite3StrICmp(zLeft, "collation_list")==0 ){
91281 int i = 0;
91282 HashElem *p;
91283 sqlite3VdbeSetNumCols(v, 2);
91284 pParse->nMem = 2;
91285 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
91286 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
91287 for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
91288 CollSeq *pColl = (CollSeq *)sqliteHashData(p);
91289 sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
91290 sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
91291 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
91293 }else
91294 #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
91296 #ifndef SQLITE_OMIT_FOREIGN_KEY
91297 if( sqlite3StrICmp(zLeft, "foreign_key_list")==0 && zRight ){
91298 FKey *pFK;
91299 Table *pTab;
91300 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
91301 pTab = sqlite3FindTable(db, zRight, zDb);
91302 if( pTab ){
91303 v = sqlite3GetVdbe(pParse);
91304 pFK = pTab->pFKey;
91305 if( pFK ){
91306 int i = 0;
91307 sqlite3VdbeSetNumCols(v, 8);
91308 pParse->nMem = 8;
91309 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
91310 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
91311 sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
91312 sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
91313 sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
91314 sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
91315 sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
91316 sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
91317 while(pFK){
91318 int j;
91319 for(j=0; j<pFK->nCol; j++){
91320 char *zCol = pFK->aCol[j].zCol;
91321 char *zOnDelete = (char *)actionName(pFK->aAction[0]);
91322 char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
91323 sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
91324 sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
91325 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
91326 sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
91327 pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
91328 sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
91329 sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
91330 sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
91331 sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
91332 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
91334 ++i;
91335 pFK = pFK->pNextFrom;
91339 }else
91340 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
91342 #ifndef NDEBUG
91343 if( sqlite3StrICmp(zLeft, "parser_trace")==0 ){
91344 if( zRight ){
91345 if( sqlite3GetBoolean(zRight) ){
91346 sqlite3ParserTrace(stderr, "parser: ");
91347 }else{
91348 sqlite3ParserTrace(0, 0);
91351 }else
91352 #endif
91354 /* Reinstall the LIKE and GLOB functions. The variant of LIKE
91355 ** used will be case sensitive or not depending on the RHS.
91357 if( sqlite3StrICmp(zLeft, "case_sensitive_like")==0 ){
91358 if( zRight ){
91359 sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight));
91361 }else
91363 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
91364 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
91365 #endif
91367 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
91368 /* Pragma "quick_check" is an experimental reduced version of
91369 ** integrity_check designed to detect most database corruption
91370 ** without most of the overhead of a full integrity-check.
91372 if( sqlite3StrICmp(zLeft, "integrity_check")==0
91373 || sqlite3StrICmp(zLeft, "quick_check")==0
91375 int i, j, addr, mxErr;
91377 /* Code that appears at the end of the integrity check. If no error
91378 ** messages have been generated, output OK. Otherwise output the
91379 ** error message
91381 static const VdbeOpList endCode[] = {
91382 { OP_AddImm, 1, 0, 0}, /* 0 */
91383 { OP_IfNeg, 1, 0, 0}, /* 1 */
91384 { OP_String8, 0, 3, 0}, /* 2 */
91385 { OP_ResultRow, 3, 1, 0},
91388 int isQuick = (sqlite3Tolower(zLeft[0])=='q');
91390 /* Initialize the VDBE program */
91391 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
91392 pParse->nMem = 6;
91393 sqlite3VdbeSetNumCols(v, 1);
91394 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
91396 /* Set the maximum error count */
91397 mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
91398 if( zRight ){
91399 sqlite3GetInt32(zRight, &mxErr);
91400 if( mxErr<=0 ){
91401 mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
91404 sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1); /* reg[1] holds errors left */
91406 /* Do an integrity check on each database file */
91407 for(i=0; i<db->nDb; i++){
91408 HashElem *x;
91409 Hash *pTbls;
91410 int cnt = 0;
91412 if( OMIT_TEMPDB && i==1 ) continue;
91414 sqlite3CodeVerifySchema(pParse, i);
91415 addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
91416 sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
91417 sqlite3VdbeJumpHere(v, addr);
91419 /* Do an integrity check of the B-Tree
91421 ** Begin by filling registers 2, 3, ... with the root pages numbers
91422 ** for all tables and indices in the database.
91424 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
91425 pTbls = &db->aDb[i].pSchema->tblHash;
91426 for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
91427 Table *pTab = sqliteHashData(x);
91428 Index *pIdx;
91429 sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
91430 cnt++;
91431 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
91432 sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
91433 cnt++;
91437 /* Make sure sufficient number of registers have been allocated */
91438 if( pParse->nMem < cnt+4 ){
91439 pParse->nMem = cnt+4;
91442 /* Do the b-tree integrity checks */
91443 sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
91444 sqlite3VdbeChangeP5(v, (u8)i);
91445 addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2);
91446 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
91447 sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
91448 P4_DYNAMIC);
91449 sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
91450 sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
91451 sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
91452 sqlite3VdbeJumpHere(v, addr);
91454 /* Make sure all the indices are constructed correctly.
91456 for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
91457 Table *pTab = sqliteHashData(x);
91458 Index *pIdx;
91459 int loopTop;
91461 if( pTab->pIndex==0 ) continue;
91462 addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Stop if out of errors */
91463 sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
91464 sqlite3VdbeJumpHere(v, addr);
91465 sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
91466 sqlite3VdbeAddOp2(v, OP_Integer, 0, 2); /* reg(2) will count entries */
91467 loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0);
91468 sqlite3VdbeAddOp2(v, OP_AddImm, 2, 1); /* increment entry count */
91469 for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
91470 int jmp2;
91471 int r1;
91472 static const VdbeOpList idxErr[] = {
91473 { OP_AddImm, 1, -1, 0},
91474 { OP_String8, 0, 3, 0}, /* 1 */
91475 { OP_Rowid, 1, 4, 0},
91476 { OP_String8, 0, 5, 0}, /* 3 */
91477 { OP_String8, 0, 6, 0}, /* 4 */
91478 { OP_Concat, 4, 3, 3},
91479 { OP_Concat, 5, 3, 3},
91480 { OP_Concat, 6, 3, 3},
91481 { OP_ResultRow, 3, 1, 0},
91482 { OP_IfPos, 1, 0, 0}, /* 9 */
91483 { OP_Halt, 0, 0, 0},
91485 r1 = sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 0);
91486 jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, j+2, 0, r1, pIdx->nColumn+1);
91487 addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
91488 sqlite3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC);
91489 sqlite3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC);
91490 sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_TRANSIENT);
91491 sqlite3VdbeJumpHere(v, addr+9);
91492 sqlite3VdbeJumpHere(v, jmp2);
91494 sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop+1);
91495 sqlite3VdbeJumpHere(v, loopTop);
91496 for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
91497 static const VdbeOpList cntIdx[] = {
91498 { OP_Integer, 0, 3, 0},
91499 { OP_Rewind, 0, 0, 0}, /* 1 */
91500 { OP_AddImm, 3, 1, 0},
91501 { OP_Next, 0, 0, 0}, /* 3 */
91502 { OP_Eq, 2, 0, 3}, /* 4 */
91503 { OP_AddImm, 1, -1, 0},
91504 { OP_String8, 0, 2, 0}, /* 6 */
91505 { OP_String8, 0, 3, 0}, /* 7 */
91506 { OP_Concat, 3, 2, 2},
91507 { OP_ResultRow, 2, 1, 0},
91509 addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);
91510 sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
91511 sqlite3VdbeJumpHere(v, addr);
91512 addr = sqlite3VdbeAddOpList(v, ArraySize(cntIdx), cntIdx);
91513 sqlite3VdbeChangeP1(v, addr+1, j+2);
91514 sqlite3VdbeChangeP2(v, addr+1, addr+4);
91515 sqlite3VdbeChangeP1(v, addr+3, j+2);
91516 sqlite3VdbeChangeP2(v, addr+3, addr+2);
91517 sqlite3VdbeJumpHere(v, addr+4);
91518 sqlite3VdbeChangeP4(v, addr+6,
91519 "wrong # of entries in index ", P4_STATIC);
91520 sqlite3VdbeChangeP4(v, addr+7, pIdx->zName, P4_TRANSIENT);
91524 addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
91525 sqlite3VdbeChangeP2(v, addr, -mxErr);
91526 sqlite3VdbeJumpHere(v, addr+1);
91527 sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
91528 }else
91529 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
91531 #ifndef SQLITE_OMIT_UTF16
91533 ** PRAGMA encoding
91534 ** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
91536 ** In its first form, this pragma returns the encoding of the main
91537 ** database. If the database is not initialized, it is initialized now.
91539 ** The second form of this pragma is a no-op if the main database file
91540 ** has not already been initialized. In this case it sets the default
91541 ** encoding that will be used for the main database file if a new file
91542 ** is created. If an existing main database file is opened, then the
91543 ** default text encoding for the existing database is used.
91545 ** In all cases new databases created using the ATTACH command are
91546 ** created to use the same default text encoding as the main database. If
91547 ** the main database has not been initialized and/or created when ATTACH
91548 ** is executed, this is done before the ATTACH operation.
91550 ** In the second form this pragma sets the text encoding to be used in
91551 ** new database files created using this database handle. It is only
91552 ** useful if invoked immediately after the main database i
91554 if( sqlite3StrICmp(zLeft, "encoding")==0 ){
91555 static const struct EncName {
91556 char *zName;
91557 u8 enc;
91558 } encnames[] = {
91559 { "UTF8", SQLITE_UTF8 },
91560 { "UTF-8", SQLITE_UTF8 }, /* Must be element [1] */
91561 { "UTF-16le", SQLITE_UTF16LE }, /* Must be element [2] */
91562 { "UTF-16be", SQLITE_UTF16BE }, /* Must be element [3] */
91563 { "UTF16le", SQLITE_UTF16LE },
91564 { "UTF16be", SQLITE_UTF16BE },
91565 { "UTF-16", 0 }, /* SQLITE_UTF16NATIVE */
91566 { "UTF16", 0 }, /* SQLITE_UTF16NATIVE */
91567 { 0, 0 }
91569 const struct EncName *pEnc;
91570 if( !zRight ){ /* "PRAGMA encoding" */
91571 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
91572 sqlite3VdbeSetNumCols(v, 1);
91573 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
91574 sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
91575 assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
91576 assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
91577 assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
91578 sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
91579 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
91580 }else{ /* "PRAGMA encoding = XXX" */
91581 /* Only change the value of sqlite.enc if the database handle is not
91582 ** initialized. If the main database exists, the new sqlite.enc value
91583 ** will be overwritten when the schema is next loaded. If it does not
91584 ** already exists, it will be created to use the new encoding value.
91586 if(
91587 !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
91588 DbHasProperty(db, 0, DB_Empty)
91590 for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
91591 if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
91592 ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
91593 break;
91596 if( !pEnc->zName ){
91597 sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
91601 }else
91602 #endif /* SQLITE_OMIT_UTF16 */
91604 #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
91606 ** PRAGMA [database.]schema_version
91607 ** PRAGMA [database.]schema_version = <integer>
91609 ** PRAGMA [database.]user_version
91610 ** PRAGMA [database.]user_version = <integer>
91612 ** The pragma's schema_version and user_version are used to set or get
91613 ** the value of the schema-version and user-version, respectively. Both
91614 ** the schema-version and the user-version are 32-bit signed integers
91615 ** stored in the database header.
91617 ** The schema-cookie is usually only manipulated internally by SQLite. It
91618 ** is incremented by SQLite whenever the database schema is modified (by
91619 ** creating or dropping a table or index). The schema version is used by
91620 ** SQLite each time a query is executed to ensure that the internal cache
91621 ** of the schema used when compiling the SQL query matches the schema of
91622 ** the database against which the compiled query is actually executed.
91623 ** Subverting this mechanism by using "PRAGMA schema_version" to modify
91624 ** the schema-version is potentially dangerous and may lead to program
91625 ** crashes or database corruption. Use with caution!
91627 ** The user-version is not used internally by SQLite. It may be used by
91628 ** applications for any purpose.
91630 if( sqlite3StrICmp(zLeft, "schema_version")==0
91631 || sqlite3StrICmp(zLeft, "user_version")==0
91632 || sqlite3StrICmp(zLeft, "freelist_count")==0
91634 int iCookie; /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */
91635 sqlite3VdbeUsesBtree(v, iDb);
91636 switch( zLeft[0] ){
91637 case 'f': case 'F':
91638 iCookie = BTREE_FREE_PAGE_COUNT;
91639 break;
91640 case 's': case 'S':
91641 iCookie = BTREE_SCHEMA_VERSION;
91642 break;
91643 default:
91644 iCookie = BTREE_USER_VERSION;
91645 break;
91648 if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){
91649 /* Write the specified cookie value */
91650 static const VdbeOpList setCookie[] = {
91651 { OP_Transaction, 0, 1, 0}, /* 0 */
91652 { OP_Integer, 0, 1, 0}, /* 1 */
91653 { OP_SetCookie, 0, 0, 1}, /* 2 */
91655 int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
91656 sqlite3VdbeChangeP1(v, addr, iDb);
91657 sqlite3VdbeChangeP1(v, addr+1, sqlite3Atoi(zRight));
91658 sqlite3VdbeChangeP1(v, addr+2, iDb);
91659 sqlite3VdbeChangeP2(v, addr+2, iCookie);
91660 }else{
91661 /* Read the specified cookie value */
91662 static const VdbeOpList readCookie[] = {
91663 { OP_Transaction, 0, 0, 0}, /* 0 */
91664 { OP_ReadCookie, 0, 1, 0}, /* 1 */
91665 { OP_ResultRow, 1, 1, 0}
91667 int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
91668 sqlite3VdbeChangeP1(v, addr, iDb);
91669 sqlite3VdbeChangeP1(v, addr+1, iDb);
91670 sqlite3VdbeChangeP3(v, addr+1, iCookie);
91671 sqlite3VdbeSetNumCols(v, 1);
91672 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
91674 }else
91675 #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
91677 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
91679 ** PRAGMA compile_options
91681 ** Return the names of all compile-time options used in this build,
91682 ** one option per row.
91684 if( sqlite3StrICmp(zLeft, "compile_options")==0 ){
91685 int i = 0;
91686 const char *zOpt;
91687 sqlite3VdbeSetNumCols(v, 1);
91688 pParse->nMem = 1;
91689 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "compile_option", SQLITE_STATIC);
91690 while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
91691 sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zOpt, 0);
91692 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
91694 }else
91695 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
91697 #ifndef SQLITE_OMIT_WAL
91699 ** PRAGMA [database.]wal_checkpoint = passive|full|restart
91701 ** Checkpoint the database.
91703 if( sqlite3StrICmp(zLeft, "wal_checkpoint")==0 ){
91704 int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
91705 int eMode = SQLITE_CHECKPOINT_PASSIVE;
91706 if( zRight ){
91707 if( sqlite3StrICmp(zRight, "full")==0 ){
91708 eMode = SQLITE_CHECKPOINT_FULL;
91709 }else if( sqlite3StrICmp(zRight, "restart")==0 ){
91710 eMode = SQLITE_CHECKPOINT_RESTART;
91713 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
91714 sqlite3VdbeSetNumCols(v, 3);
91715 pParse->nMem = 3;
91716 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "busy", SQLITE_STATIC);
91717 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "log", SQLITE_STATIC);
91718 sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "checkpointed", SQLITE_STATIC);
91720 sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
91721 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
91722 }else
91725 ** PRAGMA wal_autocheckpoint
91726 ** PRAGMA wal_autocheckpoint = N
91728 ** Configure a database connection to automatically checkpoint a database
91729 ** after accumulating N frames in the log. Or query for the current value
91730 ** of N.
91732 if( sqlite3StrICmp(zLeft, "wal_autocheckpoint")==0 ){
91733 if( zRight ){
91734 sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
91736 returnSingleInt(pParse, "wal_autocheckpoint",
91737 db->xWalCallback==sqlite3WalDefaultHook ?
91738 SQLITE_PTR_TO_INT(db->pWalArg) : 0);
91739 }else
91740 #endif
91742 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
91744 ** Report the current state of file logs for all databases
91746 if( sqlite3StrICmp(zLeft, "lock_status")==0 ){
91747 static const char *const azLockName[] = {
91748 "unlocked", "shared", "reserved", "pending", "exclusive"
91750 int i;
91751 sqlite3VdbeSetNumCols(v, 2);
91752 pParse->nMem = 2;
91753 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
91754 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
91755 for(i=0; i<db->nDb; i++){
91756 Btree *pBt;
91757 Pager *pPager;
91758 const char *zState = "unknown";
91759 int j;
91760 if( db->aDb[i].zName==0 ) continue;
91761 sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
91762 pBt = db->aDb[i].pBt;
91763 if( pBt==0 || (pPager = sqlite3BtreePager(pBt))==0 ){
91764 zState = "closed";
91765 }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0,
91766 SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
91767 zState = azLockName[j];
91769 sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
91770 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
91773 }else
91774 #endif
91776 #ifdef SQLITE_HAS_CODEC
91777 if( sqlite3StrICmp(zLeft, "key")==0 && zRight ){
91778 sqlite3_key(db, zRight, sqlite3Strlen30(zRight));
91779 }else
91780 if( sqlite3StrICmp(zLeft, "rekey")==0 && zRight ){
91781 sqlite3_rekey(db, zRight, sqlite3Strlen30(zRight));
91782 }else
91783 if( zRight && (sqlite3StrICmp(zLeft, "hexkey")==0 ||
91784 sqlite3StrICmp(zLeft, "hexrekey")==0) ){
91785 int i, h1, h2;
91786 char zKey[40];
91787 for(i=0; (h1 = zRight[i])!=0 && (h2 = zRight[i+1])!=0; i+=2){
91788 h1 += 9*(1&(h1>>6));
91789 h2 += 9*(1&(h2>>6));
91790 zKey[i/2] = (h2 & 0x0f) | ((h1 & 0xf)<<4);
91792 if( (zLeft[3] & 0xf)==0xb ){
91793 sqlite3_key(db, zKey, i/2);
91794 }else{
91795 sqlite3_rekey(db, zKey, i/2);
91797 }else
91798 #endif
91799 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
91800 if( sqlite3StrICmp(zLeft, "activate_extensions")==0 ){
91801 #ifdef SQLITE_HAS_CODEC
91802 if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
91803 sqlite3_activate_see(&zRight[4]);
91805 #endif
91806 #ifdef SQLITE_ENABLE_CEROD
91807 if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
91808 sqlite3_activate_cerod(&zRight[6]);
91810 #endif
91811 }else
91812 #endif
91815 {/* Empty ELSE clause */}
91818 ** Reset the safety level, in case the fullfsync flag or synchronous
91819 ** setting changed.
91821 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
91822 if( db->autoCommit ){
91823 sqlite3BtreeSetSafetyLevel(pDb->pBt, pDb->safety_level,
91824 (db->flags&SQLITE_FullFSync)!=0,
91825 (db->flags&SQLITE_CkptFullFSync)!=0);
91827 #endif
91828 pragma_out:
91829 sqlite3DbFree(db, zLeft);
91830 sqlite3DbFree(db, zRight);
91833 #endif /* SQLITE_OMIT_PRAGMA */
91835 /************** End of pragma.c **********************************************/
91836 /************** Begin file prepare.c *****************************************/
91838 ** 2005 May 25
91840 ** The author disclaims copyright to this source code. In place of
91841 ** a legal notice, here is a blessing:
91843 ** May you do good and not evil.
91844 ** May you find forgiveness for yourself and forgive others.
91845 ** May you share freely, never taking more than you give.
91847 *************************************************************************
91848 ** This file contains the implementation of the sqlite3_prepare()
91849 ** interface, and routines that contribute to loading the database schema
91850 ** from disk.
91854 ** Fill the InitData structure with an error message that indicates
91855 ** that the database is corrupt.
91857 static void corruptSchema(
91858 InitData *pData, /* Initialization context */
91859 const char *zObj, /* Object being parsed at the point of error */
91860 const char *zExtra /* Error information */
91862 sqlite3 *db = pData->db;
91863 if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
91864 if( zObj==0 ) zObj = "?";
91865 sqlite3SetString(pData->pzErrMsg, db,
91866 "malformed database schema (%s)", zObj);
91867 if( zExtra ){
91868 *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg,
91869 "%s - %s", *pData->pzErrMsg, zExtra);
91872 pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT_BKPT;
91876 ** This is the callback routine for the code that initializes the
91877 ** database. See sqlite3Init() below for additional information.
91878 ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
91880 ** Each callback contains the following information:
91882 ** argv[0] = name of thing being created
91883 ** argv[1] = root page number for table or index. 0 for trigger or view.
91884 ** argv[2] = SQL text for the CREATE statement.
91887 SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
91888 InitData *pData = (InitData*)pInit;
91889 sqlite3 *db = pData->db;
91890 int iDb = pData->iDb;
91892 assert( argc==3 );
91893 UNUSED_PARAMETER2(NotUsed, argc);
91894 assert( sqlite3_mutex_held(db->mutex) );
91895 DbClearProperty(db, iDb, DB_Empty);
91896 if( db->mallocFailed ){
91897 corruptSchema(pData, argv[0], 0);
91898 return 1;
91901 assert( iDb>=0 && iDb<db->nDb );
91902 if( argv==0 ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */
91903 if( argv[1]==0 ){
91904 corruptSchema(pData, argv[0], 0);
91905 }else if( argv[2] && argv[2][0] ){
91906 /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
91907 ** But because db->init.busy is set to 1, no VDBE code is generated
91908 ** or executed. All the parser does is build the internal data
91909 ** structures that describe the table, index, or view.
91911 int rc;
91912 sqlite3_stmt *pStmt;
91913 TESTONLY(int rcp); /* Return code from sqlite3_prepare() */
91915 assert( db->init.busy );
91916 db->init.iDb = iDb;
91917 db->init.newTnum = sqlite3Atoi(argv[1]);
91918 db->init.orphanTrigger = 0;
91919 TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
91920 rc = db->errCode;
91921 assert( (rc&0xFF)==(rcp&0xFF) );
91922 db->init.iDb = 0;
91923 if( SQLITE_OK!=rc ){
91924 if( db->init.orphanTrigger ){
91925 assert( iDb==1 );
91926 }else{
91927 pData->rc = rc;
91928 if( rc==SQLITE_NOMEM ){
91929 db->mallocFailed = 1;
91930 }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
91931 corruptSchema(pData, argv[0], sqlite3_errmsg(db));
91935 sqlite3_finalize(pStmt);
91936 }else if( argv[0]==0 ){
91937 corruptSchema(pData, 0, 0);
91938 }else{
91939 /* If the SQL column is blank it means this is an index that
91940 ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
91941 ** constraint for a CREATE TABLE. The index should have already
91942 ** been created when we processed the CREATE TABLE. All we have
91943 ** to do here is record the root page number for that index.
91945 Index *pIndex;
91946 pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
91947 if( pIndex==0 ){
91948 /* This can occur if there exists an index on a TEMP table which
91949 ** has the same name as another index on a permanent index. Since
91950 ** the permanent table is hidden by the TEMP table, we can also
91951 ** safely ignore the index on the permanent table.
91953 /* Do Nothing */;
91954 }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
91955 corruptSchema(pData, argv[0], "invalid rootpage");
91958 return 0;
91962 ** Attempt to read the database schema and initialize internal
91963 ** data structures for a single database file. The index of the
91964 ** database file is given by iDb. iDb==0 is used for the main
91965 ** database. iDb==1 should never be used. iDb>=2 is used for
91966 ** auxiliary databases. Return one of the SQLITE_ error codes to
91967 ** indicate success or failure.
91969 static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
91970 int rc;
91971 int i;
91972 int size;
91973 Table *pTab;
91974 Db *pDb;
91975 char const *azArg[4];
91976 int meta[5];
91977 InitData initData;
91978 char const *zMasterSchema;
91979 char const *zMasterName;
91980 int openedTransaction = 0;
91983 ** The master database table has a structure like this
91985 static const char master_schema[] =
91986 "CREATE TABLE sqlite_master(\n"
91987 " type text,\n"
91988 " name text,\n"
91989 " tbl_name text,\n"
91990 " rootpage integer,\n"
91991 " sql text\n"
91994 #ifndef SQLITE_OMIT_TEMPDB
91995 static const char temp_master_schema[] =
91996 "CREATE TEMP TABLE sqlite_temp_master(\n"
91997 " type text,\n"
91998 " name text,\n"
91999 " tbl_name text,\n"
92000 " rootpage integer,\n"
92001 " sql text\n"
92004 #else
92005 #define temp_master_schema 0
92006 #endif
92008 assert( iDb>=0 && iDb<db->nDb );
92009 assert( db->aDb[iDb].pSchema );
92010 assert( sqlite3_mutex_held(db->mutex) );
92011 assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
92013 /* zMasterSchema and zInitScript are set to point at the master schema
92014 ** and initialisation script appropriate for the database being
92015 ** initialised. zMasterName is the name of the master table.
92017 if( !OMIT_TEMPDB && iDb==1 ){
92018 zMasterSchema = temp_master_schema;
92019 }else{
92020 zMasterSchema = master_schema;
92022 zMasterName = SCHEMA_TABLE(iDb);
92024 /* Construct the schema tables. */
92025 azArg[0] = zMasterName;
92026 azArg[1] = "1";
92027 azArg[2] = zMasterSchema;
92028 azArg[3] = 0;
92029 initData.db = db;
92030 initData.iDb = iDb;
92031 initData.rc = SQLITE_OK;
92032 initData.pzErrMsg = pzErrMsg;
92033 sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
92034 if( initData.rc ){
92035 rc = initData.rc;
92036 goto error_out;
92038 pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
92039 if( ALWAYS(pTab) ){
92040 pTab->tabFlags |= TF_Readonly;
92043 /* Create a cursor to hold the database open
92045 pDb = &db->aDb[iDb];
92046 if( pDb->pBt==0 ){
92047 if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
92048 DbSetProperty(db, 1, DB_SchemaLoaded);
92050 return SQLITE_OK;
92053 /* If there is not already a read-only (or read-write) transaction opened
92054 ** on the b-tree database, open one now. If a transaction is opened, it
92055 ** will be closed before this function returns. */
92056 sqlite3BtreeEnter(pDb->pBt);
92057 if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
92058 rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
92059 if( rc!=SQLITE_OK ){
92060 sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
92061 goto initone_error_out;
92063 openedTransaction = 1;
92066 /* Get the database meta information.
92068 ** Meta values are as follows:
92069 ** meta[0] Schema cookie. Changes with each schema change.
92070 ** meta[1] File format of schema layer.
92071 ** meta[2] Size of the page cache.
92072 ** meta[3] Largest rootpage (auto/incr_vacuum mode)
92073 ** meta[4] Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
92074 ** meta[5] User version
92075 ** meta[6] Incremental vacuum mode
92076 ** meta[7] unused
92077 ** meta[8] unused
92078 ** meta[9] unused
92080 ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
92081 ** the possible values of meta[4].
92083 for(i=0; i<ArraySize(meta); i++){
92084 sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
92086 pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
92088 /* If opening a non-empty database, check the text encoding. For the
92089 ** main database, set sqlite3.enc to the encoding of the main database.
92090 ** For an attached db, it is an error if the encoding is not the same
92091 ** as sqlite3.enc.
92093 if( meta[BTREE_TEXT_ENCODING-1] ){ /* text encoding */
92094 if( iDb==0 ){
92095 u8 encoding;
92096 /* If opening the main database, set ENC(db). */
92097 encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
92098 if( encoding==0 ) encoding = SQLITE_UTF8;
92099 ENC(db) = encoding;
92100 db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
92101 }else{
92102 /* If opening an attached database, the encoding much match ENC(db) */
92103 if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
92104 sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
92105 " text encoding as main database");
92106 rc = SQLITE_ERROR;
92107 goto initone_error_out;
92110 }else{
92111 DbSetProperty(db, iDb, DB_Empty);
92113 pDb->pSchema->enc = ENC(db);
92115 if( pDb->pSchema->cache_size==0 ){
92116 size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
92117 if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
92118 pDb->pSchema->cache_size = size;
92119 sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
92123 ** file_format==1 Version 3.0.0.
92124 ** file_format==2 Version 3.1.3. // ALTER TABLE ADD COLUMN
92125 ** file_format==3 Version 3.1.4. // ditto but with non-NULL defaults
92126 ** file_format==4 Version 3.3.0. // DESC indices. Boolean constants
92128 pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
92129 if( pDb->pSchema->file_format==0 ){
92130 pDb->pSchema->file_format = 1;
92132 if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
92133 sqlite3SetString(pzErrMsg, db, "unsupported file format");
92134 rc = SQLITE_ERROR;
92135 goto initone_error_out;
92138 /* Ticket #2804: When we open a database in the newer file format,
92139 ** clear the legacy_file_format pragma flag so that a VACUUM will
92140 ** not downgrade the database and thus invalidate any descending
92141 ** indices that the user might have created.
92143 if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
92144 db->flags &= ~SQLITE_LegacyFileFmt;
92147 /* Read the schema information out of the schema tables
92149 assert( db->init.busy );
92151 char *zSql;
92152 zSql = sqlite3MPrintf(db,
92153 "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
92154 db->aDb[iDb].zName, zMasterName);
92155 #ifndef SQLITE_OMIT_AUTHORIZATION
92157 int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
92158 xAuth = db->xAuth;
92159 db->xAuth = 0;
92160 #endif
92161 rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
92162 #ifndef SQLITE_OMIT_AUTHORIZATION
92163 db->xAuth = xAuth;
92165 #endif
92166 if( rc==SQLITE_OK ) rc = initData.rc;
92167 sqlite3DbFree(db, zSql);
92168 #ifndef SQLITE_OMIT_ANALYZE
92169 if( rc==SQLITE_OK ){
92170 sqlite3AnalysisLoad(db, iDb);
92172 #endif
92174 if( db->mallocFailed ){
92175 rc = SQLITE_NOMEM;
92176 sqlite3ResetInternalSchema(db, -1);
92178 if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
92179 /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
92180 ** the schema loaded, even if errors occurred. In this situation the
92181 ** current sqlite3_prepare() operation will fail, but the following one
92182 ** will attempt to compile the supplied statement against whatever subset
92183 ** of the schema was loaded before the error occurred. The primary
92184 ** purpose of this is to allow access to the sqlite_master table
92185 ** even when its contents have been corrupted.
92187 DbSetProperty(db, iDb, DB_SchemaLoaded);
92188 rc = SQLITE_OK;
92191 /* Jump here for an error that occurs after successfully allocating
92192 ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
92193 ** before that point, jump to error_out.
92195 initone_error_out:
92196 if( openedTransaction ){
92197 sqlite3BtreeCommit(pDb->pBt);
92199 sqlite3BtreeLeave(pDb->pBt);
92201 error_out:
92202 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
92203 db->mallocFailed = 1;
92205 return rc;
92209 ** Initialize all database files - the main database file, the file
92210 ** used to store temporary tables, and any additional database files
92211 ** created using ATTACH statements. Return a success code. If an
92212 ** error occurs, write an error message into *pzErrMsg.
92214 ** After a database is initialized, the DB_SchemaLoaded bit is set
92215 ** bit is set in the flags field of the Db structure. If the database
92216 ** file was of zero-length, then the DB_Empty flag is also set.
92218 SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
92219 int i, rc;
92220 int commit_internal = !(db->flags&SQLITE_InternChanges);
92222 assert( sqlite3_mutex_held(db->mutex) );
92223 rc = SQLITE_OK;
92224 db->init.busy = 1;
92225 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
92226 if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
92227 rc = sqlite3InitOne(db, i, pzErrMsg);
92228 if( rc ){
92229 sqlite3ResetInternalSchema(db, i);
92233 /* Once all the other databases have been initialised, load the schema
92234 ** for the TEMP database. This is loaded last, as the TEMP database
92235 ** schema may contain references to objects in other databases.
92237 #ifndef SQLITE_OMIT_TEMPDB
92238 if( rc==SQLITE_OK && ALWAYS(db->nDb>1)
92239 && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
92240 rc = sqlite3InitOne(db, 1, pzErrMsg);
92241 if( rc ){
92242 sqlite3ResetInternalSchema(db, 1);
92245 #endif
92247 db->init.busy = 0;
92248 if( rc==SQLITE_OK && commit_internal ){
92249 sqlite3CommitInternalChanges(db);
92252 return rc;
92256 ** This routine is a no-op if the database schema is already initialised.
92257 ** Otherwise, the schema is loaded. An error code is returned.
92259 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
92260 int rc = SQLITE_OK;
92261 sqlite3 *db = pParse->db;
92262 assert( sqlite3_mutex_held(db->mutex) );
92263 if( !db->init.busy ){
92264 rc = sqlite3Init(db, &pParse->zErrMsg);
92266 if( rc!=SQLITE_OK ){
92267 pParse->rc = rc;
92268 pParse->nErr++;
92270 return rc;
92275 ** Check schema cookies in all databases. If any cookie is out
92276 ** of date set pParse->rc to SQLITE_SCHEMA. If all schema cookies
92277 ** make no changes to pParse->rc.
92279 static void schemaIsValid(Parse *pParse){
92280 sqlite3 *db = pParse->db;
92281 int iDb;
92282 int rc;
92283 int cookie;
92285 assert( pParse->checkSchema );
92286 assert( sqlite3_mutex_held(db->mutex) );
92287 for(iDb=0; iDb<db->nDb; iDb++){
92288 int openedTransaction = 0; /* True if a transaction is opened */
92289 Btree *pBt = db->aDb[iDb].pBt; /* Btree database to read cookie from */
92290 if( pBt==0 ) continue;
92292 /* If there is not already a read-only (or read-write) transaction opened
92293 ** on the b-tree database, open one now. If a transaction is opened, it
92294 ** will be closed immediately after reading the meta-value. */
92295 if( !sqlite3BtreeIsInReadTrans(pBt) ){
92296 rc = sqlite3BtreeBeginTrans(pBt, 0);
92297 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
92298 db->mallocFailed = 1;
92300 if( rc!=SQLITE_OK ) return;
92301 openedTransaction = 1;
92304 /* Read the schema cookie from the database. If it does not match the
92305 ** value stored as part of the in-memory schema representation,
92306 ** set Parse.rc to SQLITE_SCHEMA. */
92307 sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
92308 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
92309 if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
92310 sqlite3ResetInternalSchema(db, iDb);
92311 pParse->rc = SQLITE_SCHEMA;
92314 /* Close the transaction, if one was opened. */
92315 if( openedTransaction ){
92316 sqlite3BtreeCommit(pBt);
92322 ** Convert a schema pointer into the iDb index that indicates
92323 ** which database file in db->aDb[] the schema refers to.
92325 ** If the same database is attached more than once, the first
92326 ** attached database is returned.
92328 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
92329 int i = -1000000;
92331 /* If pSchema is NULL, then return -1000000. This happens when code in
92332 ** expr.c is trying to resolve a reference to a transient table (i.e. one
92333 ** created by a sub-select). In this case the return value of this
92334 ** function should never be used.
92336 ** We return -1000000 instead of the more usual -1 simply because using
92337 ** -1000000 as the incorrect index into db->aDb[] is much
92338 ** more likely to cause a segfault than -1 (of course there are assert()
92339 ** statements too, but it never hurts to play the odds).
92341 assert( sqlite3_mutex_held(db->mutex) );
92342 if( pSchema ){
92343 for(i=0; ALWAYS(i<db->nDb); i++){
92344 if( db->aDb[i].pSchema==pSchema ){
92345 break;
92348 assert( i>=0 && i<db->nDb );
92350 return i;
92354 ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
92356 static int sqlite3Prepare(
92357 sqlite3 *db, /* Database handle. */
92358 const char *zSql, /* UTF-8 encoded SQL statement. */
92359 int nBytes, /* Length of zSql in bytes. */
92360 int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
92361 Vdbe *pReprepare, /* VM being reprepared */
92362 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
92363 const char **pzTail /* OUT: End of parsed string */
92365 Parse *pParse; /* Parsing context */
92366 char *zErrMsg = 0; /* Error message */
92367 int rc = SQLITE_OK; /* Result code */
92368 int i; /* Loop counter */
92370 /* Allocate the parsing context */
92371 pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
92372 if( pParse==0 ){
92373 rc = SQLITE_NOMEM;
92374 goto end_prepare;
92376 pParse->pReprepare = pReprepare;
92377 assert( ppStmt && *ppStmt==0 );
92378 assert( !db->mallocFailed );
92379 assert( sqlite3_mutex_held(db->mutex) );
92381 /* Check to verify that it is possible to get a read lock on all
92382 ** database schemas. The inability to get a read lock indicates that
92383 ** some other database connection is holding a write-lock, which in
92384 ** turn means that the other connection has made uncommitted changes
92385 ** to the schema.
92387 ** Were we to proceed and prepare the statement against the uncommitted
92388 ** schema changes and if those schema changes are subsequently rolled
92389 ** back and different changes are made in their place, then when this
92390 ** prepared statement goes to run the schema cookie would fail to detect
92391 ** the schema change. Disaster would follow.
92393 ** This thread is currently holding mutexes on all Btrees (because
92394 ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
92395 ** is not possible for another thread to start a new schema change
92396 ** while this routine is running. Hence, we do not need to hold
92397 ** locks on the schema, we just need to make sure nobody else is
92398 ** holding them.
92400 ** Note that setting READ_UNCOMMITTED overrides most lock detection,
92401 ** but it does *not* override schema lock detection, so this all still
92402 ** works even if READ_UNCOMMITTED is set.
92404 for(i=0; i<db->nDb; i++) {
92405 Btree *pBt = db->aDb[i].pBt;
92406 if( pBt ){
92407 assert( sqlite3BtreeHoldsMutex(pBt) );
92408 rc = sqlite3BtreeSchemaLocked(pBt);
92409 if( rc ){
92410 const char *zDb = db->aDb[i].zName;
92411 sqlite3Error(db, rc, "database schema is locked: %s", zDb);
92412 testcase( db->flags & SQLITE_ReadUncommitted );
92413 goto end_prepare;
92418 sqlite3VtabUnlockList(db);
92420 pParse->db = db;
92421 pParse->nQueryLoop = (double)1;
92422 if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
92423 char *zSqlCopy;
92424 int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
92425 testcase( nBytes==mxLen );
92426 testcase( nBytes==mxLen+1 );
92427 if( nBytes>mxLen ){
92428 sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
92429 rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
92430 goto end_prepare;
92432 zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
92433 if( zSqlCopy ){
92434 sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
92435 sqlite3DbFree(db, zSqlCopy);
92436 pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
92437 }else{
92438 pParse->zTail = &zSql[nBytes];
92440 }else{
92441 sqlite3RunParser(pParse, zSql, &zErrMsg);
92443 assert( 1==(int)pParse->nQueryLoop );
92445 if( db->mallocFailed ){
92446 pParse->rc = SQLITE_NOMEM;
92448 if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
92449 if( pParse->checkSchema ){
92450 schemaIsValid(pParse);
92452 if( db->mallocFailed ){
92453 pParse->rc = SQLITE_NOMEM;
92455 if( pzTail ){
92456 *pzTail = pParse->zTail;
92458 rc = pParse->rc;
92460 #ifndef SQLITE_OMIT_EXPLAIN
92461 if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
92462 static const char * const azColName[] = {
92463 "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
92464 "selectid", "order", "from", "detail"
92466 int iFirst, mx;
92467 if( pParse->explain==2 ){
92468 sqlite3VdbeSetNumCols(pParse->pVdbe, 4);
92469 iFirst = 8;
92470 mx = 12;
92471 }else{
92472 sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
92473 iFirst = 0;
92474 mx = 8;
92476 for(i=iFirst; i<mx; i++){
92477 sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
92478 azColName[i], SQLITE_STATIC);
92481 #endif
92483 assert( db->init.busy==0 || saveSqlFlag==0 );
92484 if( db->init.busy==0 ){
92485 Vdbe *pVdbe = pParse->pVdbe;
92486 sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
92488 if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
92489 sqlite3VdbeFinalize(pParse->pVdbe);
92490 assert(!(*ppStmt));
92491 }else{
92492 *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
92495 if( zErrMsg ){
92496 sqlite3Error(db, rc, "%s", zErrMsg);
92497 sqlite3DbFree(db, zErrMsg);
92498 }else{
92499 sqlite3Error(db, rc, 0);
92502 /* Delete any TriggerPrg structures allocated while parsing this statement. */
92503 while( pParse->pTriggerPrg ){
92504 TriggerPrg *pT = pParse->pTriggerPrg;
92505 pParse->pTriggerPrg = pT->pNext;
92506 sqlite3DbFree(db, pT);
92509 end_prepare:
92511 sqlite3StackFree(db, pParse);
92512 rc = sqlite3ApiExit(db, rc);
92513 assert( (rc&db->errMask)==rc );
92514 return rc;
92516 static int sqlite3LockAndPrepare(
92517 sqlite3 *db, /* Database handle. */
92518 const char *zSql, /* UTF-8 encoded SQL statement. */
92519 int nBytes, /* Length of zSql in bytes. */
92520 int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
92521 Vdbe *pOld, /* VM being reprepared */
92522 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
92523 const char **pzTail /* OUT: End of parsed string */
92525 int rc;
92526 assert( ppStmt!=0 );
92527 *ppStmt = 0;
92528 if( !sqlite3SafetyCheckOk(db) ){
92529 return SQLITE_MISUSE_BKPT;
92531 sqlite3_mutex_enter(db->mutex);
92532 sqlite3BtreeEnterAll(db);
92533 rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
92534 if( rc==SQLITE_SCHEMA ){
92535 sqlite3_finalize(*ppStmt);
92536 rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
92538 sqlite3BtreeLeaveAll(db);
92539 sqlite3_mutex_leave(db->mutex);
92540 return rc;
92544 ** Rerun the compilation of a statement after a schema change.
92546 ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
92547 ** if the statement cannot be recompiled because another connection has
92548 ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
92549 ** occurs, return SQLITE_SCHEMA.
92551 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
92552 int rc;
92553 sqlite3_stmt *pNew;
92554 const char *zSql;
92555 sqlite3 *db;
92557 assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
92558 zSql = sqlite3_sql((sqlite3_stmt *)p);
92559 assert( zSql!=0 ); /* Reprepare only called for prepare_v2() statements */
92560 db = sqlite3VdbeDb(p);
92561 assert( sqlite3_mutex_held(db->mutex) );
92562 rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
92563 if( rc ){
92564 if( rc==SQLITE_NOMEM ){
92565 db->mallocFailed = 1;
92567 assert( pNew==0 );
92568 return rc;
92569 }else{
92570 assert( pNew!=0 );
92572 sqlite3VdbeSwap((Vdbe*)pNew, p);
92573 sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
92574 sqlite3VdbeResetStepResult((Vdbe*)pNew);
92575 sqlite3VdbeFinalize((Vdbe*)pNew);
92576 return SQLITE_OK;
92581 ** Two versions of the official API. Legacy and new use. In the legacy
92582 ** version, the original SQL text is not saved in the prepared statement
92583 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
92584 ** sqlite3_step(). In the new version, the original SQL text is retained
92585 ** and the statement is automatically recompiled if an schema change
92586 ** occurs.
92588 SQLITE_API int sqlite3_prepare(
92589 sqlite3 *db, /* Database handle. */
92590 const char *zSql, /* UTF-8 encoded SQL statement. */
92591 int nBytes, /* Length of zSql in bytes. */
92592 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
92593 const char **pzTail /* OUT: End of parsed string */
92595 int rc;
92596 rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
92597 assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
92598 return rc;
92600 SQLITE_API int sqlite3_prepare_v2(
92601 sqlite3 *db, /* Database handle. */
92602 const char *zSql, /* UTF-8 encoded SQL statement. */
92603 int nBytes, /* Length of zSql in bytes. */
92604 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
92605 const char **pzTail /* OUT: End of parsed string */
92607 int rc;
92608 rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
92609 assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
92610 return rc;
92614 #ifndef SQLITE_OMIT_UTF16
92616 ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
92618 static int sqlite3Prepare16(
92619 sqlite3 *db, /* Database handle. */
92620 const void *zSql, /* UTF-16 encoded SQL statement. */
92621 int nBytes, /* Length of zSql in bytes. */
92622 int saveSqlFlag, /* True to save SQL text into the sqlite3_stmt */
92623 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
92624 const void **pzTail /* OUT: End of parsed string */
92626 /* This function currently works by first transforming the UTF-16
92627 ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
92628 ** tricky bit is figuring out the pointer to return in *pzTail.
92630 char *zSql8;
92631 const char *zTail8 = 0;
92632 int rc = SQLITE_OK;
92634 assert( ppStmt );
92635 *ppStmt = 0;
92636 if( !sqlite3SafetyCheckOk(db) ){
92637 return SQLITE_MISUSE_BKPT;
92639 sqlite3_mutex_enter(db->mutex);
92640 zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
92641 if( zSql8 ){
92642 rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
92645 if( zTail8 && pzTail ){
92646 /* If sqlite3_prepare returns a tail pointer, we calculate the
92647 ** equivalent pointer into the UTF-16 string by counting the unicode
92648 ** characters between zSql8 and zTail8, and then returning a pointer
92649 ** the same number of characters into the UTF-16 string.
92651 int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
92652 *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
92654 sqlite3DbFree(db, zSql8);
92655 rc = sqlite3ApiExit(db, rc);
92656 sqlite3_mutex_leave(db->mutex);
92657 return rc;
92661 ** Two versions of the official API. Legacy and new use. In the legacy
92662 ** version, the original SQL text is not saved in the prepared statement
92663 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
92664 ** sqlite3_step(). In the new version, the original SQL text is retained
92665 ** and the statement is automatically recompiled if an schema change
92666 ** occurs.
92668 SQLITE_API int sqlite3_prepare16(
92669 sqlite3 *db, /* Database handle. */
92670 const void *zSql, /* UTF-16 encoded SQL statement. */
92671 int nBytes, /* Length of zSql in bytes. */
92672 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
92673 const void **pzTail /* OUT: End of parsed string */
92675 int rc;
92676 rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
92677 assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
92678 return rc;
92680 SQLITE_API int sqlite3_prepare16_v2(
92681 sqlite3 *db, /* Database handle. */
92682 const void *zSql, /* UTF-16 encoded SQL statement. */
92683 int nBytes, /* Length of zSql in bytes. */
92684 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
92685 const void **pzTail /* OUT: End of parsed string */
92687 int rc;
92688 rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
92689 assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
92690 return rc;
92693 #endif /* SQLITE_OMIT_UTF16 */
92695 /************** End of prepare.c *********************************************/
92696 /************** Begin file select.c ******************************************/
92698 ** 2001 September 15
92700 ** The author disclaims copyright to this source code. In place of
92701 ** a legal notice, here is a blessing:
92703 ** May you do good and not evil.
92704 ** May you find forgiveness for yourself and forgive others.
92705 ** May you share freely, never taking more than you give.
92707 *************************************************************************
92708 ** This file contains C code routines that are called by the parser
92709 ** to handle SELECT statements in SQLite.
92714 ** Delete all the content of a Select structure but do not deallocate
92715 ** the select structure itself.
92717 static void clearSelect(sqlite3 *db, Select *p){
92718 sqlite3ExprListDelete(db, p->pEList);
92719 sqlite3SrcListDelete(db, p->pSrc);
92720 sqlite3ExprDelete(db, p->pWhere);
92721 sqlite3ExprListDelete(db, p->pGroupBy);
92722 sqlite3ExprDelete(db, p->pHaving);
92723 sqlite3ExprListDelete(db, p->pOrderBy);
92724 sqlite3SelectDelete(db, p->pPrior);
92725 sqlite3ExprDelete(db, p->pLimit);
92726 sqlite3ExprDelete(db, p->pOffset);
92730 ** Initialize a SelectDest structure.
92732 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
92733 pDest->eDest = (u8)eDest;
92734 pDest->iParm = iParm;
92735 pDest->affinity = 0;
92736 pDest->iMem = 0;
92737 pDest->nMem = 0;
92742 ** Allocate a new Select structure and return a pointer to that
92743 ** structure.
92745 SQLITE_PRIVATE Select *sqlite3SelectNew(
92746 Parse *pParse, /* Parsing context */
92747 ExprList *pEList, /* which columns to include in the result */
92748 SrcList *pSrc, /* the FROM clause -- which tables to scan */
92749 Expr *pWhere, /* the WHERE clause */
92750 ExprList *pGroupBy, /* the GROUP BY clause */
92751 Expr *pHaving, /* the HAVING clause */
92752 ExprList *pOrderBy, /* the ORDER BY clause */
92753 int isDistinct, /* true if the DISTINCT keyword is present */
92754 Expr *pLimit, /* LIMIT value. NULL means not used */
92755 Expr *pOffset /* OFFSET value. NULL means no offset */
92757 Select *pNew;
92758 Select standin;
92759 sqlite3 *db = pParse->db;
92760 pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
92761 assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
92762 if( pNew==0 ){
92763 assert( db->mallocFailed );
92764 pNew = &standin;
92765 memset(pNew, 0, sizeof(*pNew));
92767 if( pEList==0 ){
92768 pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
92770 pNew->pEList = pEList;
92771 pNew->pSrc = pSrc;
92772 pNew->pWhere = pWhere;
92773 pNew->pGroupBy = pGroupBy;
92774 pNew->pHaving = pHaving;
92775 pNew->pOrderBy = pOrderBy;
92776 pNew->selFlags = isDistinct ? SF_Distinct : 0;
92777 pNew->op = TK_SELECT;
92778 pNew->pLimit = pLimit;
92779 pNew->pOffset = pOffset;
92780 assert( pOffset==0 || pLimit!=0 );
92781 pNew->addrOpenEphm[0] = -1;
92782 pNew->addrOpenEphm[1] = -1;
92783 pNew->addrOpenEphm[2] = -1;
92784 if( db->mallocFailed ) {
92785 clearSelect(db, pNew);
92786 if( pNew!=&standin ) sqlite3DbFree(db, pNew);
92787 pNew = 0;
92788 }else{
92789 assert( pNew->pSrc!=0 || pParse->nErr>0 );
92791 assert( pNew!=&standin );
92792 return pNew;
92796 ** Delete the given Select structure and all of its substructures.
92798 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
92799 if( p ){
92800 clearSelect(db, p);
92801 sqlite3DbFree(db, p);
92806 ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
92807 ** type of join. Return an integer constant that expresses that type
92808 ** in terms of the following bit values:
92810 ** JT_INNER
92811 ** JT_CROSS
92812 ** JT_OUTER
92813 ** JT_NATURAL
92814 ** JT_LEFT
92815 ** JT_RIGHT
92817 ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
92819 ** If an illegal or unsupported join type is seen, then still return
92820 ** a join type, but put an error in the pParse structure.
92822 SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
92823 int jointype = 0;
92824 Token *apAll[3];
92825 Token *p;
92826 /* 0123456789 123456789 123456789 123 */
92827 static const char zKeyText[] = "naturaleftouterightfullinnercross";
92828 static const struct {
92829 u8 i; /* Beginning of keyword text in zKeyText[] */
92830 u8 nChar; /* Length of the keyword in characters */
92831 u8 code; /* Join type mask */
92832 } aKeyword[] = {
92833 /* natural */ { 0, 7, JT_NATURAL },
92834 /* left */ { 6, 4, JT_LEFT|JT_OUTER },
92835 /* outer */ { 10, 5, JT_OUTER },
92836 /* right */ { 14, 5, JT_RIGHT|JT_OUTER },
92837 /* full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
92838 /* inner */ { 23, 5, JT_INNER },
92839 /* cross */ { 28, 5, JT_INNER|JT_CROSS },
92841 int i, j;
92842 apAll[0] = pA;
92843 apAll[1] = pB;
92844 apAll[2] = pC;
92845 for(i=0; i<3 && apAll[i]; i++){
92846 p = apAll[i];
92847 for(j=0; j<ArraySize(aKeyword); j++){
92848 if( p->n==aKeyword[j].nChar
92849 && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
92850 jointype |= aKeyword[j].code;
92851 break;
92854 testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
92855 if( j>=ArraySize(aKeyword) ){
92856 jointype |= JT_ERROR;
92857 break;
92861 (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
92862 (jointype & JT_ERROR)!=0
92864 const char *zSp = " ";
92865 assert( pB!=0 );
92866 if( pC==0 ){ zSp++; }
92867 sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
92868 "%T %T%s%T", pA, pB, zSp, pC);
92869 jointype = JT_INNER;
92870 }else if( (jointype & JT_OUTER)!=0
92871 && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
92872 sqlite3ErrorMsg(pParse,
92873 "RIGHT and FULL OUTER JOINs are not currently supported");
92874 jointype = JT_INNER;
92876 return jointype;
92880 ** Return the index of a column in a table. Return -1 if the column
92881 ** is not contained in the table.
92883 static int columnIndex(Table *pTab, const char *zCol){
92884 int i;
92885 for(i=0; i<pTab->nCol; i++){
92886 if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
92888 return -1;
92892 ** Search the first N tables in pSrc, from left to right, looking for a
92893 ** table that has a column named zCol.
92895 ** When found, set *piTab and *piCol to the table index and column index
92896 ** of the matching column and return TRUE.
92898 ** If not found, return FALSE.
92900 static int tableAndColumnIndex(
92901 SrcList *pSrc, /* Array of tables to search */
92902 int N, /* Number of tables in pSrc->a[] to search */
92903 const char *zCol, /* Name of the column we are looking for */
92904 int *piTab, /* Write index of pSrc->a[] here */
92905 int *piCol /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
92907 int i; /* For looping over tables in pSrc */
92908 int iCol; /* Index of column matching zCol */
92910 assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */
92911 for(i=0; i<N; i++){
92912 iCol = columnIndex(pSrc->a[i].pTab, zCol);
92913 if( iCol>=0 ){
92914 if( piTab ){
92915 *piTab = i;
92916 *piCol = iCol;
92918 return 1;
92921 return 0;
92925 ** This function is used to add terms implied by JOIN syntax to the
92926 ** WHERE clause expression of a SELECT statement. The new term, which
92927 ** is ANDed with the existing WHERE clause, is of the form:
92929 ** (tab1.col1 = tab2.col2)
92931 ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
92932 ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
92933 ** column iColRight of tab2.
92935 static void addWhereTerm(
92936 Parse *pParse, /* Parsing context */
92937 SrcList *pSrc, /* List of tables in FROM clause */
92938 int iLeft, /* Index of first table to join in pSrc */
92939 int iColLeft, /* Index of column in first table */
92940 int iRight, /* Index of second table in pSrc */
92941 int iColRight, /* Index of column in second table */
92942 int isOuterJoin, /* True if this is an OUTER join */
92943 Expr **ppWhere /* IN/OUT: The WHERE clause to add to */
92945 sqlite3 *db = pParse->db;
92946 Expr *pE1;
92947 Expr *pE2;
92948 Expr *pEq;
92950 assert( iLeft<iRight );
92951 assert( pSrc->nSrc>iRight );
92952 assert( pSrc->a[iLeft].pTab );
92953 assert( pSrc->a[iRight].pTab );
92955 pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
92956 pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
92958 pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
92959 if( pEq && isOuterJoin ){
92960 ExprSetProperty(pEq, EP_FromJoin);
92961 assert( !ExprHasAnyProperty(pEq, EP_TokenOnly|EP_Reduced) );
92962 ExprSetIrreducible(pEq);
92963 pEq->iRightJoinTable = (i16)pE2->iTable;
92965 *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
92969 ** Set the EP_FromJoin property on all terms of the given expression.
92970 ** And set the Expr.iRightJoinTable to iTable for every term in the
92971 ** expression.
92973 ** The EP_FromJoin property is used on terms of an expression to tell
92974 ** the LEFT OUTER JOIN processing logic that this term is part of the
92975 ** join restriction specified in the ON or USING clause and not a part
92976 ** of the more general WHERE clause. These terms are moved over to the
92977 ** WHERE clause during join processing but we need to remember that they
92978 ** originated in the ON or USING clause.
92980 ** The Expr.iRightJoinTable tells the WHERE clause processing that the
92981 ** expression depends on table iRightJoinTable even if that table is not
92982 ** explicitly mentioned in the expression. That information is needed
92983 ** for cases like this:
92985 ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
92987 ** The where clause needs to defer the handling of the t1.x=5
92988 ** term until after the t2 loop of the join. In that way, a
92989 ** NULL t2 row will be inserted whenever t1.x!=5. If we do not
92990 ** defer the handling of t1.x=5, it will be processed immediately
92991 ** after the t1 loop and rows with t1.x!=5 will never appear in
92992 ** the output, which is incorrect.
92994 static void setJoinExpr(Expr *p, int iTable){
92995 while( p ){
92996 ExprSetProperty(p, EP_FromJoin);
92997 assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
92998 ExprSetIrreducible(p);
92999 p->iRightJoinTable = (i16)iTable;
93000 setJoinExpr(p->pLeft, iTable);
93001 p = p->pRight;
93006 ** This routine processes the join information for a SELECT statement.
93007 ** ON and USING clauses are converted into extra terms of the WHERE clause.
93008 ** NATURAL joins also create extra WHERE clause terms.
93010 ** The terms of a FROM clause are contained in the Select.pSrc structure.
93011 ** The left most table is the first entry in Select.pSrc. The right-most
93012 ** table is the last entry. The join operator is held in the entry to
93013 ** the left. Thus entry 0 contains the join operator for the join between
93014 ** entries 0 and 1. Any ON or USING clauses associated with the join are
93015 ** also attached to the left entry.
93017 ** This routine returns the number of errors encountered.
93019 static int sqliteProcessJoin(Parse *pParse, Select *p){
93020 SrcList *pSrc; /* All tables in the FROM clause */
93021 int i, j; /* Loop counters */
93022 struct SrcList_item *pLeft; /* Left table being joined */
93023 struct SrcList_item *pRight; /* Right table being joined */
93025 pSrc = p->pSrc;
93026 pLeft = &pSrc->a[0];
93027 pRight = &pLeft[1];
93028 for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
93029 Table *pLeftTab = pLeft->pTab;
93030 Table *pRightTab = pRight->pTab;
93031 int isOuter;
93033 if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
93034 isOuter = (pRight->jointype & JT_OUTER)!=0;
93036 /* When the NATURAL keyword is present, add WHERE clause terms for
93037 ** every column that the two tables have in common.
93039 if( pRight->jointype & JT_NATURAL ){
93040 if( pRight->pOn || pRight->pUsing ){
93041 sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
93042 "an ON or USING clause", 0);
93043 return 1;
93045 for(j=0; j<pRightTab->nCol; j++){
93046 char *zName; /* Name of column in the right table */
93047 int iLeft; /* Matching left table */
93048 int iLeftCol; /* Matching column in the left table */
93050 zName = pRightTab->aCol[j].zName;
93051 if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
93052 addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
93053 isOuter, &p->pWhere);
93058 /* Disallow both ON and USING clauses in the same join
93060 if( pRight->pOn && pRight->pUsing ){
93061 sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
93062 "clauses in the same join");
93063 return 1;
93066 /* Add the ON clause to the end of the WHERE clause, connected by
93067 ** an AND operator.
93069 if( pRight->pOn ){
93070 if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
93071 p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
93072 pRight->pOn = 0;
93075 /* Create extra terms on the WHERE clause for each column named
93076 ** in the USING clause. Example: If the two tables to be joined are
93077 ** A and B and the USING clause names X, Y, and Z, then add this
93078 ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
93079 ** Report an error if any column mentioned in the USING clause is
93080 ** not contained in both tables to be joined.
93082 if( pRight->pUsing ){
93083 IdList *pList = pRight->pUsing;
93084 for(j=0; j<pList->nId; j++){
93085 char *zName; /* Name of the term in the USING clause */
93086 int iLeft; /* Table on the left with matching column name */
93087 int iLeftCol; /* Column number of matching column on the left */
93088 int iRightCol; /* Column number of matching column on the right */
93090 zName = pList->a[j].zName;
93091 iRightCol = columnIndex(pRightTab, zName);
93092 if( iRightCol<0
93093 || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
93095 sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
93096 "not present in both tables", zName);
93097 return 1;
93099 addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
93100 isOuter, &p->pWhere);
93104 return 0;
93108 ** Insert code into "v" that will push the record on the top of the
93109 ** stack into the sorter.
93111 static void pushOntoSorter(
93112 Parse *pParse, /* Parser context */
93113 ExprList *pOrderBy, /* The ORDER BY clause */
93114 Select *pSelect, /* The whole SELECT statement */
93115 int regData /* Register holding data to be sorted */
93117 Vdbe *v = pParse->pVdbe;
93118 int nExpr = pOrderBy->nExpr;
93119 int regBase = sqlite3GetTempRange(pParse, nExpr+2);
93120 int regRecord = sqlite3GetTempReg(pParse);
93121 int op;
93122 sqlite3ExprCacheClear(pParse);
93123 sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
93124 sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
93125 sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
93126 sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
93127 if( pSelect->selFlags & SF_UseSorter ){
93128 op = OP_SorterInsert;
93129 }else{
93130 op = OP_IdxInsert;
93132 sqlite3VdbeAddOp2(v, op, pOrderBy->iECursor, regRecord);
93133 sqlite3ReleaseTempReg(pParse, regRecord);
93134 sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
93135 if( pSelect->iLimit ){
93136 int addr1, addr2;
93137 int iLimit;
93138 if( pSelect->iOffset ){
93139 iLimit = pSelect->iOffset+1;
93140 }else{
93141 iLimit = pSelect->iLimit;
93143 addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
93144 sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
93145 addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
93146 sqlite3VdbeJumpHere(v, addr1);
93147 sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
93148 sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
93149 sqlite3VdbeJumpHere(v, addr2);
93154 ** Add code to implement the OFFSET
93156 static void codeOffset(
93157 Vdbe *v, /* Generate code into this VM */
93158 Select *p, /* The SELECT statement being coded */
93159 int iContinue /* Jump here to skip the current record */
93161 if( p->iOffset && iContinue!=0 ){
93162 int addr;
93163 sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
93164 addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
93165 sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
93166 VdbeComment((v, "skip OFFSET records"));
93167 sqlite3VdbeJumpHere(v, addr);
93172 ** Add code that will check to make sure the N registers starting at iMem
93173 ** form a distinct entry. iTab is a sorting index that holds previously
93174 ** seen combinations of the N values. A new entry is made in iTab
93175 ** if the current N values are new.
93177 ** A jump to addrRepeat is made and the N+1 values are popped from the
93178 ** stack if the top N elements are not distinct.
93180 static void codeDistinct(
93181 Parse *pParse, /* Parsing and code generating context */
93182 int iTab, /* A sorting index used to test for distinctness */
93183 int addrRepeat, /* Jump to here if not distinct */
93184 int N, /* Number of elements */
93185 int iMem /* First element */
93187 Vdbe *v;
93188 int r1;
93190 v = pParse->pVdbe;
93191 r1 = sqlite3GetTempReg(pParse);
93192 sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N);
93193 sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
93194 sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
93195 sqlite3ReleaseTempReg(pParse, r1);
93198 #ifndef SQLITE_OMIT_SUBQUERY
93200 ** Generate an error message when a SELECT is used within a subexpression
93201 ** (example: "a IN (SELECT * FROM table)") but it has more than 1 result
93202 ** column. We do this in a subroutine because the error used to occur
93203 ** in multiple places. (The error only occurs in one place now, but we
93204 ** retain the subroutine to minimize code disruption.)
93206 static int checkForMultiColumnSelectError(
93207 Parse *pParse, /* Parse context. */
93208 SelectDest *pDest, /* Destination of SELECT results */
93209 int nExpr /* Number of result columns returned by SELECT */
93211 int eDest = pDest->eDest;
93212 if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
93213 sqlite3ErrorMsg(pParse, "only a single result allowed for "
93214 "a SELECT that is part of an expression");
93215 return 1;
93216 }else{
93217 return 0;
93220 #endif
93223 ** This routine generates the code for the inside of the inner loop
93224 ** of a SELECT.
93226 ** If srcTab and nColumn are both zero, then the pEList expressions
93227 ** are evaluated in order to get the data for this row. If nColumn>0
93228 ** then data is pulled from srcTab and pEList is used only to get the
93229 ** datatypes for each column.
93231 static void selectInnerLoop(
93232 Parse *pParse, /* The parser context */
93233 Select *p, /* The complete select statement being coded */
93234 ExprList *pEList, /* List of values being extracted */
93235 int srcTab, /* Pull data from this table */
93236 int nColumn, /* Number of columns in the source table */
93237 ExprList *pOrderBy, /* If not NULL, sort results using this key */
93238 int distinct, /* If >=0, make sure results are distinct */
93239 SelectDest *pDest, /* How to dispose of the results */
93240 int iContinue, /* Jump here to continue with next row */
93241 int iBreak /* Jump here to break out of the inner loop */
93243 Vdbe *v = pParse->pVdbe;
93244 int i;
93245 int hasDistinct; /* True if the DISTINCT keyword is present */
93246 int regResult; /* Start of memory holding result set */
93247 int eDest = pDest->eDest; /* How to dispose of results */
93248 int iParm = pDest->iParm; /* First argument to disposal method */
93249 int nResultCol; /* Number of result columns */
93251 assert( v );
93252 if( NEVER(v==0) ) return;
93253 assert( pEList!=0 );
93254 hasDistinct = distinct>=0;
93255 if( pOrderBy==0 && !hasDistinct ){
93256 codeOffset(v, p, iContinue);
93259 /* Pull the requested columns.
93261 if( nColumn>0 ){
93262 nResultCol = nColumn;
93263 }else{
93264 nResultCol = pEList->nExpr;
93266 if( pDest->iMem==0 ){
93267 pDest->iMem = pParse->nMem+1;
93268 pDest->nMem = nResultCol;
93269 pParse->nMem += nResultCol;
93270 }else{
93271 assert( pDest->nMem==nResultCol );
93273 regResult = pDest->iMem;
93274 if( nColumn>0 ){
93275 for(i=0; i<nColumn; i++){
93276 sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
93278 }else if( eDest!=SRT_Exists ){
93279 /* If the destination is an EXISTS(...) expression, the actual
93280 ** values returned by the SELECT are not required.
93282 sqlite3ExprCacheClear(pParse);
93283 sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
93285 nColumn = nResultCol;
93287 /* If the DISTINCT keyword was present on the SELECT statement
93288 ** and this row has been seen before, then do not make this row
93289 ** part of the result.
93291 if( hasDistinct ){
93292 assert( pEList!=0 );
93293 assert( pEList->nExpr==nColumn );
93294 codeDistinct(pParse, distinct, iContinue, nColumn, regResult);
93295 if( pOrderBy==0 ){
93296 codeOffset(v, p, iContinue);
93300 switch( eDest ){
93301 /* In this mode, write each query result to the key of the temporary
93302 ** table iParm.
93304 #ifndef SQLITE_OMIT_COMPOUND_SELECT
93305 case SRT_Union: {
93306 int r1;
93307 r1 = sqlite3GetTempReg(pParse);
93308 sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
93309 sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
93310 sqlite3ReleaseTempReg(pParse, r1);
93311 break;
93314 /* Construct a record from the query result, but instead of
93315 ** saving that record, use it as a key to delete elements from
93316 ** the temporary table iParm.
93318 case SRT_Except: {
93319 sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
93320 break;
93322 #endif
93324 /* Store the result as data using a unique key.
93326 case SRT_Table:
93327 case SRT_EphemTab: {
93328 int r1 = sqlite3GetTempReg(pParse);
93329 testcase( eDest==SRT_Table );
93330 testcase( eDest==SRT_EphemTab );
93331 sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
93332 if( pOrderBy ){
93333 pushOntoSorter(pParse, pOrderBy, p, r1);
93334 }else{
93335 int r2 = sqlite3GetTempReg(pParse);
93336 sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
93337 sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
93338 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
93339 sqlite3ReleaseTempReg(pParse, r2);
93341 sqlite3ReleaseTempReg(pParse, r1);
93342 break;
93345 #ifndef SQLITE_OMIT_SUBQUERY
93346 /* If we are creating a set for an "expr IN (SELECT ...)" construct,
93347 ** then there should be a single item on the stack. Write this
93348 ** item into the set table with bogus data.
93350 case SRT_Set: {
93351 assert( nColumn==1 );
93352 p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affinity);
93353 if( pOrderBy ){
93354 /* At first glance you would think we could optimize out the
93355 ** ORDER BY in this case since the order of entries in the set
93356 ** does not matter. But there might be a LIMIT clause, in which
93357 ** case the order does matter */
93358 pushOntoSorter(pParse, pOrderBy, p, regResult);
93359 }else{
93360 int r1 = sqlite3GetTempReg(pParse);
93361 sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, 1, r1, &p->affinity, 1);
93362 sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
93363 sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
93364 sqlite3ReleaseTempReg(pParse, r1);
93366 break;
93369 /* If any row exist in the result set, record that fact and abort.
93371 case SRT_Exists: {
93372 sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
93373 /* The LIMIT clause will terminate the loop for us */
93374 break;
93377 /* If this is a scalar select that is part of an expression, then
93378 ** store the results in the appropriate memory cell and break out
93379 ** of the scan loop.
93381 case SRT_Mem: {
93382 assert( nColumn==1 );
93383 if( pOrderBy ){
93384 pushOntoSorter(pParse, pOrderBy, p, regResult);
93385 }else{
93386 sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
93387 /* The LIMIT clause will jump out of the loop for us */
93389 break;
93391 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
93393 /* Send the data to the callback function or to a subroutine. In the
93394 ** case of a subroutine, the subroutine itself is responsible for
93395 ** popping the data from the stack.
93397 case SRT_Coroutine:
93398 case SRT_Output: {
93399 testcase( eDest==SRT_Coroutine );
93400 testcase( eDest==SRT_Output );
93401 if( pOrderBy ){
93402 int r1 = sqlite3GetTempReg(pParse);
93403 sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
93404 pushOntoSorter(pParse, pOrderBy, p, r1);
93405 sqlite3ReleaseTempReg(pParse, r1);
93406 }else if( eDest==SRT_Coroutine ){
93407 sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
93408 }else{
93409 sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
93410 sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
93412 break;
93415 #if !defined(SQLITE_OMIT_TRIGGER)
93416 /* Discard the results. This is used for SELECT statements inside
93417 ** the body of a TRIGGER. The purpose of such selects is to call
93418 ** user-defined functions that have side effects. We do not care
93419 ** about the actual results of the select.
93421 default: {
93422 assert( eDest==SRT_Discard );
93423 break;
93425 #endif
93428 /* Jump to the end of the loop if the LIMIT is reached. Except, if
93429 ** there is a sorter, in which case the sorter has already limited
93430 ** the output for us.
93432 if( pOrderBy==0 && p->iLimit ){
93433 sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
93438 ** Given an expression list, generate a KeyInfo structure that records
93439 ** the collating sequence for each expression in that expression list.
93441 ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
93442 ** KeyInfo structure is appropriate for initializing a virtual index to
93443 ** implement that clause. If the ExprList is the result set of a SELECT
93444 ** then the KeyInfo structure is appropriate for initializing a virtual
93445 ** index to implement a DISTINCT test.
93447 ** Space to hold the KeyInfo structure is obtain from malloc. The calling
93448 ** function is responsible for seeing that this structure is eventually
93449 ** freed. Add the KeyInfo structure to the P4 field of an opcode using
93450 ** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
93452 static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
93453 sqlite3 *db = pParse->db;
93454 int nExpr;
93455 KeyInfo *pInfo;
93456 struct ExprList_item *pItem;
93457 int i;
93459 nExpr = pList->nExpr;
93460 pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
93461 if( pInfo ){
93462 pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
93463 pInfo->nField = (u16)nExpr;
93464 pInfo->enc = ENC(db);
93465 pInfo->db = db;
93466 for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
93467 CollSeq *pColl;
93468 pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
93469 if( !pColl ){
93470 pColl = db->pDfltColl;
93472 pInfo->aColl[i] = pColl;
93473 pInfo->aSortOrder[i] = pItem->sortOrder;
93476 return pInfo;
93479 #ifndef SQLITE_OMIT_COMPOUND_SELECT
93481 ** Name of the connection operator, used for error messages.
93483 static const char *selectOpName(int id){
93484 char *z;
93485 switch( id ){
93486 case TK_ALL: z = "UNION ALL"; break;
93487 case TK_INTERSECT: z = "INTERSECT"; break;
93488 case TK_EXCEPT: z = "EXCEPT"; break;
93489 default: z = "UNION"; break;
93491 return z;
93493 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
93495 #ifndef SQLITE_OMIT_EXPLAIN
93497 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
93498 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
93499 ** where the caption is of the form:
93501 ** "USE TEMP B-TREE FOR xxx"
93503 ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
93504 ** is determined by the zUsage argument.
93506 static void explainTempTable(Parse *pParse, const char *zUsage){
93507 if( pParse->explain==2 ){
93508 Vdbe *v = pParse->pVdbe;
93509 char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
93510 sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
93515 ** Assign expression b to lvalue a. A second, no-op, version of this macro
93516 ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
93517 ** in sqlite3Select() to assign values to structure member variables that
93518 ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
93519 ** code with #ifndef directives.
93521 # define explainSetInteger(a, b) a = b
93523 #else
93524 /* No-op versions of the explainXXX() functions and macros. */
93525 # define explainTempTable(y,z)
93526 # define explainSetInteger(y,z)
93527 #endif
93529 #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
93531 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
93532 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
93533 ** where the caption is of one of the two forms:
93535 ** "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
93536 ** "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
93538 ** where iSub1 and iSub2 are the integers passed as the corresponding
93539 ** function parameters, and op is the text representation of the parameter
93540 ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
93541 ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
93542 ** false, or the second form if it is true.
93544 static void explainComposite(
93545 Parse *pParse, /* Parse context */
93546 int op, /* One of TK_UNION, TK_EXCEPT etc. */
93547 int iSub1, /* Subquery id 1 */
93548 int iSub2, /* Subquery id 2 */
93549 int bUseTmp /* True if a temp table was used */
93551 assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
93552 if( pParse->explain==2 ){
93553 Vdbe *v = pParse->pVdbe;
93554 char *zMsg = sqlite3MPrintf(
93555 pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
93556 bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
93558 sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
93561 #else
93562 /* No-op versions of the explainXXX() functions and macros. */
93563 # define explainComposite(v,w,x,y,z)
93564 #endif
93567 ** If the inner loop was generated using a non-null pOrderBy argument,
93568 ** then the results were placed in a sorter. After the loop is terminated
93569 ** we need to run the sorter and output the results. The following
93570 ** routine generates the code needed to do that.
93572 static void generateSortTail(
93573 Parse *pParse, /* Parsing context */
93574 Select *p, /* The SELECT statement */
93575 Vdbe *v, /* Generate code into this VDBE */
93576 int nColumn, /* Number of columns of data */
93577 SelectDest *pDest /* Write the sorted results here */
93579 int addrBreak = sqlite3VdbeMakeLabel(v); /* Jump here to exit loop */
93580 int addrContinue = sqlite3VdbeMakeLabel(v); /* Jump here for next cycle */
93581 int addr;
93582 int iTab;
93583 int pseudoTab = 0;
93584 ExprList *pOrderBy = p->pOrderBy;
93586 int eDest = pDest->eDest;
93587 int iParm = pDest->iParm;
93589 int regRow;
93590 int regRowid;
93592 iTab = pOrderBy->iECursor;
93593 regRow = sqlite3GetTempReg(pParse);
93594 if( eDest==SRT_Output || eDest==SRT_Coroutine ){
93595 pseudoTab = pParse->nTab++;
93596 sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn);
93597 regRowid = 0;
93598 }else{
93599 regRowid = sqlite3GetTempReg(pParse);
93601 if( p->selFlags & SF_UseSorter ){
93602 int regSortOut = ++pParse->nMem;
93603 int ptab2 = pParse->nTab++;
93604 sqlite3VdbeAddOp3(v, OP_OpenPseudo, ptab2, regSortOut, pOrderBy->nExpr+2);
93605 addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
93606 codeOffset(v, p, addrContinue);
93607 sqlite3VdbeAddOp2(v, OP_SorterData, iTab, regSortOut);
93608 sqlite3VdbeAddOp3(v, OP_Column, ptab2, pOrderBy->nExpr+1, regRow);
93609 sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
93610 }else{
93611 addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
93612 codeOffset(v, p, addrContinue);
93613 sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr+1, regRow);
93615 switch( eDest ){
93616 case SRT_Table:
93617 case SRT_EphemTab: {
93618 testcase( eDest==SRT_Table );
93619 testcase( eDest==SRT_EphemTab );
93620 sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
93621 sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
93622 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
93623 break;
93625 #ifndef SQLITE_OMIT_SUBQUERY
93626 case SRT_Set: {
93627 assert( nColumn==1 );
93628 sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, &p->affinity, 1);
93629 sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
93630 sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
93631 break;
93633 case SRT_Mem: {
93634 assert( nColumn==1 );
93635 sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
93636 /* The LIMIT clause will terminate the loop for us */
93637 break;
93639 #endif
93640 default: {
93641 int i;
93642 assert( eDest==SRT_Output || eDest==SRT_Coroutine );
93643 testcase( eDest==SRT_Output );
93644 testcase( eDest==SRT_Coroutine );
93645 for(i=0; i<nColumn; i++){
93646 assert( regRow!=pDest->iMem+i );
93647 sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iMem+i);
93648 if( i==0 ){
93649 sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
93652 if( eDest==SRT_Output ){
93653 sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iMem, nColumn);
93654 sqlite3ExprCacheAffinityChange(pParse, pDest->iMem, nColumn);
93655 }else{
93656 sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
93658 break;
93661 sqlite3ReleaseTempReg(pParse, regRow);
93662 sqlite3ReleaseTempReg(pParse, regRowid);
93664 /* The bottom of the loop
93666 sqlite3VdbeResolveLabel(v, addrContinue);
93667 if( p->selFlags & SF_UseSorter ){
93668 sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr);
93669 }else{
93670 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
93672 sqlite3VdbeResolveLabel(v, addrBreak);
93673 if( eDest==SRT_Output || eDest==SRT_Coroutine ){
93674 sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
93679 ** Return a pointer to a string containing the 'declaration type' of the
93680 ** expression pExpr. The string may be treated as static by the caller.
93682 ** The declaration type is the exact datatype definition extracted from the
93683 ** original CREATE TABLE statement if the expression is a column. The
93684 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
93685 ** is considered a column can be complex in the presence of subqueries. The
93686 ** result-set expression in all of the following SELECT statements is
93687 ** considered a column by this function.
93689 ** SELECT col FROM tbl;
93690 ** SELECT (SELECT col FROM tbl;
93691 ** SELECT (SELECT col FROM tbl);
93692 ** SELECT abc FROM (SELECT col AS abc FROM tbl);
93694 ** The declaration type for any expression other than a column is NULL.
93696 static const char *columnType(
93697 NameContext *pNC,
93698 Expr *pExpr,
93699 const char **pzOriginDb,
93700 const char **pzOriginTab,
93701 const char **pzOriginCol
93703 char const *zType = 0;
93704 char const *zOriginDb = 0;
93705 char const *zOriginTab = 0;
93706 char const *zOriginCol = 0;
93707 int j;
93708 if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
93710 switch( pExpr->op ){
93711 case TK_AGG_COLUMN:
93712 case TK_COLUMN: {
93713 /* The expression is a column. Locate the table the column is being
93714 ** extracted from in NameContext.pSrcList. This table may be real
93715 ** database table or a subquery.
93717 Table *pTab = 0; /* Table structure column is extracted from */
93718 Select *pS = 0; /* Select the column is extracted from */
93719 int iCol = pExpr->iColumn; /* Index of column in pTab */
93720 testcase( pExpr->op==TK_AGG_COLUMN );
93721 testcase( pExpr->op==TK_COLUMN );
93722 while( pNC && !pTab ){
93723 SrcList *pTabList = pNC->pSrcList;
93724 for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
93725 if( j<pTabList->nSrc ){
93726 pTab = pTabList->a[j].pTab;
93727 pS = pTabList->a[j].pSelect;
93728 }else{
93729 pNC = pNC->pNext;
93733 if( pTab==0 ){
93734 /* At one time, code such as "SELECT new.x" within a trigger would
93735 ** cause this condition to run. Since then, we have restructured how
93736 ** trigger code is generated and so this condition is no longer
93737 ** possible. However, it can still be true for statements like
93738 ** the following:
93740 ** CREATE TABLE t1(col INTEGER);
93741 ** SELECT (SELECT t1.col) FROM FROM t1;
93743 ** when columnType() is called on the expression "t1.col" in the
93744 ** sub-select. In this case, set the column type to NULL, even
93745 ** though it should really be "INTEGER".
93747 ** This is not a problem, as the column type of "t1.col" is never
93748 ** used. When columnType() is called on the expression
93749 ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
93750 ** branch below. */
93751 break;
93754 assert( pTab && pExpr->pTab==pTab );
93755 if( pS ){
93756 /* The "table" is actually a sub-select or a view in the FROM clause
93757 ** of the SELECT statement. Return the declaration type and origin
93758 ** data for the result-set column of the sub-select.
93760 if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
93761 /* If iCol is less than zero, then the expression requests the
93762 ** rowid of the sub-select or view. This expression is legal (see
93763 ** test case misc2.2.2) - it always evaluates to NULL.
93765 NameContext sNC;
93766 Expr *p = pS->pEList->a[iCol].pExpr;
93767 sNC.pSrcList = pS->pSrc;
93768 sNC.pNext = pNC;
93769 sNC.pParse = pNC->pParse;
93770 zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
93772 }else if( ALWAYS(pTab->pSchema) ){
93773 /* A real table */
93774 assert( !pS );
93775 if( iCol<0 ) iCol = pTab->iPKey;
93776 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
93777 if( iCol<0 ){
93778 zType = "INTEGER";
93779 zOriginCol = "rowid";
93780 }else{
93781 zType = pTab->aCol[iCol].zType;
93782 zOriginCol = pTab->aCol[iCol].zName;
93784 zOriginTab = pTab->zName;
93785 if( pNC->pParse ){
93786 int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
93787 zOriginDb = pNC->pParse->db->aDb[iDb].zName;
93790 break;
93792 #ifndef SQLITE_OMIT_SUBQUERY
93793 case TK_SELECT: {
93794 /* The expression is a sub-select. Return the declaration type and
93795 ** origin info for the single column in the result set of the SELECT
93796 ** statement.
93798 NameContext sNC;
93799 Select *pS = pExpr->x.pSelect;
93800 Expr *p = pS->pEList->a[0].pExpr;
93801 assert( ExprHasProperty(pExpr, EP_xIsSelect) );
93802 sNC.pSrcList = pS->pSrc;
93803 sNC.pNext = pNC;
93804 sNC.pParse = pNC->pParse;
93805 zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
93806 break;
93808 #endif
93811 if( pzOriginDb ){
93812 assert( pzOriginTab && pzOriginCol );
93813 *pzOriginDb = zOriginDb;
93814 *pzOriginTab = zOriginTab;
93815 *pzOriginCol = zOriginCol;
93817 return zType;
93821 ** Generate code that will tell the VDBE the declaration types of columns
93822 ** in the result set.
93824 static void generateColumnTypes(
93825 Parse *pParse, /* Parser context */
93826 SrcList *pTabList, /* List of tables */
93827 ExprList *pEList /* Expressions defining the result set */
93829 #ifndef SQLITE_OMIT_DECLTYPE
93830 Vdbe *v = pParse->pVdbe;
93831 int i;
93832 NameContext sNC;
93833 sNC.pSrcList = pTabList;
93834 sNC.pParse = pParse;
93835 for(i=0; i<pEList->nExpr; i++){
93836 Expr *p = pEList->a[i].pExpr;
93837 const char *zType;
93838 #ifdef SQLITE_ENABLE_COLUMN_METADATA
93839 const char *zOrigDb = 0;
93840 const char *zOrigTab = 0;
93841 const char *zOrigCol = 0;
93842 zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
93844 /* The vdbe must make its own copy of the column-type and other
93845 ** column specific strings, in case the schema is reset before this
93846 ** virtual machine is deleted.
93848 sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
93849 sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
93850 sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
93851 #else
93852 zType = columnType(&sNC, p, 0, 0, 0);
93853 #endif
93854 sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
93856 #endif /* SQLITE_OMIT_DECLTYPE */
93860 ** Generate code that will tell the VDBE the names of columns
93861 ** in the result set. This information is used to provide the
93862 ** azCol[] values in the callback.
93864 static void generateColumnNames(
93865 Parse *pParse, /* Parser context */
93866 SrcList *pTabList, /* List of tables */
93867 ExprList *pEList /* Expressions defining the result set */
93869 Vdbe *v = pParse->pVdbe;
93870 int i, j;
93871 sqlite3 *db = pParse->db;
93872 int fullNames, shortNames;
93874 #ifndef SQLITE_OMIT_EXPLAIN
93875 /* If this is an EXPLAIN, skip this step */
93876 if( pParse->explain ){
93877 return;
93879 #endif
93881 if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
93882 pParse->colNamesSet = 1;
93883 fullNames = (db->flags & SQLITE_FullColNames)!=0;
93884 shortNames = (db->flags & SQLITE_ShortColNames)!=0;
93885 sqlite3VdbeSetNumCols(v, pEList->nExpr);
93886 for(i=0; i<pEList->nExpr; i++){
93887 Expr *p;
93888 p = pEList->a[i].pExpr;
93889 if( NEVER(p==0) ) continue;
93890 if( pEList->a[i].zName ){
93891 char *zName = pEList->a[i].zName;
93892 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
93893 }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
93894 Table *pTab;
93895 char *zCol;
93896 int iCol = p->iColumn;
93897 for(j=0; ALWAYS(j<pTabList->nSrc); j++){
93898 if( pTabList->a[j].iCursor==p->iTable ) break;
93900 assert( j<pTabList->nSrc );
93901 pTab = pTabList->a[j].pTab;
93902 if( iCol<0 ) iCol = pTab->iPKey;
93903 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
93904 if( iCol<0 ){
93905 zCol = "rowid";
93906 }else{
93907 zCol = pTab->aCol[iCol].zName;
93909 if( !shortNames && !fullNames ){
93910 sqlite3VdbeSetColName(v, i, COLNAME_NAME,
93911 sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
93912 }else if( fullNames ){
93913 char *zName = 0;
93914 zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
93915 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
93916 }else{
93917 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
93919 }else{
93920 sqlite3VdbeSetColName(v, i, COLNAME_NAME,
93921 sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
93924 generateColumnTypes(pParse, pTabList, pEList);
93928 ** Given a an expression list (which is really the list of expressions
93929 ** that form the result set of a SELECT statement) compute appropriate
93930 ** column names for a table that would hold the expression list.
93932 ** All column names will be unique.
93934 ** Only the column names are computed. Column.zType, Column.zColl,
93935 ** and other fields of Column are zeroed.
93937 ** Return SQLITE_OK on success. If a memory allocation error occurs,
93938 ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
93940 static int selectColumnsFromExprList(
93941 Parse *pParse, /* Parsing context */
93942 ExprList *pEList, /* Expr list from which to derive column names */
93943 int *pnCol, /* Write the number of columns here */
93944 Column **paCol /* Write the new column list here */
93946 sqlite3 *db = pParse->db; /* Database connection */
93947 int i, j; /* Loop counters */
93948 int cnt; /* Index added to make the name unique */
93949 Column *aCol, *pCol; /* For looping over result columns */
93950 int nCol; /* Number of columns in the result set */
93951 Expr *p; /* Expression for a single result column */
93952 char *zName; /* Column name */
93953 int nName; /* Size of name in zName[] */
93955 *pnCol = nCol = pEList->nExpr;
93956 aCol = *paCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
93957 if( aCol==0 ) return SQLITE_NOMEM;
93958 for(i=0, pCol=aCol; i<nCol; i++, pCol++){
93959 /* Get an appropriate name for the column
93961 p = pEList->a[i].pExpr;
93962 assert( p->pRight==0 || ExprHasProperty(p->pRight, EP_IntValue)
93963 || p->pRight->u.zToken==0 || p->pRight->u.zToken[0]!=0 );
93964 if( (zName = pEList->a[i].zName)!=0 ){
93965 /* If the column contains an "AS <name>" phrase, use <name> as the name */
93966 zName = sqlite3DbStrDup(db, zName);
93967 }else{
93968 Expr *pColExpr = p; /* The expression that is the result column name */
93969 Table *pTab; /* Table associated with this expression */
93970 while( pColExpr->op==TK_DOT ){
93971 pColExpr = pColExpr->pRight;
93972 assert( pColExpr!=0 );
93974 if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
93975 /* For columns use the column name name */
93976 int iCol = pColExpr->iColumn;
93977 pTab = pColExpr->pTab;
93978 if( iCol<0 ) iCol = pTab->iPKey;
93979 zName = sqlite3MPrintf(db, "%s",
93980 iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
93981 }else if( pColExpr->op==TK_ID ){
93982 assert( !ExprHasProperty(pColExpr, EP_IntValue) );
93983 zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
93984 }else{
93985 /* Use the original text of the column expression as its name */
93986 zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
93989 if( db->mallocFailed ){
93990 sqlite3DbFree(db, zName);
93991 break;
93994 /* Make sure the column name is unique. If the name is not unique,
93995 ** append a integer to the name so that it becomes unique.
93997 nName = sqlite3Strlen30(zName);
93998 for(j=cnt=0; j<i; j++){
93999 if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
94000 char *zNewName;
94001 zName[nName] = 0;
94002 zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
94003 sqlite3DbFree(db, zName);
94004 zName = zNewName;
94005 j = -1;
94006 if( zName==0 ) break;
94009 pCol->zName = zName;
94011 if( db->mallocFailed ){
94012 for(j=0; j<i; j++){
94013 sqlite3DbFree(db, aCol[j].zName);
94015 sqlite3DbFree(db, aCol);
94016 *paCol = 0;
94017 *pnCol = 0;
94018 return SQLITE_NOMEM;
94020 return SQLITE_OK;
94024 ** Add type and collation information to a column list based on
94025 ** a SELECT statement.
94027 ** The column list presumably came from selectColumnNamesFromExprList().
94028 ** The column list has only names, not types or collations. This
94029 ** routine goes through and adds the types and collations.
94031 ** This routine requires that all identifiers in the SELECT
94032 ** statement be resolved.
94034 static void selectAddColumnTypeAndCollation(
94035 Parse *pParse, /* Parsing contexts */
94036 int nCol, /* Number of columns */
94037 Column *aCol, /* List of columns */
94038 Select *pSelect /* SELECT used to determine types and collations */
94040 sqlite3 *db = pParse->db;
94041 NameContext sNC;
94042 Column *pCol;
94043 CollSeq *pColl;
94044 int i;
94045 Expr *p;
94046 struct ExprList_item *a;
94048 assert( pSelect!=0 );
94049 assert( (pSelect->selFlags & SF_Resolved)!=0 );
94050 assert( nCol==pSelect->pEList->nExpr || db->mallocFailed );
94051 if( db->mallocFailed ) return;
94052 memset(&sNC, 0, sizeof(sNC));
94053 sNC.pSrcList = pSelect->pSrc;
94054 a = pSelect->pEList->a;
94055 for(i=0, pCol=aCol; i<nCol; i++, pCol++){
94056 p = a[i].pExpr;
94057 pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
94058 pCol->affinity = sqlite3ExprAffinity(p);
94059 if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
94060 pColl = sqlite3ExprCollSeq(pParse, p);
94061 if( pColl ){
94062 pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
94068 ** Given a SELECT statement, generate a Table structure that describes
94069 ** the result set of that SELECT.
94071 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
94072 Table *pTab;
94073 sqlite3 *db = pParse->db;
94074 int savedFlags;
94076 savedFlags = db->flags;
94077 db->flags &= ~SQLITE_FullColNames;
94078 db->flags |= SQLITE_ShortColNames;
94079 sqlite3SelectPrep(pParse, pSelect, 0);
94080 if( pParse->nErr ) return 0;
94081 while( pSelect->pPrior ) pSelect = pSelect->pPrior;
94082 db->flags = savedFlags;
94083 pTab = sqlite3DbMallocZero(db, sizeof(Table) );
94084 if( pTab==0 ){
94085 return 0;
94087 /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
94088 ** is disabled */
94089 assert( db->lookaside.bEnabled==0 );
94090 pTab->nRef = 1;
94091 pTab->zName = 0;
94092 pTab->nRowEst = 1000000;
94093 selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
94094 selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);
94095 pTab->iPKey = -1;
94096 if( db->mallocFailed ){
94097 sqlite3DeleteTable(db, pTab);
94098 return 0;
94100 return pTab;
94104 ** Get a VDBE for the given parser context. Create a new one if necessary.
94105 ** If an error occurs, return NULL and leave a message in pParse.
94107 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
94108 Vdbe *v = pParse->pVdbe;
94109 if( v==0 ){
94110 v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
94111 #ifndef SQLITE_OMIT_TRACE
94112 if( v ){
94113 sqlite3VdbeAddOp0(v, OP_Trace);
94115 #endif
94117 return v;
94122 ** Compute the iLimit and iOffset fields of the SELECT based on the
94123 ** pLimit and pOffset expressions. pLimit and pOffset hold the expressions
94124 ** that appear in the original SQL statement after the LIMIT and OFFSET
94125 ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset
94126 ** are the integer memory register numbers for counters used to compute
94127 ** the limit and offset. If there is no limit and/or offset, then
94128 ** iLimit and iOffset are negative.
94130 ** This routine changes the values of iLimit and iOffset only if
94131 ** a limit or offset is defined by pLimit and pOffset. iLimit and
94132 ** iOffset should have been preset to appropriate default values
94133 ** (usually but not always -1) prior to calling this routine.
94134 ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
94135 ** redefined. The UNION ALL operator uses this property to force
94136 ** the reuse of the same limit and offset registers across multiple
94137 ** SELECT statements.
94139 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
94140 Vdbe *v = 0;
94141 int iLimit = 0;
94142 int iOffset;
94143 int addr1, n;
94144 if( p->iLimit ) return;
94147 ** "LIMIT -1" always shows all rows. There is some
94148 ** contraversy about what the correct behavior should be.
94149 ** The current implementation interprets "LIMIT 0" to mean
94150 ** no rows.
94152 sqlite3ExprCacheClear(pParse);
94153 assert( p->pOffset==0 || p->pLimit!=0 );
94154 if( p->pLimit ){
94155 p->iLimit = iLimit = ++pParse->nMem;
94156 v = sqlite3GetVdbe(pParse);
94157 if( NEVER(v==0) ) return; /* VDBE should have already been allocated */
94158 if( sqlite3ExprIsInteger(p->pLimit, &n) ){
94159 sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
94160 VdbeComment((v, "LIMIT counter"));
94161 if( n==0 ){
94162 sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
94163 }else{
94164 if( p->nSelectRow > (double)n ) p->nSelectRow = (double)n;
94166 }else{
94167 sqlite3ExprCode(pParse, p->pLimit, iLimit);
94168 sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
94169 VdbeComment((v, "LIMIT counter"));
94170 sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
94172 if( p->pOffset ){
94173 p->iOffset = iOffset = ++pParse->nMem;
94174 pParse->nMem++; /* Allocate an extra register for limit+offset */
94175 sqlite3ExprCode(pParse, p->pOffset, iOffset);
94176 sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
94177 VdbeComment((v, "OFFSET counter"));
94178 addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
94179 sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
94180 sqlite3VdbeJumpHere(v, addr1);
94181 sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
94182 VdbeComment((v, "LIMIT+OFFSET"));
94183 addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
94184 sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
94185 sqlite3VdbeJumpHere(v, addr1);
94190 #ifndef SQLITE_OMIT_COMPOUND_SELECT
94192 ** Return the appropriate collating sequence for the iCol-th column of
94193 ** the result set for the compound-select statement "p". Return NULL if
94194 ** the column has no default collating sequence.
94196 ** The collating sequence for the compound select is taken from the
94197 ** left-most term of the select that has a collating sequence.
94199 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
94200 CollSeq *pRet;
94201 if( p->pPrior ){
94202 pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
94203 }else{
94204 pRet = 0;
94206 assert( iCol>=0 );
94207 if( pRet==0 && iCol<p->pEList->nExpr ){
94208 pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
94210 return pRet;
94212 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
94214 /* Forward reference */
94215 static int multiSelectOrderBy(
94216 Parse *pParse, /* Parsing context */
94217 Select *p, /* The right-most of SELECTs to be coded */
94218 SelectDest *pDest /* What to do with query results */
94222 #ifndef SQLITE_OMIT_COMPOUND_SELECT
94224 ** This routine is called to process a compound query form from
94225 ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
94226 ** INTERSECT
94228 ** "p" points to the right-most of the two queries. the query on the
94229 ** left is p->pPrior. The left query could also be a compound query
94230 ** in which case this routine will be called recursively.
94232 ** The results of the total query are to be written into a destination
94233 ** of type eDest with parameter iParm.
94235 ** Example 1: Consider a three-way compound SQL statement.
94237 ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
94239 ** This statement is parsed up as follows:
94241 ** SELECT c FROM t3
94242 ** |
94243 ** `-----> SELECT b FROM t2
94244 ** |
94245 ** `------> SELECT a FROM t1
94247 ** The arrows in the diagram above represent the Select.pPrior pointer.
94248 ** So if this routine is called with p equal to the t3 query, then
94249 ** pPrior will be the t2 query. p->op will be TK_UNION in this case.
94251 ** Notice that because of the way SQLite parses compound SELECTs, the
94252 ** individual selects always group from left to right.
94254 static int multiSelect(
94255 Parse *pParse, /* Parsing context */
94256 Select *p, /* The right-most of SELECTs to be coded */
94257 SelectDest *pDest /* What to do with query results */
94259 int rc = SQLITE_OK; /* Success code from a subroutine */
94260 Select *pPrior; /* Another SELECT immediately to our left */
94261 Vdbe *v; /* Generate code to this VDBE */
94262 SelectDest dest; /* Alternative data destination */
94263 Select *pDelete = 0; /* Chain of simple selects to delete */
94264 sqlite3 *db; /* Database connection */
94265 #ifndef SQLITE_OMIT_EXPLAIN
94266 int iSub1; /* EQP id of left-hand query */
94267 int iSub2; /* EQP id of right-hand query */
94268 #endif
94270 /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
94271 ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
94273 assert( p && p->pPrior ); /* Calling function guarantees this much */
94274 db = pParse->db;
94275 pPrior = p->pPrior;
94276 assert( pPrior->pRightmost!=pPrior );
94277 assert( pPrior->pRightmost==p->pRightmost );
94278 dest = *pDest;
94279 if( pPrior->pOrderBy ){
94280 sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
94281 selectOpName(p->op));
94282 rc = 1;
94283 goto multi_select_end;
94285 if( pPrior->pLimit ){
94286 sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
94287 selectOpName(p->op));
94288 rc = 1;
94289 goto multi_select_end;
94292 v = sqlite3GetVdbe(pParse);
94293 assert( v!=0 ); /* The VDBE already created by calling function */
94295 /* Create the destination temporary table if necessary
94297 if( dest.eDest==SRT_EphemTab ){
94298 assert( p->pEList );
94299 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, p->pEList->nExpr);
94300 sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
94301 dest.eDest = SRT_Table;
94304 /* Make sure all SELECTs in the statement have the same number of elements
94305 ** in their result sets.
94307 assert( p->pEList && pPrior->pEList );
94308 if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
94309 sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
94310 " do not have the same number of result columns", selectOpName(p->op));
94311 rc = 1;
94312 goto multi_select_end;
94315 /* Compound SELECTs that have an ORDER BY clause are handled separately.
94317 if( p->pOrderBy ){
94318 return multiSelectOrderBy(pParse, p, pDest);
94321 /* Generate code for the left and right SELECT statements.
94323 switch( p->op ){
94324 case TK_ALL: {
94325 int addr = 0;
94326 int nLimit;
94327 assert( !pPrior->pLimit );
94328 pPrior->pLimit = p->pLimit;
94329 pPrior->pOffset = p->pOffset;
94330 explainSetInteger(iSub1, pParse->iNextSelectId);
94331 rc = sqlite3Select(pParse, pPrior, &dest);
94332 p->pLimit = 0;
94333 p->pOffset = 0;
94334 if( rc ){
94335 goto multi_select_end;
94337 p->pPrior = 0;
94338 p->iLimit = pPrior->iLimit;
94339 p->iOffset = pPrior->iOffset;
94340 if( p->iLimit ){
94341 addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
94342 VdbeComment((v, "Jump ahead if LIMIT reached"));
94344 explainSetInteger(iSub2, pParse->iNextSelectId);
94345 rc = sqlite3Select(pParse, p, &dest);
94346 testcase( rc!=SQLITE_OK );
94347 pDelete = p->pPrior;
94348 p->pPrior = pPrior;
94349 p->nSelectRow += pPrior->nSelectRow;
94350 if( pPrior->pLimit
94351 && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
94352 && p->nSelectRow > (double)nLimit
94354 p->nSelectRow = (double)nLimit;
94356 if( addr ){
94357 sqlite3VdbeJumpHere(v, addr);
94359 break;
94361 case TK_EXCEPT:
94362 case TK_UNION: {
94363 int unionTab; /* Cursor number of the temporary table holding result */
94364 u8 op = 0; /* One of the SRT_ operations to apply to self */
94365 int priorOp; /* The SRT_ operation to apply to prior selects */
94366 Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
94367 int addr;
94368 SelectDest uniondest;
94370 testcase( p->op==TK_EXCEPT );
94371 testcase( p->op==TK_UNION );
94372 priorOp = SRT_Union;
94373 if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){
94374 /* We can reuse a temporary table generated by a SELECT to our
94375 ** right.
94377 assert( p->pRightmost!=p ); /* Can only happen for leftward elements
94378 ** of a 3-way or more compound */
94379 assert( p->pLimit==0 ); /* Not allowed on leftward elements */
94380 assert( p->pOffset==0 ); /* Not allowed on leftward elements */
94381 unionTab = dest.iParm;
94382 }else{
94383 /* We will need to create our own temporary table to hold the
94384 ** intermediate results.
94386 unionTab = pParse->nTab++;
94387 assert( p->pOrderBy==0 );
94388 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
94389 assert( p->addrOpenEphm[0] == -1 );
94390 p->addrOpenEphm[0] = addr;
94391 p->pRightmost->selFlags |= SF_UsesEphemeral;
94392 assert( p->pEList );
94395 /* Code the SELECT statements to our left
94397 assert( !pPrior->pOrderBy );
94398 sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
94399 explainSetInteger(iSub1, pParse->iNextSelectId);
94400 rc = sqlite3Select(pParse, pPrior, &uniondest);
94401 if( rc ){
94402 goto multi_select_end;
94405 /* Code the current SELECT statement
94407 if( p->op==TK_EXCEPT ){
94408 op = SRT_Except;
94409 }else{
94410 assert( p->op==TK_UNION );
94411 op = SRT_Union;
94413 p->pPrior = 0;
94414 pLimit = p->pLimit;
94415 p->pLimit = 0;
94416 pOffset = p->pOffset;
94417 p->pOffset = 0;
94418 uniondest.eDest = op;
94419 explainSetInteger(iSub2, pParse->iNextSelectId);
94420 rc = sqlite3Select(pParse, p, &uniondest);
94421 testcase( rc!=SQLITE_OK );
94422 /* Query flattening in sqlite3Select() might refill p->pOrderBy.
94423 ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
94424 sqlite3ExprListDelete(db, p->pOrderBy);
94425 pDelete = p->pPrior;
94426 p->pPrior = pPrior;
94427 p->pOrderBy = 0;
94428 if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;
94429 sqlite3ExprDelete(db, p->pLimit);
94430 p->pLimit = pLimit;
94431 p->pOffset = pOffset;
94432 p->iLimit = 0;
94433 p->iOffset = 0;
94435 /* Convert the data in the temporary table into whatever form
94436 ** it is that we currently need.
94438 assert( unionTab==dest.iParm || dest.eDest!=priorOp );
94439 if( dest.eDest!=priorOp ){
94440 int iCont, iBreak, iStart;
94441 assert( p->pEList );
94442 if( dest.eDest==SRT_Output ){
94443 Select *pFirst = p;
94444 while( pFirst->pPrior ) pFirst = pFirst->pPrior;
94445 generateColumnNames(pParse, 0, pFirst->pEList);
94447 iBreak = sqlite3VdbeMakeLabel(v);
94448 iCont = sqlite3VdbeMakeLabel(v);
94449 computeLimitRegisters(pParse, p, iBreak);
94450 sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
94451 iStart = sqlite3VdbeCurrentAddr(v);
94452 selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
94453 0, -1, &dest, iCont, iBreak);
94454 sqlite3VdbeResolveLabel(v, iCont);
94455 sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
94456 sqlite3VdbeResolveLabel(v, iBreak);
94457 sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
94459 break;
94461 default: assert( p->op==TK_INTERSECT ); {
94462 int tab1, tab2;
94463 int iCont, iBreak, iStart;
94464 Expr *pLimit, *pOffset;
94465 int addr;
94466 SelectDest intersectdest;
94467 int r1;
94469 /* INTERSECT is different from the others since it requires
94470 ** two temporary tables. Hence it has its own case. Begin
94471 ** by allocating the tables we will need.
94473 tab1 = pParse->nTab++;
94474 tab2 = pParse->nTab++;
94475 assert( p->pOrderBy==0 );
94477 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
94478 assert( p->addrOpenEphm[0] == -1 );
94479 p->addrOpenEphm[0] = addr;
94480 p->pRightmost->selFlags |= SF_UsesEphemeral;
94481 assert( p->pEList );
94483 /* Code the SELECTs to our left into temporary table "tab1".
94485 sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
94486 explainSetInteger(iSub1, pParse->iNextSelectId);
94487 rc = sqlite3Select(pParse, pPrior, &intersectdest);
94488 if( rc ){
94489 goto multi_select_end;
94492 /* Code the current SELECT into temporary table "tab2"
94494 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
94495 assert( p->addrOpenEphm[1] == -1 );
94496 p->addrOpenEphm[1] = addr;
94497 p->pPrior = 0;
94498 pLimit = p->pLimit;
94499 p->pLimit = 0;
94500 pOffset = p->pOffset;
94501 p->pOffset = 0;
94502 intersectdest.iParm = tab2;
94503 explainSetInteger(iSub2, pParse->iNextSelectId);
94504 rc = sqlite3Select(pParse, p, &intersectdest);
94505 testcase( rc!=SQLITE_OK );
94506 pDelete = p->pPrior;
94507 p->pPrior = pPrior;
94508 if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
94509 sqlite3ExprDelete(db, p->pLimit);
94510 p->pLimit = pLimit;
94511 p->pOffset = pOffset;
94513 /* Generate code to take the intersection of the two temporary
94514 ** tables.
94516 assert( p->pEList );
94517 if( dest.eDest==SRT_Output ){
94518 Select *pFirst = p;
94519 while( pFirst->pPrior ) pFirst = pFirst->pPrior;
94520 generateColumnNames(pParse, 0, pFirst->pEList);
94522 iBreak = sqlite3VdbeMakeLabel(v);
94523 iCont = sqlite3VdbeMakeLabel(v);
94524 computeLimitRegisters(pParse, p, iBreak);
94525 sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
94526 r1 = sqlite3GetTempReg(pParse);
94527 iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
94528 sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
94529 sqlite3ReleaseTempReg(pParse, r1);
94530 selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
94531 0, -1, &dest, iCont, iBreak);
94532 sqlite3VdbeResolveLabel(v, iCont);
94533 sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
94534 sqlite3VdbeResolveLabel(v, iBreak);
94535 sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
94536 sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
94537 break;
94541 explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
94543 /* Compute collating sequences used by
94544 ** temporary tables needed to implement the compound select.
94545 ** Attach the KeyInfo structure to all temporary tables.
94547 ** This section is run by the right-most SELECT statement only.
94548 ** SELECT statements to the left always skip this part. The right-most
94549 ** SELECT might also skip this part if it has no ORDER BY clause and
94550 ** no temp tables are required.
94552 if( p->selFlags & SF_UsesEphemeral ){
94553 int i; /* Loop counter */
94554 KeyInfo *pKeyInfo; /* Collating sequence for the result set */
94555 Select *pLoop; /* For looping through SELECT statements */
94556 CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */
94557 int nCol; /* Number of columns in result set */
94559 assert( p->pRightmost==p );
94560 nCol = p->pEList->nExpr;
94561 pKeyInfo = sqlite3DbMallocZero(db,
94562 sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1));
94563 if( !pKeyInfo ){
94564 rc = SQLITE_NOMEM;
94565 goto multi_select_end;
94568 pKeyInfo->enc = ENC(db);
94569 pKeyInfo->nField = (u16)nCol;
94571 for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
94572 *apColl = multiSelectCollSeq(pParse, p, i);
94573 if( 0==*apColl ){
94574 *apColl = db->pDfltColl;
94578 for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
94579 for(i=0; i<2; i++){
94580 int addr = pLoop->addrOpenEphm[i];
94581 if( addr<0 ){
94582 /* If [0] is unused then [1] is also unused. So we can
94583 ** always safely abort as soon as the first unused slot is found */
94584 assert( pLoop->addrOpenEphm[1]<0 );
94585 break;
94587 sqlite3VdbeChangeP2(v, addr, nCol);
94588 sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
94589 pLoop->addrOpenEphm[i] = -1;
94592 sqlite3DbFree(db, pKeyInfo);
94595 multi_select_end:
94596 pDest->iMem = dest.iMem;
94597 pDest->nMem = dest.nMem;
94598 sqlite3SelectDelete(db, pDelete);
94599 return rc;
94601 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
94604 ** Code an output subroutine for a coroutine implementation of a
94605 ** SELECT statment.
94607 ** The data to be output is contained in pIn->iMem. There are
94608 ** pIn->nMem columns to be output. pDest is where the output should
94609 ** be sent.
94611 ** regReturn is the number of the register holding the subroutine
94612 ** return address.
94614 ** If regPrev>0 then it is the first register in a vector that
94615 ** records the previous output. mem[regPrev] is a flag that is false
94616 ** if there has been no previous output. If regPrev>0 then code is
94617 ** generated to suppress duplicates. pKeyInfo is used for comparing
94618 ** keys.
94620 ** If the LIMIT found in p->iLimit is reached, jump immediately to
94621 ** iBreak.
94623 static int generateOutputSubroutine(
94624 Parse *pParse, /* Parsing context */
94625 Select *p, /* The SELECT statement */
94626 SelectDest *pIn, /* Coroutine supplying data */
94627 SelectDest *pDest, /* Where to send the data */
94628 int regReturn, /* The return address register */
94629 int regPrev, /* Previous result register. No uniqueness if 0 */
94630 KeyInfo *pKeyInfo, /* For comparing with previous entry */
94631 int p4type, /* The p4 type for pKeyInfo */
94632 int iBreak /* Jump here if we hit the LIMIT */
94634 Vdbe *v = pParse->pVdbe;
94635 int iContinue;
94636 int addr;
94638 addr = sqlite3VdbeCurrentAddr(v);
94639 iContinue = sqlite3VdbeMakeLabel(v);
94641 /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
94643 if( regPrev ){
94644 int j1, j2;
94645 j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
94646 j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iMem, regPrev+1, pIn->nMem,
94647 (char*)pKeyInfo, p4type);
94648 sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
94649 sqlite3VdbeJumpHere(v, j1);
94650 sqlite3ExprCodeCopy(pParse, pIn->iMem, regPrev+1, pIn->nMem);
94651 sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
94653 if( pParse->db->mallocFailed ) return 0;
94655 /* Suppress the the first OFFSET entries if there is an OFFSET clause
94657 codeOffset(v, p, iContinue);
94659 switch( pDest->eDest ){
94660 /* Store the result as data using a unique key.
94662 case SRT_Table:
94663 case SRT_EphemTab: {
94664 int r1 = sqlite3GetTempReg(pParse);
94665 int r2 = sqlite3GetTempReg(pParse);
94666 testcase( pDest->eDest==SRT_Table );
94667 testcase( pDest->eDest==SRT_EphemTab );
94668 sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iMem, pIn->nMem, r1);
94669 sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iParm, r2);
94670 sqlite3VdbeAddOp3(v, OP_Insert, pDest->iParm, r1, r2);
94671 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
94672 sqlite3ReleaseTempReg(pParse, r2);
94673 sqlite3ReleaseTempReg(pParse, r1);
94674 break;
94677 #ifndef SQLITE_OMIT_SUBQUERY
94678 /* If we are creating a set for an "expr IN (SELECT ...)" construct,
94679 ** then there should be a single item on the stack. Write this
94680 ** item into the set table with bogus data.
94682 case SRT_Set: {
94683 int r1;
94684 assert( pIn->nMem==1 );
94685 p->affinity =
94686 sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affinity);
94687 r1 = sqlite3GetTempReg(pParse);
94688 sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iMem, 1, r1, &p->affinity, 1);
94689 sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, 1);
94690 sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iParm, r1);
94691 sqlite3ReleaseTempReg(pParse, r1);
94692 break;
94695 #if 0 /* Never occurs on an ORDER BY query */
94696 /* If any row exist in the result set, record that fact and abort.
94698 case SRT_Exists: {
94699 sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iParm);
94700 /* The LIMIT clause will terminate the loop for us */
94701 break;
94703 #endif
94705 /* If this is a scalar select that is part of an expression, then
94706 ** store the results in the appropriate memory cell and break out
94707 ** of the scan loop.
94709 case SRT_Mem: {
94710 assert( pIn->nMem==1 );
94711 sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iParm, 1);
94712 /* The LIMIT clause will jump out of the loop for us */
94713 break;
94715 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
94717 /* The results are stored in a sequence of registers
94718 ** starting at pDest->iMem. Then the co-routine yields.
94720 case SRT_Coroutine: {
94721 if( pDest->iMem==0 ){
94722 pDest->iMem = sqlite3GetTempRange(pParse, pIn->nMem);
94723 pDest->nMem = pIn->nMem;
94725 sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iMem, pDest->nMem);
94726 sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
94727 break;
94730 /* If none of the above, then the result destination must be
94731 ** SRT_Output. This routine is never called with any other
94732 ** destination other than the ones handled above or SRT_Output.
94734 ** For SRT_Output, results are stored in a sequence of registers.
94735 ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
94736 ** return the next row of result.
94738 default: {
94739 assert( pDest->eDest==SRT_Output );
94740 sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iMem, pIn->nMem);
94741 sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, pIn->nMem);
94742 break;
94746 /* Jump to the end of the loop if the LIMIT is reached.
94748 if( p->iLimit ){
94749 sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
94752 /* Generate the subroutine return
94754 sqlite3VdbeResolveLabel(v, iContinue);
94755 sqlite3VdbeAddOp1(v, OP_Return, regReturn);
94757 return addr;
94761 ** Alternative compound select code generator for cases when there
94762 ** is an ORDER BY clause.
94764 ** We assume a query of the following form:
94766 ** <selectA> <operator> <selectB> ORDER BY <orderbylist>
94768 ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea
94769 ** is to code both <selectA> and <selectB> with the ORDER BY clause as
94770 ** co-routines. Then run the co-routines in parallel and merge the results
94771 ** into the output. In addition to the two coroutines (called selectA and
94772 ** selectB) there are 7 subroutines:
94774 ** outA: Move the output of the selectA coroutine into the output
94775 ** of the compound query.
94777 ** outB: Move the output of the selectB coroutine into the output
94778 ** of the compound query. (Only generated for UNION and
94779 ** UNION ALL. EXCEPT and INSERTSECT never output a row that
94780 ** appears only in B.)
94782 ** AltB: Called when there is data from both coroutines and A<B.
94784 ** AeqB: Called when there is data from both coroutines and A==B.
94786 ** AgtB: Called when there is data from both coroutines and A>B.
94788 ** EofA: Called when data is exhausted from selectA.
94790 ** EofB: Called when data is exhausted from selectB.
94792 ** The implementation of the latter five subroutines depend on which
94793 ** <operator> is used:
94796 ** UNION ALL UNION EXCEPT INTERSECT
94797 ** ------------- ----------------- -------------- -----------------
94798 ** AltB: outA, nextA outA, nextA outA, nextA nextA
94800 ** AeqB: outA, nextA nextA nextA outA, nextA
94802 ** AgtB: outB, nextB outB, nextB nextB nextB
94804 ** EofA: outB, nextB outB, nextB halt halt
94806 ** EofB: outA, nextA outA, nextA outA, nextA halt
94808 ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
94809 ** causes an immediate jump to EofA and an EOF on B following nextB causes
94810 ** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or
94811 ** following nextX causes a jump to the end of the select processing.
94813 ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
94814 ** within the output subroutine. The regPrev register set holds the previously
94815 ** output value. A comparison is made against this value and the output
94816 ** is skipped if the next results would be the same as the previous.
94818 ** The implementation plan is to implement the two coroutines and seven
94819 ** subroutines first, then put the control logic at the bottom. Like this:
94821 ** goto Init
94822 ** coA: coroutine for left query (A)
94823 ** coB: coroutine for right query (B)
94824 ** outA: output one row of A
94825 ** outB: output one row of B (UNION and UNION ALL only)
94826 ** EofA: ...
94827 ** EofB: ...
94828 ** AltB: ...
94829 ** AeqB: ...
94830 ** AgtB: ...
94831 ** Init: initialize coroutine registers
94832 ** yield coA
94833 ** if eof(A) goto EofA
94834 ** yield coB
94835 ** if eof(B) goto EofB
94836 ** Cmpr: Compare A, B
94837 ** Jump AltB, AeqB, AgtB
94838 ** End: ...
94840 ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
94841 ** actually called using Gosub and they do not Return. EofA and EofB loop
94842 ** until all data is exhausted then jump to the "end" labe. AltB, AeqB,
94843 ** and AgtB jump to either L2 or to one of EofA or EofB.
94845 #ifndef SQLITE_OMIT_COMPOUND_SELECT
94846 static int multiSelectOrderBy(
94847 Parse *pParse, /* Parsing context */
94848 Select *p, /* The right-most of SELECTs to be coded */
94849 SelectDest *pDest /* What to do with query results */
94851 int i, j; /* Loop counters */
94852 Select *pPrior; /* Another SELECT immediately to our left */
94853 Vdbe *v; /* Generate code to this VDBE */
94854 SelectDest destA; /* Destination for coroutine A */
94855 SelectDest destB; /* Destination for coroutine B */
94856 int regAddrA; /* Address register for select-A coroutine */
94857 int regEofA; /* Flag to indicate when select-A is complete */
94858 int regAddrB; /* Address register for select-B coroutine */
94859 int regEofB; /* Flag to indicate when select-B is complete */
94860 int addrSelectA; /* Address of the select-A coroutine */
94861 int addrSelectB; /* Address of the select-B coroutine */
94862 int regOutA; /* Address register for the output-A subroutine */
94863 int regOutB; /* Address register for the output-B subroutine */
94864 int addrOutA; /* Address of the output-A subroutine */
94865 int addrOutB = 0; /* Address of the output-B subroutine */
94866 int addrEofA; /* Address of the select-A-exhausted subroutine */
94867 int addrEofB; /* Address of the select-B-exhausted subroutine */
94868 int addrAltB; /* Address of the A<B subroutine */
94869 int addrAeqB; /* Address of the A==B subroutine */
94870 int addrAgtB; /* Address of the A>B subroutine */
94871 int regLimitA; /* Limit register for select-A */
94872 int regLimitB; /* Limit register for select-A */
94873 int regPrev; /* A range of registers to hold previous output */
94874 int savedLimit; /* Saved value of p->iLimit */
94875 int savedOffset; /* Saved value of p->iOffset */
94876 int labelCmpr; /* Label for the start of the merge algorithm */
94877 int labelEnd; /* Label for the end of the overall SELECT stmt */
94878 int j1; /* Jump instructions that get retargetted */
94879 int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
94880 KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
94881 KeyInfo *pKeyMerge; /* Comparison information for merging rows */
94882 sqlite3 *db; /* Database connection */
94883 ExprList *pOrderBy; /* The ORDER BY clause */
94884 int nOrderBy; /* Number of terms in the ORDER BY clause */
94885 int *aPermute; /* Mapping from ORDER BY terms to result set columns */
94886 #ifndef SQLITE_OMIT_EXPLAIN
94887 int iSub1; /* EQP id of left-hand query */
94888 int iSub2; /* EQP id of right-hand query */
94889 #endif
94891 assert( p->pOrderBy!=0 );
94892 assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */
94893 db = pParse->db;
94894 v = pParse->pVdbe;
94895 assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */
94896 labelEnd = sqlite3VdbeMakeLabel(v);
94897 labelCmpr = sqlite3VdbeMakeLabel(v);
94900 /* Patch up the ORDER BY clause
94902 op = p->op;
94903 pPrior = p->pPrior;
94904 assert( pPrior->pOrderBy==0 );
94905 pOrderBy = p->pOrderBy;
94906 assert( pOrderBy );
94907 nOrderBy = pOrderBy->nExpr;
94909 /* For operators other than UNION ALL we have to make sure that
94910 ** the ORDER BY clause covers every term of the result set. Add
94911 ** terms to the ORDER BY clause as necessary.
94913 if( op!=TK_ALL ){
94914 for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
94915 struct ExprList_item *pItem;
94916 for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
94917 assert( pItem->iCol>0 );
94918 if( pItem->iCol==i ) break;
94920 if( j==nOrderBy ){
94921 Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
94922 if( pNew==0 ) return SQLITE_NOMEM;
94923 pNew->flags |= EP_IntValue;
94924 pNew->u.iValue = i;
94925 pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
94926 pOrderBy->a[nOrderBy++].iCol = (u16)i;
94931 /* Compute the comparison permutation and keyinfo that is used with
94932 ** the permutation used to determine if the next
94933 ** row of results comes from selectA or selectB. Also add explicit
94934 ** collations to the ORDER BY clause terms so that when the subqueries
94935 ** to the right and the left are evaluated, they use the correct
94936 ** collation.
94938 aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
94939 if( aPermute ){
94940 struct ExprList_item *pItem;
94941 for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
94942 assert( pItem->iCol>0 && pItem->iCol<=p->pEList->nExpr );
94943 aPermute[i] = pItem->iCol - 1;
94945 pKeyMerge =
94946 sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1));
94947 if( pKeyMerge ){
94948 pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy];
94949 pKeyMerge->nField = (u16)nOrderBy;
94950 pKeyMerge->enc = ENC(db);
94951 for(i=0; i<nOrderBy; i++){
94952 CollSeq *pColl;
94953 Expr *pTerm = pOrderBy->a[i].pExpr;
94954 if( pTerm->flags & EP_ExpCollate ){
94955 pColl = pTerm->pColl;
94956 }else{
94957 pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
94958 pTerm->flags |= EP_ExpCollate;
94959 pTerm->pColl = pColl;
94961 pKeyMerge->aColl[i] = pColl;
94962 pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
94965 }else{
94966 pKeyMerge = 0;
94969 /* Reattach the ORDER BY clause to the query.
94971 p->pOrderBy = pOrderBy;
94972 pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
94974 /* Allocate a range of temporary registers and the KeyInfo needed
94975 ** for the logic that removes duplicate result rows when the
94976 ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
94978 if( op==TK_ALL ){
94979 regPrev = 0;
94980 }else{
94981 int nExpr = p->pEList->nExpr;
94982 assert( nOrderBy>=nExpr || db->mallocFailed );
94983 regPrev = sqlite3GetTempRange(pParse, nExpr+1);
94984 sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
94985 pKeyDup = sqlite3DbMallocZero(db,
94986 sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );
94987 if( pKeyDup ){
94988 pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];
94989 pKeyDup->nField = (u16)nExpr;
94990 pKeyDup->enc = ENC(db);
94991 for(i=0; i<nExpr; i++){
94992 pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
94993 pKeyDup->aSortOrder[i] = 0;
94998 /* Separate the left and the right query from one another
95000 p->pPrior = 0;
95001 sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
95002 if( pPrior->pPrior==0 ){
95003 sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
95006 /* Compute the limit registers */
95007 computeLimitRegisters(pParse, p, labelEnd);
95008 if( p->iLimit && op==TK_ALL ){
95009 regLimitA = ++pParse->nMem;
95010 regLimitB = ++pParse->nMem;
95011 sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
95012 regLimitA);
95013 sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
95014 }else{
95015 regLimitA = regLimitB = 0;
95017 sqlite3ExprDelete(db, p->pLimit);
95018 p->pLimit = 0;
95019 sqlite3ExprDelete(db, p->pOffset);
95020 p->pOffset = 0;
95022 regAddrA = ++pParse->nMem;
95023 regEofA = ++pParse->nMem;
95024 regAddrB = ++pParse->nMem;
95025 regEofB = ++pParse->nMem;
95026 regOutA = ++pParse->nMem;
95027 regOutB = ++pParse->nMem;
95028 sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
95029 sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
95031 /* Jump past the various subroutines and coroutines to the main
95032 ** merge loop
95034 j1 = sqlite3VdbeAddOp0(v, OP_Goto);
95035 addrSelectA = sqlite3VdbeCurrentAddr(v);
95038 /* Generate a coroutine to evaluate the SELECT statement to the
95039 ** left of the compound operator - the "A" select.
95041 VdbeNoopComment((v, "Begin coroutine for left SELECT"));
95042 pPrior->iLimit = regLimitA;
95043 explainSetInteger(iSub1, pParse->iNextSelectId);
95044 sqlite3Select(pParse, pPrior, &destA);
95045 sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
95046 sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
95047 VdbeNoopComment((v, "End coroutine for left SELECT"));
95049 /* Generate a coroutine to evaluate the SELECT statement on
95050 ** the right - the "B" select
95052 addrSelectB = sqlite3VdbeCurrentAddr(v);
95053 VdbeNoopComment((v, "Begin coroutine for right SELECT"));
95054 savedLimit = p->iLimit;
95055 savedOffset = p->iOffset;
95056 p->iLimit = regLimitB;
95057 p->iOffset = 0;
95058 explainSetInteger(iSub2, pParse->iNextSelectId);
95059 sqlite3Select(pParse, p, &destB);
95060 p->iLimit = savedLimit;
95061 p->iOffset = savedOffset;
95062 sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
95063 sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
95064 VdbeNoopComment((v, "End coroutine for right SELECT"));
95066 /* Generate a subroutine that outputs the current row of the A
95067 ** select as the next output row of the compound select.
95069 VdbeNoopComment((v, "Output routine for A"));
95070 addrOutA = generateOutputSubroutine(pParse,
95071 p, &destA, pDest, regOutA,
95072 regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
95074 /* Generate a subroutine that outputs the current row of the B
95075 ** select as the next output row of the compound select.
95077 if( op==TK_ALL || op==TK_UNION ){
95078 VdbeNoopComment((v, "Output routine for B"));
95079 addrOutB = generateOutputSubroutine(pParse,
95080 p, &destB, pDest, regOutB,
95081 regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
95084 /* Generate a subroutine to run when the results from select A
95085 ** are exhausted and only data in select B remains.
95087 VdbeNoopComment((v, "eof-A subroutine"));
95088 if( op==TK_EXCEPT || op==TK_INTERSECT ){
95089 addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
95090 }else{
95091 addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
95092 sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
95093 sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
95094 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
95095 p->nSelectRow += pPrior->nSelectRow;
95098 /* Generate a subroutine to run when the results from select B
95099 ** are exhausted and only data in select A remains.
95101 if( op==TK_INTERSECT ){
95102 addrEofB = addrEofA;
95103 if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
95104 }else{
95105 VdbeNoopComment((v, "eof-B subroutine"));
95106 addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
95107 sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
95108 sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
95109 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
95112 /* Generate code to handle the case of A<B
95114 VdbeNoopComment((v, "A-lt-B subroutine"));
95115 addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
95116 sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
95117 sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
95118 sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
95120 /* Generate code to handle the case of A==B
95122 if( op==TK_ALL ){
95123 addrAeqB = addrAltB;
95124 }else if( op==TK_INTERSECT ){
95125 addrAeqB = addrAltB;
95126 addrAltB++;
95127 }else{
95128 VdbeNoopComment((v, "A-eq-B subroutine"));
95129 addrAeqB =
95130 sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
95131 sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
95132 sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
95135 /* Generate code to handle the case of A>B
95137 VdbeNoopComment((v, "A-gt-B subroutine"));
95138 addrAgtB = sqlite3VdbeCurrentAddr(v);
95139 if( op==TK_ALL || op==TK_UNION ){
95140 sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
95142 sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
95143 sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
95144 sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
95146 /* This code runs once to initialize everything.
95148 sqlite3VdbeJumpHere(v, j1);
95149 sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
95150 sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
95151 sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
95152 sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
95153 sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
95154 sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
95156 /* Implement the main merge loop
95158 sqlite3VdbeResolveLabel(v, labelCmpr);
95159 sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
95160 sqlite3VdbeAddOp4(v, OP_Compare, destA.iMem, destB.iMem, nOrderBy,
95161 (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
95162 sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
95164 /* Release temporary registers
95166 if( regPrev ){
95167 sqlite3ReleaseTempRange(pParse, regPrev, nOrderBy+1);
95170 /* Jump to the this point in order to terminate the query.
95172 sqlite3VdbeResolveLabel(v, labelEnd);
95174 /* Set the number of output columns
95176 if( pDest->eDest==SRT_Output ){
95177 Select *pFirst = pPrior;
95178 while( pFirst->pPrior ) pFirst = pFirst->pPrior;
95179 generateColumnNames(pParse, 0, pFirst->pEList);
95182 /* Reassembly the compound query so that it will be freed correctly
95183 ** by the calling function */
95184 if( p->pPrior ){
95185 sqlite3SelectDelete(db, p->pPrior);
95187 p->pPrior = pPrior;
95189 /*** TBD: Insert subroutine calls to close cursors on incomplete
95190 **** subqueries ****/
95191 explainComposite(pParse, p->op, iSub1, iSub2, 0);
95192 return SQLITE_OK;
95194 #endif
95196 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
95197 /* Forward Declarations */
95198 static void substExprList(sqlite3*, ExprList*, int, ExprList*);
95199 static void substSelect(sqlite3*, Select *, int, ExprList *);
95202 ** Scan through the expression pExpr. Replace every reference to
95203 ** a column in table number iTable with a copy of the iColumn-th
95204 ** entry in pEList. (But leave references to the ROWID column
95205 ** unchanged.)
95207 ** This routine is part of the flattening procedure. A subquery
95208 ** whose result set is defined by pEList appears as entry in the
95209 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
95210 ** FORM clause entry is iTable. This routine make the necessary
95211 ** changes to pExpr so that it refers directly to the source table
95212 ** of the subquery rather the result set of the subquery.
95214 static Expr *substExpr(
95215 sqlite3 *db, /* Report malloc errors to this connection */
95216 Expr *pExpr, /* Expr in which substitution occurs */
95217 int iTable, /* Table to be substituted */
95218 ExprList *pEList /* Substitute expressions */
95220 if( pExpr==0 ) return 0;
95221 if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
95222 if( pExpr->iColumn<0 ){
95223 pExpr->op = TK_NULL;
95224 }else{
95225 Expr *pNew;
95226 assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
95227 assert( pExpr->pLeft==0 && pExpr->pRight==0 );
95228 pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
95229 if( pNew && pExpr->pColl ){
95230 pNew->pColl = pExpr->pColl;
95232 sqlite3ExprDelete(db, pExpr);
95233 pExpr = pNew;
95235 }else{
95236 pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
95237 pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
95238 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
95239 substSelect(db, pExpr->x.pSelect, iTable, pEList);
95240 }else{
95241 substExprList(db, pExpr->x.pList, iTable, pEList);
95244 return pExpr;
95246 static void substExprList(
95247 sqlite3 *db, /* Report malloc errors here */
95248 ExprList *pList, /* List to scan and in which to make substitutes */
95249 int iTable, /* Table to be substituted */
95250 ExprList *pEList /* Substitute values */
95252 int i;
95253 if( pList==0 ) return;
95254 for(i=0; i<pList->nExpr; i++){
95255 pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
95258 static void substSelect(
95259 sqlite3 *db, /* Report malloc errors here */
95260 Select *p, /* SELECT statement in which to make substitutions */
95261 int iTable, /* Table to be replaced */
95262 ExprList *pEList /* Substitute values */
95264 SrcList *pSrc;
95265 struct SrcList_item *pItem;
95266 int i;
95267 if( !p ) return;
95268 substExprList(db, p->pEList, iTable, pEList);
95269 substExprList(db, p->pGroupBy, iTable, pEList);
95270 substExprList(db, p->pOrderBy, iTable, pEList);
95271 p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
95272 p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
95273 substSelect(db, p->pPrior, iTable, pEList);
95274 pSrc = p->pSrc;
95275 assert( pSrc ); /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
95276 if( ALWAYS(pSrc) ){
95277 for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
95278 substSelect(db, pItem->pSelect, iTable, pEList);
95282 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
95284 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
95286 ** This routine attempts to flatten subqueries in order to speed
95287 ** execution. It returns 1 if it makes changes and 0 if no flattening
95288 ** occurs.
95290 ** To understand the concept of flattening, consider the following
95291 ** query:
95293 ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
95295 ** The default way of implementing this query is to execute the
95296 ** subquery first and store the results in a temporary table, then
95297 ** run the outer query on that temporary table. This requires two
95298 ** passes over the data. Furthermore, because the temporary table
95299 ** has no indices, the WHERE clause on the outer query cannot be
95300 ** optimized.
95302 ** This routine attempts to rewrite queries such as the above into
95303 ** a single flat select, like this:
95305 ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
95307 ** The code generated for this simpification gives the same result
95308 ** but only has to scan the data once. And because indices might
95309 ** exist on the table t1, a complete scan of the data might be
95310 ** avoided.
95312 ** Flattening is only attempted if all of the following are true:
95314 ** (1) The subquery and the outer query do not both use aggregates.
95316 ** (2) The subquery is not an aggregate or the outer query is not a join.
95318 ** (3) The subquery is not the right operand of a left outer join
95319 ** (Originally ticket #306. Strengthened by ticket #3300)
95321 ** (4) The subquery is not DISTINCT.
95323 ** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT
95324 ** sub-queries that were excluded from this optimization. Restriction
95325 ** (4) has since been expanded to exclude all DISTINCT subqueries.
95327 ** (6) The subquery does not use aggregates or the outer query is not
95328 ** DISTINCT.
95330 ** (7) The subquery has a FROM clause.
95332 ** (8) The subquery does not use LIMIT or the outer query is not a join.
95334 ** (9) The subquery does not use LIMIT or the outer query does not use
95335 ** aggregates.
95337 ** (10) The subquery does not use aggregates or the outer query does not
95338 ** use LIMIT.
95340 ** (11) The subquery and the outer query do not both have ORDER BY clauses.
95342 ** (**) Not implemented. Subsumed into restriction (3). Was previously
95343 ** a separate restriction deriving from ticket #350.
95345 ** (13) The subquery and outer query do not both use LIMIT.
95347 ** (14) The subquery does not use OFFSET.
95349 ** (15) The outer query is not part of a compound select or the
95350 ** subquery does not have a LIMIT clause.
95351 ** (See ticket #2339 and ticket [02a8e81d44]).
95353 ** (16) The outer query is not an aggregate or the subquery does
95354 ** not contain ORDER BY. (Ticket #2942) This used to not matter
95355 ** until we introduced the group_concat() function.
95357 ** (17) The sub-query is not a compound select, or it is a UNION ALL
95358 ** compound clause made up entirely of non-aggregate queries, and
95359 ** the parent query:
95361 ** * is not itself part of a compound select,
95362 ** * is not an aggregate or DISTINCT query, and
95363 ** * has no other tables or sub-selects in the FROM clause.
95365 ** The parent and sub-query may contain WHERE clauses. Subject to
95366 ** rules (11), (13) and (14), they may also contain ORDER BY,
95367 ** LIMIT and OFFSET clauses.
95369 ** (18) If the sub-query is a compound select, then all terms of the
95370 ** ORDER by clause of the parent must be simple references to
95371 ** columns of the sub-query.
95373 ** (19) The subquery does not use LIMIT or the outer query does not
95374 ** have a WHERE clause.
95376 ** (20) If the sub-query is a compound select, then it must not use
95377 ** an ORDER BY clause. Ticket #3773. We could relax this constraint
95378 ** somewhat by saying that the terms of the ORDER BY clause must
95379 ** appear as unmodified result columns in the outer query. But
95380 ** have other optimizations in mind to deal with that case.
95382 ** (21) The subquery does not use LIMIT or the outer query is not
95383 ** DISTINCT. (See ticket [752e1646fc]).
95385 ** In this routine, the "p" parameter is a pointer to the outer query.
95386 ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
95387 ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
95389 ** If flattening is not attempted, this routine is a no-op and returns 0.
95390 ** If flattening is attempted this routine returns 1.
95392 ** All of the expression analysis must occur on both the outer query and
95393 ** the subquery before this routine runs.
95395 static int flattenSubquery(
95396 Parse *pParse, /* Parsing context */
95397 Select *p, /* The parent or outer SELECT statement */
95398 int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
95399 int isAgg, /* True if outer SELECT uses aggregate functions */
95400 int subqueryIsAgg /* True if the subquery uses aggregate functions */
95402 const char *zSavedAuthContext = pParse->zAuthContext;
95403 Select *pParent;
95404 Select *pSub; /* The inner query or "subquery" */
95405 Select *pSub1; /* Pointer to the rightmost select in sub-query */
95406 SrcList *pSrc; /* The FROM clause of the outer query */
95407 SrcList *pSubSrc; /* The FROM clause of the subquery */
95408 ExprList *pList; /* The result set of the outer query */
95409 int iParent; /* VDBE cursor number of the pSub result set temp table */
95410 int i; /* Loop counter */
95411 Expr *pWhere; /* The WHERE clause */
95412 struct SrcList_item *pSubitem; /* The subquery */
95413 sqlite3 *db = pParse->db;
95415 /* Check to see if flattening is permitted. Return 0 if not.
95417 assert( p!=0 );
95418 assert( p->pPrior==0 ); /* Unable to flatten compound queries */
95419 if( db->flags & SQLITE_QueryFlattener ) return 0;
95420 pSrc = p->pSrc;
95421 assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
95422 pSubitem = &pSrc->a[iFrom];
95423 iParent = pSubitem->iCursor;
95424 pSub = pSubitem->pSelect;
95425 assert( pSub!=0 );
95426 if( isAgg && subqueryIsAgg ) return 0; /* Restriction (1) */
95427 if( subqueryIsAgg && pSrc->nSrc>1 ) return 0; /* Restriction (2) */
95428 pSubSrc = pSub->pSrc;
95429 assert( pSubSrc );
95430 /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
95431 ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
95432 ** because they could be computed at compile-time. But when LIMIT and OFFSET
95433 ** became arbitrary expressions, we were forced to add restrictions (13)
95434 ** and (14). */
95435 if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */
95436 if( pSub->pOffset ) return 0; /* Restriction (14) */
95437 if( p->pRightmost && pSub->pLimit ){
95438 return 0; /* Restriction (15) */
95440 if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */
95441 if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (5) */
95442 if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
95443 return 0; /* Restrictions (8)(9) */
95445 if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
95446 return 0; /* Restriction (6) */
95448 if( p->pOrderBy && pSub->pOrderBy ){
95449 return 0; /* Restriction (11) */
95451 if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */
95452 if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */
95453 if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
95454 return 0; /* Restriction (21) */
95457 /* OBSOLETE COMMENT 1:
95458 ** Restriction 3: If the subquery is a join, make sure the subquery is
95459 ** not used as the right operand of an outer join. Examples of why this
95460 ** is not allowed:
95462 ** t1 LEFT OUTER JOIN (t2 JOIN t3)
95464 ** If we flatten the above, we would get
95466 ** (t1 LEFT OUTER JOIN t2) JOIN t3
95468 ** which is not at all the same thing.
95470 ** OBSOLETE COMMENT 2:
95471 ** Restriction 12: If the subquery is the right operand of a left outer
95472 ** join, make sure the subquery has no WHERE clause.
95473 ** An examples of why this is not allowed:
95475 ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
95477 ** If we flatten the above, we would get
95479 ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
95481 ** But the t2.x>0 test will always fail on a NULL row of t2, which
95482 ** effectively converts the OUTER JOIN into an INNER JOIN.
95484 ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
95485 ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
95486 ** is fraught with danger. Best to avoid the whole thing. If the
95487 ** subquery is the right term of a LEFT JOIN, then do not flatten.
95489 if( (pSubitem->jointype & JT_OUTER)!=0 ){
95490 return 0;
95493 /* Restriction 17: If the sub-query is a compound SELECT, then it must
95494 ** use only the UNION ALL operator. And none of the simple select queries
95495 ** that make up the compound SELECT are allowed to be aggregate or distinct
95496 ** queries.
95498 if( pSub->pPrior ){
95499 if( pSub->pOrderBy ){
95500 return 0; /* Restriction 20 */
95502 if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
95503 return 0;
95505 for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
95506 testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
95507 testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
95508 if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
95509 || (pSub1->pPrior && pSub1->op!=TK_ALL)
95510 || NEVER(pSub1->pSrc==0) || pSub1->pSrc->nSrc!=1
95512 return 0;
95516 /* Restriction 18. */
95517 if( p->pOrderBy ){
95518 int ii;
95519 for(ii=0; ii<p->pOrderBy->nExpr; ii++){
95520 if( p->pOrderBy->a[ii].iCol==0 ) return 0;
95525 /***** If we reach this point, flattening is permitted. *****/
95527 /* Authorize the subquery */
95528 pParse->zAuthContext = pSubitem->zName;
95529 sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
95530 pParse->zAuthContext = zSavedAuthContext;
95532 /* If the sub-query is a compound SELECT statement, then (by restrictions
95533 ** 17 and 18 above) it must be a UNION ALL and the parent query must
95534 ** be of the form:
95536 ** SELECT <expr-list> FROM (<sub-query>) <where-clause>
95538 ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
95539 ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
95540 ** OFFSET clauses and joins them to the left-hand-side of the original
95541 ** using UNION ALL operators. In this case N is the number of simple
95542 ** select statements in the compound sub-query.
95544 ** Example:
95546 ** SELECT a+1 FROM (
95547 ** SELECT x FROM tab
95548 ** UNION ALL
95549 ** SELECT y FROM tab
95550 ** UNION ALL
95551 ** SELECT abs(z*2) FROM tab2
95552 ** ) WHERE a!=5 ORDER BY 1
95554 ** Transformed into:
95556 ** SELECT x+1 FROM tab WHERE x+1!=5
95557 ** UNION ALL
95558 ** SELECT y+1 FROM tab WHERE y+1!=5
95559 ** UNION ALL
95560 ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
95561 ** ORDER BY 1
95563 ** We call this the "compound-subquery flattening".
95565 for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
95566 Select *pNew;
95567 ExprList *pOrderBy = p->pOrderBy;
95568 Expr *pLimit = p->pLimit;
95569 Select *pPrior = p->pPrior;
95570 p->pOrderBy = 0;
95571 p->pSrc = 0;
95572 p->pPrior = 0;
95573 p->pLimit = 0;
95574 pNew = sqlite3SelectDup(db, p, 0);
95575 p->pLimit = pLimit;
95576 p->pOrderBy = pOrderBy;
95577 p->pSrc = pSrc;
95578 p->op = TK_ALL;
95579 p->pRightmost = 0;
95580 if( pNew==0 ){
95581 pNew = pPrior;
95582 }else{
95583 pNew->pPrior = pPrior;
95584 pNew->pRightmost = 0;
95586 p->pPrior = pNew;
95587 if( db->mallocFailed ) return 1;
95590 /* Begin flattening the iFrom-th entry of the FROM clause
95591 ** in the outer query.
95593 pSub = pSub1 = pSubitem->pSelect;
95595 /* Delete the transient table structure associated with the
95596 ** subquery
95598 sqlite3DbFree(db, pSubitem->zDatabase);
95599 sqlite3DbFree(db, pSubitem->zName);
95600 sqlite3DbFree(db, pSubitem->zAlias);
95601 pSubitem->zDatabase = 0;
95602 pSubitem->zName = 0;
95603 pSubitem->zAlias = 0;
95604 pSubitem->pSelect = 0;
95606 /* Defer deleting the Table object associated with the
95607 ** subquery until code generation is
95608 ** complete, since there may still exist Expr.pTab entries that
95609 ** refer to the subquery even after flattening. Ticket #3346.
95611 ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
95613 if( ALWAYS(pSubitem->pTab!=0) ){
95614 Table *pTabToDel = pSubitem->pTab;
95615 if( pTabToDel->nRef==1 ){
95616 Parse *pToplevel = sqlite3ParseToplevel(pParse);
95617 pTabToDel->pNextZombie = pToplevel->pZombieTab;
95618 pToplevel->pZombieTab = pTabToDel;
95619 }else{
95620 pTabToDel->nRef--;
95622 pSubitem->pTab = 0;
95625 /* The following loop runs once for each term in a compound-subquery
95626 ** flattening (as described above). If we are doing a different kind
95627 ** of flattening - a flattening other than a compound-subquery flattening -
95628 ** then this loop only runs once.
95630 ** This loop moves all of the FROM elements of the subquery into the
95631 ** the FROM clause of the outer query. Before doing this, remember
95632 ** the cursor number for the original outer query FROM element in
95633 ** iParent. The iParent cursor will never be used. Subsequent code
95634 ** will scan expressions looking for iParent references and replace
95635 ** those references with expressions that resolve to the subquery FROM
95636 ** elements we are now copying in.
95638 for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
95639 int nSubSrc;
95640 u8 jointype = 0;
95641 pSubSrc = pSub->pSrc; /* FROM clause of subquery */
95642 nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */
95643 pSrc = pParent->pSrc; /* FROM clause of the outer query */
95645 if( pSrc ){
95646 assert( pParent==p ); /* First time through the loop */
95647 jointype = pSubitem->jointype;
95648 }else{
95649 assert( pParent!=p ); /* 2nd and subsequent times through the loop */
95650 pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
95651 if( pSrc==0 ){
95652 assert( db->mallocFailed );
95653 break;
95657 /* The subquery uses a single slot of the FROM clause of the outer
95658 ** query. If the subquery has more than one element in its FROM clause,
95659 ** then expand the outer query to make space for it to hold all elements
95660 ** of the subquery.
95662 ** Example:
95664 ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
95666 ** The outer query has 3 slots in its FROM clause. One slot of the
95667 ** outer query (the middle slot) is used by the subquery. The next
95668 ** block of code will expand the out query to 4 slots. The middle
95669 ** slot is expanded to two slots in order to make space for the
95670 ** two elements in the FROM clause of the subquery.
95672 if( nSubSrc>1 ){
95673 pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
95674 if( db->mallocFailed ){
95675 break;
95679 /* Transfer the FROM clause terms from the subquery into the
95680 ** outer query.
95682 for(i=0; i<nSubSrc; i++){
95683 sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
95684 pSrc->a[i+iFrom] = pSubSrc->a[i];
95685 memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
95687 pSrc->a[iFrom].jointype = jointype;
95689 /* Now begin substituting subquery result set expressions for
95690 ** references to the iParent in the outer query.
95692 ** Example:
95694 ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
95695 ** \ \_____________ subquery __________/ /
95696 ** \_____________________ outer query ______________________________/
95698 ** We look at every expression in the outer query and every place we see
95699 ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
95701 pList = pParent->pEList;
95702 for(i=0; i<pList->nExpr; i++){
95703 if( pList->a[i].zName==0 ){
95704 const char *zSpan = pList->a[i].zSpan;
95705 if( ALWAYS(zSpan) ){
95706 pList->a[i].zName = sqlite3DbStrDup(db, zSpan);
95710 substExprList(db, pParent->pEList, iParent, pSub->pEList);
95711 if( isAgg ){
95712 substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
95713 pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
95715 if( pSub->pOrderBy ){
95716 assert( pParent->pOrderBy==0 );
95717 pParent->pOrderBy = pSub->pOrderBy;
95718 pSub->pOrderBy = 0;
95719 }else if( pParent->pOrderBy ){
95720 substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
95722 if( pSub->pWhere ){
95723 pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
95724 }else{
95725 pWhere = 0;
95727 if( subqueryIsAgg ){
95728 assert( pParent->pHaving==0 );
95729 pParent->pHaving = pParent->pWhere;
95730 pParent->pWhere = pWhere;
95731 pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
95732 pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
95733 sqlite3ExprDup(db, pSub->pHaving, 0));
95734 assert( pParent->pGroupBy==0 );
95735 pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
95736 }else{
95737 pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
95738 pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
95741 /* The flattened query is distinct if either the inner or the
95742 ** outer query is distinct.
95744 pParent->selFlags |= pSub->selFlags & SF_Distinct;
95747 ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
95749 ** One is tempted to try to add a and b to combine the limits. But this
95750 ** does not work if either limit is negative.
95752 if( pSub->pLimit ){
95753 pParent->pLimit = pSub->pLimit;
95754 pSub->pLimit = 0;
95758 /* Finially, delete what is left of the subquery and return
95759 ** success.
95761 sqlite3SelectDelete(db, pSub1);
95763 return 1;
95765 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
95768 ** Analyze the SELECT statement passed as an argument to see if it
95769 ** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if
95770 ** it is, or 0 otherwise. At present, a query is considered to be
95771 ** a min()/max() query if:
95773 ** 1. There is a single object in the FROM clause.
95775 ** 2. There is a single expression in the result set, and it is
95776 ** either min(x) or max(x), where x is a column reference.
95778 static u8 minMaxQuery(Select *p){
95779 Expr *pExpr;
95780 ExprList *pEList = p->pEList;
95782 if( pEList->nExpr!=1 ) return WHERE_ORDERBY_NORMAL;
95783 pExpr = pEList->a[0].pExpr;
95784 if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
95785 if( NEVER(ExprHasProperty(pExpr, EP_xIsSelect)) ) return 0;
95786 pEList = pExpr->x.pList;
95787 if( pEList==0 || pEList->nExpr!=1 ) return 0;
95788 if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL;
95789 assert( !ExprHasProperty(pExpr, EP_IntValue) );
95790 if( sqlite3StrICmp(pExpr->u.zToken,"min")==0 ){
95791 return WHERE_ORDERBY_MIN;
95792 }else if( sqlite3StrICmp(pExpr->u.zToken,"max")==0 ){
95793 return WHERE_ORDERBY_MAX;
95795 return WHERE_ORDERBY_NORMAL;
95799 ** The select statement passed as the first argument is an aggregate query.
95800 ** The second argment is the associated aggregate-info object. This
95801 ** function tests if the SELECT is of the form:
95803 ** SELECT count(*) FROM <tbl>
95805 ** where table is a database table, not a sub-select or view. If the query
95806 ** does match this pattern, then a pointer to the Table object representing
95807 ** <tbl> is returned. Otherwise, 0 is returned.
95809 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
95810 Table *pTab;
95811 Expr *pExpr;
95813 assert( !p->pGroupBy );
95815 if( p->pWhere || p->pEList->nExpr!=1
95816 || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
95818 return 0;
95820 pTab = p->pSrc->a[0].pTab;
95821 pExpr = p->pEList->a[0].pExpr;
95822 assert( pTab && !pTab->pSelect && pExpr );
95824 if( IsVirtual(pTab) ) return 0;
95825 if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
95826 if( (pAggInfo->aFunc[0].pFunc->flags&SQLITE_FUNC_COUNT)==0 ) return 0;
95827 if( pExpr->flags&EP_Distinct ) return 0;
95829 return pTab;
95833 ** If the source-list item passed as an argument was augmented with an
95834 ** INDEXED BY clause, then try to locate the specified index. If there
95835 ** was such a clause and the named index cannot be found, return
95836 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
95837 ** pFrom->pIndex and return SQLITE_OK.
95839 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
95840 if( pFrom->pTab && pFrom->zIndex ){
95841 Table *pTab = pFrom->pTab;
95842 char *zIndex = pFrom->zIndex;
95843 Index *pIdx;
95844 for(pIdx=pTab->pIndex;
95845 pIdx && sqlite3StrICmp(pIdx->zName, zIndex);
95846 pIdx=pIdx->pNext
95848 if( !pIdx ){
95849 sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
95850 pParse->checkSchema = 1;
95851 return SQLITE_ERROR;
95853 pFrom->pIndex = pIdx;
95855 return SQLITE_OK;
95859 ** This routine is a Walker callback for "expanding" a SELECT statement.
95860 ** "Expanding" means to do the following:
95862 ** (1) Make sure VDBE cursor numbers have been assigned to every
95863 ** element of the FROM clause.
95865 ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
95866 ** defines FROM clause. When views appear in the FROM clause,
95867 ** fill pTabList->a[].pSelect with a copy of the SELECT statement
95868 ** that implements the view. A copy is made of the view's SELECT
95869 ** statement so that we can freely modify or delete that statement
95870 ** without worrying about messing up the presistent representation
95871 ** of the view.
95873 ** (3) Add terms to the WHERE clause to accomodate the NATURAL keyword
95874 ** on joins and the ON and USING clause of joins.
95876 ** (4) Scan the list of columns in the result set (pEList) looking
95877 ** for instances of the "*" operator or the TABLE.* operator.
95878 ** If found, expand each "*" to be every column in every table
95879 ** and TABLE.* to be every column in TABLE.
95882 static int selectExpander(Walker *pWalker, Select *p){
95883 Parse *pParse = pWalker->pParse;
95884 int i, j, k;
95885 SrcList *pTabList;
95886 ExprList *pEList;
95887 struct SrcList_item *pFrom;
95888 sqlite3 *db = pParse->db;
95890 if( db->mallocFailed ){
95891 return WRC_Abort;
95893 if( NEVER(p->pSrc==0) || (p->selFlags & SF_Expanded)!=0 ){
95894 return WRC_Prune;
95896 p->selFlags |= SF_Expanded;
95897 pTabList = p->pSrc;
95898 pEList = p->pEList;
95900 /* Make sure cursor numbers have been assigned to all entries in
95901 ** the FROM clause of the SELECT statement.
95903 sqlite3SrcListAssignCursors(pParse, pTabList);
95905 /* Look up every table named in the FROM clause of the select. If
95906 ** an entry of the FROM clause is a subquery instead of a table or view,
95907 ** then create a transient table structure to describe the subquery.
95909 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
95910 Table *pTab;
95911 if( pFrom->pTab!=0 ){
95912 /* This statement has already been prepared. There is no need
95913 ** to go further. */
95914 assert( i==0 );
95915 return WRC_Prune;
95917 if( pFrom->zName==0 ){
95918 #ifndef SQLITE_OMIT_SUBQUERY
95919 Select *pSel = pFrom->pSelect;
95920 /* A sub-query in the FROM clause of a SELECT */
95921 assert( pSel!=0 );
95922 assert( pFrom->pTab==0 );
95923 sqlite3WalkSelect(pWalker, pSel);
95924 pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
95925 if( pTab==0 ) return WRC_Abort;
95926 pTab->nRef = 1;
95927 pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab);
95928 while( pSel->pPrior ){ pSel = pSel->pPrior; }
95929 selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
95930 pTab->iPKey = -1;
95931 pTab->nRowEst = 1000000;
95932 pTab->tabFlags |= TF_Ephemeral;
95933 #endif
95934 }else{
95935 /* An ordinary table or view name in the FROM clause */
95936 assert( pFrom->pTab==0 );
95937 pFrom->pTab = pTab =
95938 sqlite3LocateTable(pParse,0,pFrom->zName,pFrom->zDatabase);
95939 if( pTab==0 ) return WRC_Abort;
95940 pTab->nRef++;
95941 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
95942 if( pTab->pSelect || IsVirtual(pTab) ){
95943 /* We reach here if the named table is a really a view */
95944 if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
95945 assert( pFrom->pSelect==0 );
95946 pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
95947 sqlite3WalkSelect(pWalker, pFrom->pSelect);
95949 #endif
95952 /* Locate the index named by the INDEXED BY clause, if any. */
95953 if( sqlite3IndexedByLookup(pParse, pFrom) ){
95954 return WRC_Abort;
95958 /* Process NATURAL keywords, and ON and USING clauses of joins.
95960 if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
95961 return WRC_Abort;
95964 /* For every "*" that occurs in the column list, insert the names of
95965 ** all columns in all tables. And for every TABLE.* insert the names
95966 ** of all columns in TABLE. The parser inserted a special expression
95967 ** with the TK_ALL operator for each "*" that it found in the column list.
95968 ** The following code just has to locate the TK_ALL expressions and expand
95969 ** each one to the list of all columns in all tables.
95971 ** The first loop just checks to see if there are any "*" operators
95972 ** that need expanding.
95974 for(k=0; k<pEList->nExpr; k++){
95975 Expr *pE = pEList->a[k].pExpr;
95976 if( pE->op==TK_ALL ) break;
95977 assert( pE->op!=TK_DOT || pE->pRight!=0 );
95978 assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
95979 if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
95981 if( k<pEList->nExpr ){
95983 ** If we get here it means the result set contains one or more "*"
95984 ** operators that need to be expanded. Loop through each expression
95985 ** in the result set and expand them one by one.
95987 struct ExprList_item *a = pEList->a;
95988 ExprList *pNew = 0;
95989 int flags = pParse->db->flags;
95990 int longNames = (flags & SQLITE_FullColNames)!=0
95991 && (flags & SQLITE_ShortColNames)==0;
95993 for(k=0; k<pEList->nExpr; k++){
95994 Expr *pE = a[k].pExpr;
95995 assert( pE->op!=TK_DOT || pE->pRight!=0 );
95996 if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pE->pRight->op!=TK_ALL) ){
95997 /* This particular expression does not need to be expanded.
95999 pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
96000 if( pNew ){
96001 pNew->a[pNew->nExpr-1].zName = a[k].zName;
96002 pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
96003 a[k].zName = 0;
96004 a[k].zSpan = 0;
96006 a[k].pExpr = 0;
96007 }else{
96008 /* This expression is a "*" or a "TABLE.*" and needs to be
96009 ** expanded. */
96010 int tableSeen = 0; /* Set to 1 when TABLE matches */
96011 char *zTName; /* text of name of TABLE */
96012 if( pE->op==TK_DOT ){
96013 assert( pE->pLeft!=0 );
96014 assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
96015 zTName = pE->pLeft->u.zToken;
96016 }else{
96017 zTName = 0;
96019 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
96020 Table *pTab = pFrom->pTab;
96021 char *zTabName = pFrom->zAlias;
96022 if( zTabName==0 ){
96023 zTabName = pTab->zName;
96025 if( db->mallocFailed ) break;
96026 if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
96027 continue;
96029 tableSeen = 1;
96030 for(j=0; j<pTab->nCol; j++){
96031 Expr *pExpr, *pRight;
96032 char *zName = pTab->aCol[j].zName;
96033 char *zColname; /* The computed column name */
96034 char *zToFree; /* Malloced string that needs to be freed */
96035 Token sColname; /* Computed column name as a token */
96037 /* If a column is marked as 'hidden' (currently only possible
96038 ** for virtual tables), do not include it in the expanded
96039 ** result-set list.
96041 if( IsHiddenColumn(&pTab->aCol[j]) ){
96042 assert(IsVirtual(pTab));
96043 continue;
96046 if( i>0 && zTName==0 ){
96047 if( (pFrom->jointype & JT_NATURAL)!=0
96048 && tableAndColumnIndex(pTabList, i, zName, 0, 0)
96050 /* In a NATURAL join, omit the join columns from the
96051 ** table to the right of the join */
96052 continue;
96054 if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
96055 /* In a join with a USING clause, omit columns in the
96056 ** using clause from the table on the right. */
96057 continue;
96060 pRight = sqlite3Expr(db, TK_ID, zName);
96061 zColname = zName;
96062 zToFree = 0;
96063 if( longNames || pTabList->nSrc>1 ){
96064 Expr *pLeft;
96065 pLeft = sqlite3Expr(db, TK_ID, zTabName);
96066 pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
96067 if( longNames ){
96068 zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
96069 zToFree = zColname;
96071 }else{
96072 pExpr = pRight;
96074 pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
96075 sColname.z = zColname;
96076 sColname.n = sqlite3Strlen30(zColname);
96077 sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
96078 sqlite3DbFree(db, zToFree);
96081 if( !tableSeen ){
96082 if( zTName ){
96083 sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
96084 }else{
96085 sqlite3ErrorMsg(pParse, "no tables specified");
96090 sqlite3ExprListDelete(db, pEList);
96091 p->pEList = pNew;
96093 #if SQLITE_MAX_COLUMN
96094 if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
96095 sqlite3ErrorMsg(pParse, "too many columns in result set");
96097 #endif
96098 return WRC_Continue;
96102 ** No-op routine for the parse-tree walker.
96104 ** When this routine is the Walker.xExprCallback then expression trees
96105 ** are walked without any actions being taken at each node. Presumably,
96106 ** when this routine is used for Walker.xExprCallback then
96107 ** Walker.xSelectCallback is set to do something useful for every
96108 ** subquery in the parser tree.
96110 static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
96111 UNUSED_PARAMETER2(NotUsed, NotUsed2);
96112 return WRC_Continue;
96116 ** This routine "expands" a SELECT statement and all of its subqueries.
96117 ** For additional information on what it means to "expand" a SELECT
96118 ** statement, see the comment on the selectExpand worker callback above.
96120 ** Expanding a SELECT statement is the first step in processing a
96121 ** SELECT statement. The SELECT statement must be expanded before
96122 ** name resolution is performed.
96124 ** If anything goes wrong, an error message is written into pParse.
96125 ** The calling function can detect the problem by looking at pParse->nErr
96126 ** and/or pParse->db->mallocFailed.
96128 static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
96129 Walker w;
96130 w.xSelectCallback = selectExpander;
96131 w.xExprCallback = exprWalkNoop;
96132 w.pParse = pParse;
96133 sqlite3WalkSelect(&w, pSelect);
96137 #ifndef SQLITE_OMIT_SUBQUERY
96139 ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
96140 ** interface.
96142 ** For each FROM-clause subquery, add Column.zType and Column.zColl
96143 ** information to the Table structure that represents the result set
96144 ** of that subquery.
96146 ** The Table structure that represents the result set was constructed
96147 ** by selectExpander() but the type and collation information was omitted
96148 ** at that point because identifiers had not yet been resolved. This
96149 ** routine is called after identifier resolution.
96151 static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
96152 Parse *pParse;
96153 int i;
96154 SrcList *pTabList;
96155 struct SrcList_item *pFrom;
96157 assert( p->selFlags & SF_Resolved );
96158 if( (p->selFlags & SF_HasTypeInfo)==0 ){
96159 p->selFlags |= SF_HasTypeInfo;
96160 pParse = pWalker->pParse;
96161 pTabList = p->pSrc;
96162 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
96163 Table *pTab = pFrom->pTab;
96164 if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
96165 /* A sub-query in the FROM clause of a SELECT */
96166 Select *pSel = pFrom->pSelect;
96167 assert( pSel );
96168 while( pSel->pPrior ) pSel = pSel->pPrior;
96169 selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel);
96173 return WRC_Continue;
96175 #endif
96179 ** This routine adds datatype and collating sequence information to
96180 ** the Table structures of all FROM-clause subqueries in a
96181 ** SELECT statement.
96183 ** Use this routine after name resolution.
96185 static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
96186 #ifndef SQLITE_OMIT_SUBQUERY
96187 Walker w;
96188 w.xSelectCallback = selectAddSubqueryTypeInfo;
96189 w.xExprCallback = exprWalkNoop;
96190 w.pParse = pParse;
96191 sqlite3WalkSelect(&w, pSelect);
96192 #endif
96197 ** This routine sets of a SELECT statement for processing. The
96198 ** following is accomplished:
96200 ** * VDBE Cursor numbers are assigned to all FROM-clause terms.
96201 ** * Ephemeral Table objects are created for all FROM-clause subqueries.
96202 ** * ON and USING clauses are shifted into WHERE statements
96203 ** * Wildcards "*" and "TABLE.*" in result sets are expanded.
96204 ** * Identifiers in expression are matched to tables.
96206 ** This routine acts recursively on all subqueries within the SELECT.
96208 SQLITE_PRIVATE void sqlite3SelectPrep(
96209 Parse *pParse, /* The parser context */
96210 Select *p, /* The SELECT statement being coded. */
96211 NameContext *pOuterNC /* Name context for container */
96213 sqlite3 *db;
96214 if( NEVER(p==0) ) return;
96215 db = pParse->db;
96216 if( p->selFlags & SF_HasTypeInfo ) return;
96217 sqlite3SelectExpand(pParse, p);
96218 if( pParse->nErr || db->mallocFailed ) return;
96219 sqlite3ResolveSelectNames(pParse, p, pOuterNC);
96220 if( pParse->nErr || db->mallocFailed ) return;
96221 sqlite3SelectAddTypeInfo(pParse, p);
96225 ** Reset the aggregate accumulator.
96227 ** The aggregate accumulator is a set of memory cells that hold
96228 ** intermediate results while calculating an aggregate. This
96229 ** routine simply stores NULLs in all of those memory cells.
96231 static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
96232 Vdbe *v = pParse->pVdbe;
96233 int i;
96234 struct AggInfo_func *pFunc;
96235 if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
96236 return;
96238 for(i=0; i<pAggInfo->nColumn; i++){
96239 sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
96241 for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
96242 sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
96243 if( pFunc->iDistinct>=0 ){
96244 Expr *pE = pFunc->pExpr;
96245 assert( !ExprHasProperty(pE, EP_xIsSelect) );
96246 if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
96247 sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
96248 "argument");
96249 pFunc->iDistinct = -1;
96250 }else{
96251 KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList);
96252 sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
96253 (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
96260 ** Invoke the OP_AggFinalize opcode for every aggregate function
96261 ** in the AggInfo structure.
96263 static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
96264 Vdbe *v = pParse->pVdbe;
96265 int i;
96266 struct AggInfo_func *pF;
96267 for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
96268 ExprList *pList = pF->pExpr->x.pList;
96269 assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
96270 sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
96271 (void*)pF->pFunc, P4_FUNCDEF);
96276 ** Update the accumulator memory cells for an aggregate based on
96277 ** the current cursor position.
96279 static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
96280 Vdbe *v = pParse->pVdbe;
96281 int i;
96282 struct AggInfo_func *pF;
96283 struct AggInfo_col *pC;
96285 pAggInfo->directMode = 1;
96286 sqlite3ExprCacheClear(pParse);
96287 for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
96288 int nArg;
96289 int addrNext = 0;
96290 int regAgg;
96291 ExprList *pList = pF->pExpr->x.pList;
96292 assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
96293 if( pList ){
96294 nArg = pList->nExpr;
96295 regAgg = sqlite3GetTempRange(pParse, nArg);
96296 sqlite3ExprCodeExprList(pParse, pList, regAgg, 1);
96297 }else{
96298 nArg = 0;
96299 regAgg = 0;
96301 if( pF->iDistinct>=0 ){
96302 addrNext = sqlite3VdbeMakeLabel(v);
96303 assert( nArg==1 );
96304 codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
96306 if( pF->pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
96307 CollSeq *pColl = 0;
96308 struct ExprList_item *pItem;
96309 int j;
96310 assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */
96311 for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
96312 pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
96314 if( !pColl ){
96315 pColl = pParse->db->pDfltColl;
96317 sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
96319 sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
96320 (void*)pF->pFunc, P4_FUNCDEF);
96321 sqlite3VdbeChangeP5(v, (u8)nArg);
96322 sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
96323 sqlite3ReleaseTempRange(pParse, regAgg, nArg);
96324 if( addrNext ){
96325 sqlite3VdbeResolveLabel(v, addrNext);
96326 sqlite3ExprCacheClear(pParse);
96330 /* Before populating the accumulator registers, clear the column cache.
96331 ** Otherwise, if any of the required column values are already present
96332 ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
96333 ** to pC->iMem. But by the time the value is used, the original register
96334 ** may have been used, invalidating the underlying buffer holding the
96335 ** text or blob value. See ticket [883034dcb5].
96337 ** Another solution would be to change the OP_SCopy used to copy cached
96338 ** values to an OP_Copy.
96340 sqlite3ExprCacheClear(pParse);
96341 for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
96342 sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
96344 pAggInfo->directMode = 0;
96345 sqlite3ExprCacheClear(pParse);
96349 ** Add a single OP_Explain instruction to the VDBE to explain a simple
96350 ** count(*) query ("SELECT count(*) FROM pTab").
96352 #ifndef SQLITE_OMIT_EXPLAIN
96353 static void explainSimpleCount(
96354 Parse *pParse, /* Parse context */
96355 Table *pTab, /* Table being queried */
96356 Index *pIdx /* Index used to optimize scan, or NULL */
96358 if( pParse->explain==2 ){
96359 char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s %s%s(~%d rows)",
96360 pTab->zName,
96361 pIdx ? "USING COVERING INDEX " : "",
96362 pIdx ? pIdx->zName : "",
96363 pTab->nRowEst
96365 sqlite3VdbeAddOp4(
96366 pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
96370 #else
96371 # define explainSimpleCount(a,b,c)
96372 #endif
96375 ** Generate code for the SELECT statement given in the p argument.
96377 ** The results are distributed in various ways depending on the
96378 ** contents of the SelectDest structure pointed to by argument pDest
96379 ** as follows:
96381 ** pDest->eDest Result
96382 ** ------------ -------------------------------------------
96383 ** SRT_Output Generate a row of output (using the OP_ResultRow
96384 ** opcode) for each row in the result set.
96386 ** SRT_Mem Only valid if the result is a single column.
96387 ** Store the first column of the first result row
96388 ** in register pDest->iParm then abandon the rest
96389 ** of the query. This destination implies "LIMIT 1".
96391 ** SRT_Set The result must be a single column. Store each
96392 ** row of result as the key in table pDest->iParm.
96393 ** Apply the affinity pDest->affinity before storing
96394 ** results. Used to implement "IN (SELECT ...)".
96396 ** SRT_Union Store results as a key in a temporary table pDest->iParm.
96398 ** SRT_Except Remove results from the temporary table pDest->iParm.
96400 ** SRT_Table Store results in temporary table pDest->iParm.
96401 ** This is like SRT_EphemTab except that the table
96402 ** is assumed to already be open.
96404 ** SRT_EphemTab Create an temporary table pDest->iParm and store
96405 ** the result there. The cursor is left open after
96406 ** returning. This is like SRT_Table except that
96407 ** this destination uses OP_OpenEphemeral to create
96408 ** the table first.
96410 ** SRT_Coroutine Generate a co-routine that returns a new row of
96411 ** results each time it is invoked. The entry point
96412 ** of the co-routine is stored in register pDest->iParm.
96414 ** SRT_Exists Store a 1 in memory cell pDest->iParm if the result
96415 ** set is not empty.
96417 ** SRT_Discard Throw the results away. This is used by SELECT
96418 ** statements within triggers whose only purpose is
96419 ** the side-effects of functions.
96421 ** This routine returns the number of errors. If any errors are
96422 ** encountered, then an appropriate error message is left in
96423 ** pParse->zErrMsg.
96425 ** This routine does NOT free the Select structure passed in. The
96426 ** calling function needs to do that.
96428 SQLITE_PRIVATE int sqlite3Select(
96429 Parse *pParse, /* The parser context */
96430 Select *p, /* The SELECT statement being coded. */
96431 SelectDest *pDest /* What to do with the query results */
96433 int i, j; /* Loop counters */
96434 WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */
96435 Vdbe *v; /* The virtual machine under construction */
96436 int isAgg; /* True for select lists like "count(*)" */
96437 ExprList *pEList; /* List of columns to extract. */
96438 SrcList *pTabList; /* List of tables to select from */
96439 Expr *pWhere; /* The WHERE clause. May be NULL */
96440 ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */
96441 ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
96442 Expr *pHaving; /* The HAVING clause. May be NULL */
96443 int isDistinct; /* True if the DISTINCT keyword is present */
96444 int distinct; /* Table to use for the distinct set */
96445 int rc = 1; /* Value to return from this function */
96446 int addrSortIndex; /* Address of an OP_OpenEphemeral instruction */
96447 int addrDistinctIndex; /* Address of an OP_OpenEphemeral instruction */
96448 AggInfo sAggInfo; /* Information used by aggregate queries */
96449 int iEnd; /* Address of the end of the query */
96450 sqlite3 *db; /* The database connection */
96452 #ifndef SQLITE_OMIT_EXPLAIN
96453 int iRestoreSelectId = pParse->iSelectId;
96454 pParse->iSelectId = pParse->iNextSelectId++;
96455 #endif
96457 db = pParse->db;
96458 if( p==0 || db->mallocFailed || pParse->nErr ){
96459 return 1;
96461 if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
96462 memset(&sAggInfo, 0, sizeof(sAggInfo));
96464 if( IgnorableOrderby(pDest) ){
96465 assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
96466 pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
96467 /* If ORDER BY makes no difference in the output then neither does
96468 ** DISTINCT so it can be removed too. */
96469 sqlite3ExprListDelete(db, p->pOrderBy);
96470 p->pOrderBy = 0;
96471 p->selFlags &= ~SF_Distinct;
96473 sqlite3SelectPrep(pParse, p, 0);
96474 pOrderBy = p->pOrderBy;
96475 pTabList = p->pSrc;
96476 pEList = p->pEList;
96477 if( pParse->nErr || db->mallocFailed ){
96478 goto select_end;
96480 isAgg = (p->selFlags & SF_Aggregate)!=0;
96481 assert( pEList!=0 );
96483 /* Begin generating code.
96485 v = sqlite3GetVdbe(pParse);
96486 if( v==0 ) goto select_end;
96488 /* If writing to memory or generating a set
96489 ** only a single column may be output.
96491 #ifndef SQLITE_OMIT_SUBQUERY
96492 if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
96493 goto select_end;
96495 #endif
96497 /* Generate code for all sub-queries in the FROM clause
96499 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
96500 for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
96501 struct SrcList_item *pItem = &pTabList->a[i];
96502 SelectDest dest;
96503 Select *pSub = pItem->pSelect;
96504 int isAggSub;
96506 if( pSub==0 ) continue;
96507 if( pItem->addrFillSub ){
96508 sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
96509 continue;
96512 /* Increment Parse.nHeight by the height of the largest expression
96513 ** tree refered to by this, the parent select. The child select
96514 ** may contain expression trees of at most
96515 ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
96516 ** more conservative than necessary, but much easier than enforcing
96517 ** an exact limit.
96519 pParse->nHeight += sqlite3SelectExprHeight(p);
96521 isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
96522 if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
96523 /* This subquery can be absorbed into its parent. */
96524 if( isAggSub ){
96525 isAgg = 1;
96526 p->selFlags |= SF_Aggregate;
96528 i = -1;
96529 }else{
96530 /* Generate a subroutine that will fill an ephemeral table with
96531 ** the content of this subquery. pItem->addrFillSub will point
96532 ** to the address of the generated subroutine. pItem->regReturn
96533 ** is a register allocated to hold the subroutine return address
96535 int topAddr;
96536 int onceAddr = 0;
96537 int retAddr;
96538 assert( pItem->addrFillSub==0 );
96539 pItem->regReturn = ++pParse->nMem;
96540 topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
96541 pItem->addrFillSub = topAddr+1;
96542 VdbeNoopComment((v, "materialize %s", pItem->pTab->zName));
96543 if( pItem->isCorrelated==0 && pParse->pTriggerTab==0 ){
96544 /* If the subquery is no correlated and if we are not inside of
96545 ** a trigger, then we only need to compute the value of the subquery
96546 ** once. */
96547 int regOnce = ++pParse->nMem;
96548 onceAddr = sqlite3VdbeAddOp1(v, OP_Once, regOnce);
96550 sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
96551 explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
96552 sqlite3Select(pParse, pSub, &dest);
96553 pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
96554 if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
96555 retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
96556 VdbeComment((v, "end %s", pItem->pTab->zName));
96557 sqlite3VdbeChangeP1(v, topAddr, retAddr);
96560 if( /*pParse->nErr ||*/ db->mallocFailed ){
96561 goto select_end;
96563 pParse->nHeight -= sqlite3SelectExprHeight(p);
96564 pTabList = p->pSrc;
96565 if( !IgnorableOrderby(pDest) ){
96566 pOrderBy = p->pOrderBy;
96569 pEList = p->pEList;
96570 #endif
96571 pWhere = p->pWhere;
96572 pGroupBy = p->pGroupBy;
96573 pHaving = p->pHaving;
96574 isDistinct = (p->selFlags & SF_Distinct)!=0;
96576 #ifndef SQLITE_OMIT_COMPOUND_SELECT
96577 /* If there is are a sequence of queries, do the earlier ones first.
96579 if( p->pPrior ){
96580 if( p->pRightmost==0 ){
96581 Select *pLoop, *pRight = 0;
96582 int cnt = 0;
96583 int mxSelect;
96584 for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
96585 pLoop->pRightmost = p;
96586 pLoop->pNext = pRight;
96587 pRight = pLoop;
96589 mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
96590 if( mxSelect && cnt>mxSelect ){
96591 sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
96592 goto select_end;
96595 rc = multiSelect(pParse, p, pDest);
96596 explainSetInteger(pParse->iSelectId, iRestoreSelectId);
96597 return rc;
96599 #endif
96601 /* If there is both a GROUP BY and an ORDER BY clause and they are
96602 ** identical, then disable the ORDER BY clause since the GROUP BY
96603 ** will cause elements to come out in the correct order. This is
96604 ** an optimization - the correct answer should result regardless.
96605 ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER
96606 ** to disable this optimization for testing purposes.
96608 if( sqlite3ExprListCompare(p->pGroupBy, pOrderBy)==0
96609 && (db->flags & SQLITE_GroupByOrder)==0 ){
96610 pOrderBy = 0;
96613 /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
96614 ** if the select-list is the same as the ORDER BY list, then this query
96615 ** can be rewritten as a GROUP BY. In other words, this:
96617 ** SELECT DISTINCT xyz FROM ... ORDER BY xyz
96619 ** is transformed to:
96621 ** SELECT xyz FROM ... GROUP BY xyz
96623 ** The second form is preferred as a single index (or temp-table) may be
96624 ** used for both the ORDER BY and DISTINCT processing. As originally
96625 ** written the query must use a temp-table for at least one of the ORDER
96626 ** BY and DISTINCT, and an index or separate temp-table for the other.
96628 if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
96629 && sqlite3ExprListCompare(pOrderBy, p->pEList)==0
96631 p->selFlags &= ~SF_Distinct;
96632 p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
96633 pGroupBy = p->pGroupBy;
96634 pOrderBy = 0;
96637 /* If there is an ORDER BY clause, then this sorting
96638 ** index might end up being unused if the data can be
96639 ** extracted in pre-sorted order. If that is the case, then the
96640 ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
96641 ** we figure out that the sorting index is not needed. The addrSortIndex
96642 ** variable is used to facilitate that change.
96644 if( pOrderBy ){
96645 KeyInfo *pKeyInfo;
96646 pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
96647 pOrderBy->iECursor = pParse->nTab++;
96648 p->addrOpenEphm[2] = addrSortIndex =
96649 sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
96650 pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
96651 (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
96652 }else{
96653 addrSortIndex = -1;
96656 /* If the output is destined for a temporary table, open that table.
96658 if( pDest->eDest==SRT_EphemTab ){
96659 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iParm, pEList->nExpr);
96662 /* Set the limiter.
96664 iEnd = sqlite3VdbeMakeLabel(v);
96665 p->nSelectRow = (double)LARGEST_INT64;
96666 computeLimitRegisters(pParse, p, iEnd);
96667 if( p->iLimit==0 && addrSortIndex>=0 ){
96668 sqlite3VdbeGetOp(v, addrSortIndex)->opcode = OP_SorterOpen;
96669 p->selFlags |= SF_UseSorter;
96672 /* Open a virtual index to use for the distinct set.
96674 if( p->selFlags & SF_Distinct ){
96675 KeyInfo *pKeyInfo;
96676 distinct = pParse->nTab++;
96677 pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
96678 addrDistinctIndex = sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0,
96679 (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
96680 sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
96681 }else{
96682 distinct = addrDistinctIndex = -1;
96685 /* Aggregate and non-aggregate queries are handled differently */
96686 if( !isAgg && pGroupBy==0 ){
96687 ExprList *pDist = (isDistinct ? p->pEList : 0);
96689 /* Begin the database scan. */
96690 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, pDist, 0);
96691 if( pWInfo==0 ) goto select_end;
96692 if( pWInfo->nRowOut < p->nSelectRow ) p->nSelectRow = pWInfo->nRowOut;
96694 /* If sorting index that was created by a prior OP_OpenEphemeral
96695 ** instruction ended up not being needed, then change the OP_OpenEphemeral
96696 ** into an OP_Noop.
96698 if( addrSortIndex>=0 && pOrderBy==0 ){
96699 sqlite3VdbeChangeToNoop(v, addrSortIndex);
96700 p->addrOpenEphm[2] = -1;
96703 if( pWInfo->eDistinct ){
96704 VdbeOp *pOp; /* No longer required OpenEphemeral instr. */
96706 assert( addrDistinctIndex>=0 );
96707 pOp = sqlite3VdbeGetOp(v, addrDistinctIndex);
96709 assert( isDistinct );
96710 assert( pWInfo->eDistinct==WHERE_DISTINCT_ORDERED
96711 || pWInfo->eDistinct==WHERE_DISTINCT_UNIQUE
96713 distinct = -1;
96714 if( pWInfo->eDistinct==WHERE_DISTINCT_ORDERED ){
96715 int iJump;
96716 int iExpr;
96717 int iFlag = ++pParse->nMem;
96718 int iBase = pParse->nMem+1;
96719 int iBase2 = iBase + pEList->nExpr;
96720 pParse->nMem += (pEList->nExpr*2);
96722 /* Change the OP_OpenEphemeral coded earlier to an OP_Integer. The
96723 ** OP_Integer initializes the "first row" flag. */
96724 pOp->opcode = OP_Integer;
96725 pOp->p1 = 1;
96726 pOp->p2 = iFlag;
96728 sqlite3ExprCodeExprList(pParse, pEList, iBase, 1);
96729 iJump = sqlite3VdbeCurrentAddr(v) + 1 + pEList->nExpr + 1 + 1;
96730 sqlite3VdbeAddOp2(v, OP_If, iFlag, iJump-1);
96731 for(iExpr=0; iExpr<pEList->nExpr; iExpr++){
96732 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[iExpr].pExpr);
96733 sqlite3VdbeAddOp3(v, OP_Ne, iBase+iExpr, iJump, iBase2+iExpr);
96734 sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
96735 sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
96737 sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iContinue);
96739 sqlite3VdbeAddOp2(v, OP_Integer, 0, iFlag);
96740 assert( sqlite3VdbeCurrentAddr(v)==iJump );
96741 sqlite3VdbeAddOp3(v, OP_Move, iBase, iBase2, pEList->nExpr);
96742 }else{
96743 pOp->opcode = OP_Noop;
96747 /* Use the standard inner loop. */
96748 selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, pDest,
96749 pWInfo->iContinue, pWInfo->iBreak);
96751 /* End the database scan loop.
96753 sqlite3WhereEnd(pWInfo);
96754 }else{
96755 /* This is the processing for aggregate queries */
96756 NameContext sNC; /* Name context for processing aggregate information */
96757 int iAMem; /* First Mem address for storing current GROUP BY */
96758 int iBMem; /* First Mem address for previous GROUP BY */
96759 int iUseFlag; /* Mem address holding flag indicating that at least
96760 ** one row of the input to the aggregator has been
96761 ** processed */
96762 int iAbortFlag; /* Mem address which causes query abort if positive */
96763 int groupBySort; /* Rows come from source in GROUP BY order */
96764 int addrEnd; /* End of processing for this SELECT */
96765 int sortPTab = 0; /* Pseudotable used to decode sorting results */
96766 int sortOut = 0; /* Output register from the sorter */
96768 /* Remove any and all aliases between the result set and the
96769 ** GROUP BY clause.
96771 if( pGroupBy ){
96772 int k; /* Loop counter */
96773 struct ExprList_item *pItem; /* For looping over expression in a list */
96775 for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
96776 pItem->iAlias = 0;
96778 for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
96779 pItem->iAlias = 0;
96781 if( p->nSelectRow>(double)100 ) p->nSelectRow = (double)100;
96782 }else{
96783 p->nSelectRow = (double)1;
96787 /* Create a label to jump to when we want to abort the query */
96788 addrEnd = sqlite3VdbeMakeLabel(v);
96790 /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
96791 ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
96792 ** SELECT statement.
96794 memset(&sNC, 0, sizeof(sNC));
96795 sNC.pParse = pParse;
96796 sNC.pSrcList = pTabList;
96797 sNC.pAggInfo = &sAggInfo;
96798 sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
96799 sAggInfo.pGroupBy = pGroupBy;
96800 sqlite3ExprAnalyzeAggList(&sNC, pEList);
96801 sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
96802 if( pHaving ){
96803 sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
96805 sAggInfo.nAccumulator = sAggInfo.nColumn;
96806 for(i=0; i<sAggInfo.nFunc; i++){
96807 assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
96808 sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
96810 if( db->mallocFailed ) goto select_end;
96812 /* Processing for aggregates with GROUP BY is very different and
96813 ** much more complex than aggregates without a GROUP BY.
96815 if( pGroupBy ){
96816 KeyInfo *pKeyInfo; /* Keying information for the group by clause */
96817 int j1; /* A-vs-B comparision jump */
96818 int addrOutputRow; /* Start of subroutine that outputs a result row */
96819 int regOutputRow; /* Return address register for output subroutine */
96820 int addrSetAbort; /* Set the abort flag and return */
96821 int addrTopOfLoop; /* Top of the input loop */
96822 int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
96823 int addrReset; /* Subroutine for resetting the accumulator */
96824 int regReset; /* Return address register for reset subroutine */
96826 /* If there is a GROUP BY clause we might need a sorting index to
96827 ** implement it. Allocate that sorting index now. If it turns out
96828 ** that we do not need it after all, the OP_SorterOpen instruction
96829 ** will be converted into a Noop.
96831 sAggInfo.sortingIdx = pParse->nTab++;
96832 pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
96833 addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
96834 sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
96835 0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
96837 /* Initialize memory locations used by GROUP BY aggregate processing
96839 iUseFlag = ++pParse->nMem;
96840 iAbortFlag = ++pParse->nMem;
96841 regOutputRow = ++pParse->nMem;
96842 addrOutputRow = sqlite3VdbeMakeLabel(v);
96843 regReset = ++pParse->nMem;
96844 addrReset = sqlite3VdbeMakeLabel(v);
96845 iAMem = pParse->nMem + 1;
96846 pParse->nMem += pGroupBy->nExpr;
96847 iBMem = pParse->nMem + 1;
96848 pParse->nMem += pGroupBy->nExpr;
96849 sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
96850 VdbeComment((v, "clear abort flag"));
96851 sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
96852 VdbeComment((v, "indicate accumulator empty"));
96854 /* Begin a loop that will extract all source rows in GROUP BY order.
96855 ** This might involve two separate loops with an OP_Sort in between, or
96856 ** it might be a single loop that uses an index to extract information
96857 ** in the right order to begin with.
96859 sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
96860 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0, 0);
96861 if( pWInfo==0 ) goto select_end;
96862 if( pGroupBy==0 ){
96863 /* The optimizer is able to deliver rows in group by order so
96864 ** we do not have to sort. The OP_OpenEphemeral table will be
96865 ** cancelled later because we still need to use the pKeyInfo
96867 pGroupBy = p->pGroupBy;
96868 groupBySort = 0;
96869 }else{
96870 /* Rows are coming out in undetermined order. We have to push
96871 ** each row into a sorting index, terminate the first loop,
96872 ** then loop over the sorting index in order to get the output
96873 ** in sorted order
96875 int regBase;
96876 int regRecord;
96877 int nCol;
96878 int nGroupBy;
96880 explainTempTable(pParse,
96881 isDistinct && !(p->selFlags&SF_Distinct)?"DISTINCT":"GROUP BY");
96883 groupBySort = 1;
96884 nGroupBy = pGroupBy->nExpr;
96885 nCol = nGroupBy + 1;
96886 j = nGroupBy+1;
96887 for(i=0; i<sAggInfo.nColumn; i++){
96888 if( sAggInfo.aCol[i].iSorterColumn>=j ){
96889 nCol++;
96890 j++;
96893 regBase = sqlite3GetTempRange(pParse, nCol);
96894 sqlite3ExprCacheClear(pParse);
96895 sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
96896 sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
96897 j = nGroupBy+1;
96898 for(i=0; i<sAggInfo.nColumn; i++){
96899 struct AggInfo_col *pCol = &sAggInfo.aCol[i];
96900 if( pCol->iSorterColumn>=j ){
96901 int r1 = j + regBase;
96902 int r2;
96904 r2 = sqlite3ExprCodeGetColumn(pParse,
96905 pCol->pTab, pCol->iColumn, pCol->iTable, r1);
96906 if( r1!=r2 ){
96907 sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
96909 j++;
96912 regRecord = sqlite3GetTempReg(pParse);
96913 sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
96914 sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
96915 sqlite3ReleaseTempReg(pParse, regRecord);
96916 sqlite3ReleaseTempRange(pParse, regBase, nCol);
96917 sqlite3WhereEnd(pWInfo);
96918 sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
96919 sortOut = sqlite3GetTempReg(pParse);
96920 sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
96921 sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
96922 VdbeComment((v, "GROUP BY sort"));
96923 sAggInfo.useSortingIdx = 1;
96924 sqlite3ExprCacheClear(pParse);
96927 /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
96928 ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
96929 ** Then compare the current GROUP BY terms against the GROUP BY terms
96930 ** from the previous row currently stored in a0, a1, a2...
96932 addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
96933 sqlite3ExprCacheClear(pParse);
96934 if( groupBySort ){
96935 sqlite3VdbeAddOp2(v, OP_SorterData, sAggInfo.sortingIdx, sortOut);
96937 for(j=0; j<pGroupBy->nExpr; j++){
96938 if( groupBySort ){
96939 sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
96940 if( j==0 ) sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
96941 }else{
96942 sAggInfo.directMode = 1;
96943 sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
96946 sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
96947 (char*)pKeyInfo, P4_KEYINFO);
96948 j1 = sqlite3VdbeCurrentAddr(v);
96949 sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
96951 /* Generate code that runs whenever the GROUP BY changes.
96952 ** Changes in the GROUP BY are detected by the previous code
96953 ** block. If there were no changes, this block is skipped.
96955 ** This code copies current group by terms in b0,b1,b2,...
96956 ** over to a0,a1,a2. It then calls the output subroutine
96957 ** and resets the aggregate accumulator registers in preparation
96958 ** for the next GROUP BY batch.
96960 sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
96961 sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
96962 VdbeComment((v, "output one row"));
96963 sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
96964 VdbeComment((v, "check abort flag"));
96965 sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
96966 VdbeComment((v, "reset accumulator"));
96968 /* Update the aggregate accumulators based on the content of
96969 ** the current row
96971 sqlite3VdbeJumpHere(v, j1);
96972 updateAccumulator(pParse, &sAggInfo);
96973 sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
96974 VdbeComment((v, "indicate data in accumulator"));
96976 /* End of the loop
96978 if( groupBySort ){
96979 sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
96980 }else{
96981 sqlite3WhereEnd(pWInfo);
96982 sqlite3VdbeChangeToNoop(v, addrSortingIdx);
96985 /* Output the final row of result
96987 sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
96988 VdbeComment((v, "output final row"));
96990 /* Jump over the subroutines
96992 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
96994 /* Generate a subroutine that outputs a single row of the result
96995 ** set. This subroutine first looks at the iUseFlag. If iUseFlag
96996 ** is less than or equal to zero, the subroutine is a no-op. If
96997 ** the processing calls for the query to abort, this subroutine
96998 ** increments the iAbortFlag memory location before returning in
96999 ** order to signal the caller to abort.
97001 addrSetAbort = sqlite3VdbeCurrentAddr(v);
97002 sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
97003 VdbeComment((v, "set abort flag"));
97004 sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
97005 sqlite3VdbeResolveLabel(v, addrOutputRow);
97006 addrOutputRow = sqlite3VdbeCurrentAddr(v);
97007 sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
97008 VdbeComment((v, "Groupby result generator entry point"));
97009 sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
97010 finalizeAggFunctions(pParse, &sAggInfo);
97011 sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
97012 selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
97013 distinct, pDest,
97014 addrOutputRow+1, addrSetAbort);
97015 sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
97016 VdbeComment((v, "end groupby result generator"));
97018 /* Generate a subroutine that will reset the group-by accumulator
97020 sqlite3VdbeResolveLabel(v, addrReset);
97021 resetAccumulator(pParse, &sAggInfo);
97022 sqlite3VdbeAddOp1(v, OP_Return, regReset);
97024 } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */
97025 else {
97026 ExprList *pDel = 0;
97027 #ifndef SQLITE_OMIT_BTREECOUNT
97028 Table *pTab;
97029 if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
97030 /* If isSimpleCount() returns a pointer to a Table structure, then
97031 ** the SQL statement is of the form:
97033 ** SELECT count(*) FROM <tbl>
97035 ** where the Table structure returned represents table <tbl>.
97037 ** This statement is so common that it is optimized specially. The
97038 ** OP_Count instruction is executed either on the intkey table that
97039 ** contains the data for table <tbl> or on one of its indexes. It
97040 ** is better to execute the op on an index, as indexes are almost
97041 ** always spread across less pages than their corresponding tables.
97043 const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
97044 const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */
97045 Index *pIdx; /* Iterator variable */
97046 KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */
97047 Index *pBest = 0; /* Best index found so far */
97048 int iRoot = pTab->tnum; /* Root page of scanned b-tree */
97050 sqlite3CodeVerifySchema(pParse, iDb);
97051 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
97053 /* Search for the index that has the least amount of columns. If
97054 ** there is such an index, and it has less columns than the table
97055 ** does, then we can assume that it consumes less space on disk and
97056 ** will therefore be cheaper to scan to determine the query result.
97057 ** In this case set iRoot to the root page number of the index b-tree
97058 ** and pKeyInfo to the KeyInfo structure required to navigate the
97059 ** index.
97061 ** (2011-04-15) Do not do a full scan of an unordered index.
97063 ** In practice the KeyInfo structure will not be used. It is only
97064 ** passed to keep OP_OpenRead happy.
97066 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
97067 if( pIdx->bUnordered==0 && (!pBest || pIdx->nColumn<pBest->nColumn) ){
97068 pBest = pIdx;
97071 if( pBest && pBest->nColumn<pTab->nCol ){
97072 iRoot = pBest->tnum;
97073 pKeyInfo = sqlite3IndexKeyinfo(pParse, pBest);
97076 /* Open a read-only cursor, execute the OP_Count, close the cursor. */
97077 sqlite3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb);
97078 if( pKeyInfo ){
97079 sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF);
97081 sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
97082 sqlite3VdbeAddOp1(v, OP_Close, iCsr);
97083 explainSimpleCount(pParse, pTab, pBest);
97084 }else
97085 #endif /* SQLITE_OMIT_BTREECOUNT */
97087 /* Check if the query is of one of the following forms:
97089 ** SELECT min(x) FROM ...
97090 ** SELECT max(x) FROM ...
97092 ** If it is, then ask the code in where.c to attempt to sort results
97093 ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
97094 ** If where.c is able to produce results sorted in this order, then
97095 ** add vdbe code to break out of the processing loop after the
97096 ** first iteration (since the first iteration of the loop is
97097 ** guaranteed to operate on the row with the minimum or maximum
97098 ** value of x, the only row required).
97100 ** A special flag must be passed to sqlite3WhereBegin() to slightly
97101 ** modify behaviour as follows:
97103 ** + If the query is a "SELECT min(x)", then the loop coded by
97104 ** where.c should not iterate over any values with a NULL value
97105 ** for x.
97107 ** + The optimizer code in where.c (the thing that decides which
97108 ** index or indices to use) should place a different priority on
97109 ** satisfying the 'ORDER BY' clause than it does in other cases.
97110 ** Refer to code and comments in where.c for details.
97112 ExprList *pMinMax = 0;
97113 u8 flag = minMaxQuery(p);
97114 if( flag ){
97115 assert( !ExprHasProperty(p->pEList->a[0].pExpr, EP_xIsSelect) );
97116 pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->x.pList,0);
97117 pDel = pMinMax;
97118 if( pMinMax && !db->mallocFailed ){
97119 pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
97120 pMinMax->a[0].pExpr->op = TK_COLUMN;
97124 /* This case runs if the aggregate has no GROUP BY clause. The
97125 ** processing is much simpler since there is only a single row
97126 ** of output.
97128 resetAccumulator(pParse, &sAggInfo);
97129 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax, 0, flag);
97130 if( pWInfo==0 ){
97131 sqlite3ExprListDelete(db, pDel);
97132 goto select_end;
97134 updateAccumulator(pParse, &sAggInfo);
97135 if( !pMinMax && flag ){
97136 sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
97137 VdbeComment((v, "%s() by index",
97138 (flag==WHERE_ORDERBY_MIN?"min":"max")));
97140 sqlite3WhereEnd(pWInfo);
97141 finalizeAggFunctions(pParse, &sAggInfo);
97144 pOrderBy = 0;
97145 sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
97146 selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1,
97147 pDest, addrEnd, addrEnd);
97148 sqlite3ExprListDelete(db, pDel);
97150 sqlite3VdbeResolveLabel(v, addrEnd);
97152 } /* endif aggregate query */
97154 if( distinct>=0 ){
97155 explainTempTable(pParse, "DISTINCT");
97158 /* If there is an ORDER BY clause, then we need to sort the results
97159 ** and send them to the callback one by one.
97161 if( pOrderBy ){
97162 explainTempTable(pParse, "ORDER BY");
97163 generateSortTail(pParse, p, v, pEList->nExpr, pDest);
97166 /* Jump here to skip this query
97168 sqlite3VdbeResolveLabel(v, iEnd);
97170 /* The SELECT was successfully coded. Set the return code to 0
97171 ** to indicate no errors.
97173 rc = 0;
97175 /* Control jumps to here if an error is encountered above, or upon
97176 ** successful coding of the SELECT.
97178 select_end:
97179 explainSetInteger(pParse->iSelectId, iRestoreSelectId);
97181 /* Identify column names if results of the SELECT are to be output.
97183 if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
97184 generateColumnNames(pParse, pTabList, pEList);
97187 sqlite3DbFree(db, sAggInfo.aCol);
97188 sqlite3DbFree(db, sAggInfo.aFunc);
97189 return rc;
97192 #if defined(SQLITE_DEBUG)
97194 *******************************************************************************
97195 ** The following code is used for testing and debugging only. The code
97196 ** that follows does not appear in normal builds.
97198 ** These routines are used to print out the content of all or part of a
97199 ** parse structures such as Select or Expr. Such printouts are useful
97200 ** for helping to understand what is happening inside the code generator
97201 ** during the execution of complex SELECT statements.
97203 ** These routine are not called anywhere from within the normal
97204 ** code base. Then are intended to be called from within the debugger
97205 ** or from temporary "printf" statements inserted for debugging.
97207 SQLITE_PRIVATE void sqlite3PrintExpr(Expr *p){
97208 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
97209 sqlite3DebugPrintf("(%s", p->u.zToken);
97210 }else{
97211 sqlite3DebugPrintf("(%d", p->op);
97213 if( p->pLeft ){
97214 sqlite3DebugPrintf(" ");
97215 sqlite3PrintExpr(p->pLeft);
97217 if( p->pRight ){
97218 sqlite3DebugPrintf(" ");
97219 sqlite3PrintExpr(p->pRight);
97221 sqlite3DebugPrintf(")");
97223 SQLITE_PRIVATE void sqlite3PrintExprList(ExprList *pList){
97224 int i;
97225 for(i=0; i<pList->nExpr; i++){
97226 sqlite3PrintExpr(pList->a[i].pExpr);
97227 if( i<pList->nExpr-1 ){
97228 sqlite3DebugPrintf(", ");
97232 SQLITE_PRIVATE void sqlite3PrintSelect(Select *p, int indent){
97233 sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p);
97234 sqlite3PrintExprList(p->pEList);
97235 sqlite3DebugPrintf("\n");
97236 if( p->pSrc ){
97237 char *zPrefix;
97238 int i;
97239 zPrefix = "FROM";
97240 for(i=0; i<p->pSrc->nSrc; i++){
97241 struct SrcList_item *pItem = &p->pSrc->a[i];
97242 sqlite3DebugPrintf("%*s ", indent+6, zPrefix);
97243 zPrefix = "";
97244 if( pItem->pSelect ){
97245 sqlite3DebugPrintf("(\n");
97246 sqlite3PrintSelect(pItem->pSelect, indent+10);
97247 sqlite3DebugPrintf("%*s)", indent+8, "");
97248 }else if( pItem->zName ){
97249 sqlite3DebugPrintf("%s", pItem->zName);
97251 if( pItem->pTab ){
97252 sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName);
97254 if( pItem->zAlias ){
97255 sqlite3DebugPrintf(" AS %s", pItem->zAlias);
97257 if( i<p->pSrc->nSrc-1 ){
97258 sqlite3DebugPrintf(",");
97260 sqlite3DebugPrintf("\n");
97263 if( p->pWhere ){
97264 sqlite3DebugPrintf("%*s WHERE ", indent, "");
97265 sqlite3PrintExpr(p->pWhere);
97266 sqlite3DebugPrintf("\n");
97268 if( p->pGroupBy ){
97269 sqlite3DebugPrintf("%*s GROUP BY ", indent, "");
97270 sqlite3PrintExprList(p->pGroupBy);
97271 sqlite3DebugPrintf("\n");
97273 if( p->pHaving ){
97274 sqlite3DebugPrintf("%*s HAVING ", indent, "");
97275 sqlite3PrintExpr(p->pHaving);
97276 sqlite3DebugPrintf("\n");
97278 if( p->pOrderBy ){
97279 sqlite3DebugPrintf("%*s ORDER BY ", indent, "");
97280 sqlite3PrintExprList(p->pOrderBy);
97281 sqlite3DebugPrintf("\n");
97284 /* End of the structure debug printing code
97285 *****************************************************************************/
97286 #endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
97288 /************** End of select.c **********************************************/
97289 /************** Begin file table.c *******************************************/
97291 ** 2001 September 15
97293 ** The author disclaims copyright to this source code. In place of
97294 ** a legal notice, here is a blessing:
97296 ** May you do good and not evil.
97297 ** May you find forgiveness for yourself and forgive others.
97298 ** May you share freely, never taking more than you give.
97300 *************************************************************************
97301 ** This file contains the sqlite3_get_table() and sqlite3_free_table()
97302 ** interface routines. These are just wrappers around the main
97303 ** interface routine of sqlite3_exec().
97305 ** These routines are in a separate files so that they will not be linked
97306 ** if they are not used.
97308 /* #include <stdlib.h> */
97309 /* #include <string.h> */
97311 #ifndef SQLITE_OMIT_GET_TABLE
97314 ** This structure is used to pass data from sqlite3_get_table() through
97315 ** to the callback function is uses to build the result.
97317 typedef struct TabResult {
97318 char **azResult; /* Accumulated output */
97319 char *zErrMsg; /* Error message text, if an error occurs */
97320 int nAlloc; /* Slots allocated for azResult[] */
97321 int nRow; /* Number of rows in the result */
97322 int nColumn; /* Number of columns in the result */
97323 int nData; /* Slots used in azResult[]. (nRow+1)*nColumn */
97324 int rc; /* Return code from sqlite3_exec() */
97325 } TabResult;
97328 ** This routine is called once for each row in the result table. Its job
97329 ** is to fill in the TabResult structure appropriately, allocating new
97330 ** memory as necessary.
97332 static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
97333 TabResult *p = (TabResult*)pArg; /* Result accumulator */
97334 int need; /* Slots needed in p->azResult[] */
97335 int i; /* Loop counter */
97336 char *z; /* A single column of result */
97338 /* Make sure there is enough space in p->azResult to hold everything
97339 ** we need to remember from this invocation of the callback.
97341 if( p->nRow==0 && argv!=0 ){
97342 need = nCol*2;
97343 }else{
97344 need = nCol;
97346 if( p->nData + need > p->nAlloc ){
97347 char **azNew;
97348 p->nAlloc = p->nAlloc*2 + need;
97349 azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
97350 if( azNew==0 ) goto malloc_failed;
97351 p->azResult = azNew;
97354 /* If this is the first row, then generate an extra row containing
97355 ** the names of all columns.
97357 if( p->nRow==0 ){
97358 p->nColumn = nCol;
97359 for(i=0; i<nCol; i++){
97360 z = sqlite3_mprintf("%s", colv[i]);
97361 if( z==0 ) goto malloc_failed;
97362 p->azResult[p->nData++] = z;
97364 }else if( p->nColumn!=nCol ){
97365 sqlite3_free(p->zErrMsg);
97366 p->zErrMsg = sqlite3_mprintf(
97367 "sqlite3_get_table() called with two or more incompatible queries"
97369 p->rc = SQLITE_ERROR;
97370 return 1;
97373 /* Copy over the row data
97375 if( argv!=0 ){
97376 for(i=0; i<nCol; i++){
97377 if( argv[i]==0 ){
97378 z = 0;
97379 }else{
97380 int n = sqlite3Strlen30(argv[i])+1;
97381 z = sqlite3_malloc( n );
97382 if( z==0 ) goto malloc_failed;
97383 memcpy(z, argv[i], n);
97385 p->azResult[p->nData++] = z;
97387 p->nRow++;
97389 return 0;
97391 malloc_failed:
97392 p->rc = SQLITE_NOMEM;
97393 return 1;
97397 ** Query the database. But instead of invoking a callback for each row,
97398 ** malloc() for space to hold the result and return the entire results
97399 ** at the conclusion of the call.
97401 ** The result that is written to ***pazResult is held in memory obtained
97402 ** from malloc(). But the caller cannot free this memory directly.
97403 ** Instead, the entire table should be passed to sqlite3_free_table() when
97404 ** the calling procedure is finished using it.
97406 SQLITE_API int sqlite3_get_table(
97407 sqlite3 *db, /* The database on which the SQL executes */
97408 const char *zSql, /* The SQL to be executed */
97409 char ***pazResult, /* Write the result table here */
97410 int *pnRow, /* Write the number of rows in the result here */
97411 int *pnColumn, /* Write the number of columns of result here */
97412 char **pzErrMsg /* Write error messages here */
97414 int rc;
97415 TabResult res;
97417 *pazResult = 0;
97418 if( pnColumn ) *pnColumn = 0;
97419 if( pnRow ) *pnRow = 0;
97420 if( pzErrMsg ) *pzErrMsg = 0;
97421 res.zErrMsg = 0;
97422 res.nRow = 0;
97423 res.nColumn = 0;
97424 res.nData = 1;
97425 res.nAlloc = 20;
97426 res.rc = SQLITE_OK;
97427 res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
97428 if( res.azResult==0 ){
97429 db->errCode = SQLITE_NOMEM;
97430 return SQLITE_NOMEM;
97432 res.azResult[0] = 0;
97433 rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
97434 assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
97435 res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
97436 if( (rc&0xff)==SQLITE_ABORT ){
97437 sqlite3_free_table(&res.azResult[1]);
97438 if( res.zErrMsg ){
97439 if( pzErrMsg ){
97440 sqlite3_free(*pzErrMsg);
97441 *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
97443 sqlite3_free(res.zErrMsg);
97445 db->errCode = res.rc; /* Assume 32-bit assignment is atomic */
97446 return res.rc;
97448 sqlite3_free(res.zErrMsg);
97449 if( rc!=SQLITE_OK ){
97450 sqlite3_free_table(&res.azResult[1]);
97451 return rc;
97453 if( res.nAlloc>res.nData ){
97454 char **azNew;
97455 azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData );
97456 if( azNew==0 ){
97457 sqlite3_free_table(&res.azResult[1]);
97458 db->errCode = SQLITE_NOMEM;
97459 return SQLITE_NOMEM;
97461 res.azResult = azNew;
97463 *pazResult = &res.azResult[1];
97464 if( pnColumn ) *pnColumn = res.nColumn;
97465 if( pnRow ) *pnRow = res.nRow;
97466 return rc;
97470 ** This routine frees the space the sqlite3_get_table() malloced.
97472 SQLITE_API void sqlite3_free_table(
97473 char **azResult /* Result returned from from sqlite3_get_table() */
97475 if( azResult ){
97476 int i, n;
97477 azResult--;
97478 assert( azResult!=0 );
97479 n = SQLITE_PTR_TO_INT(azResult[0]);
97480 for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
97481 sqlite3_free(azResult);
97485 #endif /* SQLITE_OMIT_GET_TABLE */
97487 /************** End of table.c ***********************************************/
97488 /************** Begin file trigger.c *****************************************/
97491 ** The author disclaims copyright to this source code. In place of
97492 ** a legal notice, here is a blessing:
97494 ** May you do good and not evil.
97495 ** May you find forgiveness for yourself and forgive others.
97496 ** May you share freely, never taking more than you give.
97498 *************************************************************************
97499 ** This file contains the implementation for TRIGGERs
97502 #ifndef SQLITE_OMIT_TRIGGER
97504 ** Delete a linked list of TriggerStep structures.
97506 SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
97507 while( pTriggerStep ){
97508 TriggerStep * pTmp = pTriggerStep;
97509 pTriggerStep = pTriggerStep->pNext;
97511 sqlite3ExprDelete(db, pTmp->pWhere);
97512 sqlite3ExprListDelete(db, pTmp->pExprList);
97513 sqlite3SelectDelete(db, pTmp->pSelect);
97514 sqlite3IdListDelete(db, pTmp->pIdList);
97516 sqlite3DbFree(db, pTmp);
97521 ** Given table pTab, return a list of all the triggers attached to
97522 ** the table. The list is connected by Trigger.pNext pointers.
97524 ** All of the triggers on pTab that are in the same database as pTab
97525 ** are already attached to pTab->pTrigger. But there might be additional
97526 ** triggers on pTab in the TEMP schema. This routine prepends all
97527 ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
97528 ** and returns the combined list.
97530 ** To state it another way: This routine returns a list of all triggers
97531 ** that fire off of pTab. The list will include any TEMP triggers on
97532 ** pTab as well as the triggers lised in pTab->pTrigger.
97534 SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
97535 Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
97536 Trigger *pList = 0; /* List of triggers to return */
97538 if( pParse->disableTriggers ){
97539 return 0;
97542 if( pTmpSchema!=pTab->pSchema ){
97543 HashElem *p;
97544 assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
97545 for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
97546 Trigger *pTrig = (Trigger *)sqliteHashData(p);
97547 if( pTrig->pTabSchema==pTab->pSchema
97548 && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
97550 pTrig->pNext = (pList ? pList : pTab->pTrigger);
97551 pList = pTrig;
97556 return (pList ? pList : pTab->pTrigger);
97560 ** This is called by the parser when it sees a CREATE TRIGGER statement
97561 ** up to the point of the BEGIN before the trigger actions. A Trigger
97562 ** structure is generated based on the information available and stored
97563 ** in pParse->pNewTrigger. After the trigger actions have been parsed, the
97564 ** sqlite3FinishTrigger() function is called to complete the trigger
97565 ** construction process.
97567 SQLITE_PRIVATE void sqlite3BeginTrigger(
97568 Parse *pParse, /* The parse context of the CREATE TRIGGER statement */
97569 Token *pName1, /* The name of the trigger */
97570 Token *pName2, /* The name of the trigger */
97571 int tr_tm, /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
97572 int op, /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
97573 IdList *pColumns, /* column list if this is an UPDATE OF trigger */
97574 SrcList *pTableName,/* The name of the table/view the trigger applies to */
97575 Expr *pWhen, /* WHEN clause */
97576 int isTemp, /* True if the TEMPORARY keyword is present */
97577 int noErr /* Suppress errors if the trigger already exists */
97579 Trigger *pTrigger = 0; /* The new trigger */
97580 Table *pTab; /* Table that the trigger fires off of */
97581 char *zName = 0; /* Name of the trigger */
97582 sqlite3 *db = pParse->db; /* The database connection */
97583 int iDb; /* The database to store the trigger in */
97584 Token *pName; /* The unqualified db name */
97585 DbFixer sFix; /* State vector for the DB fixer */
97586 int iTabDb; /* Index of the database holding pTab */
97588 assert( pName1!=0 ); /* pName1->z might be NULL, but not pName1 itself */
97589 assert( pName2!=0 );
97590 assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
97591 assert( op>0 && op<0xff );
97592 if( isTemp ){
97593 /* If TEMP was specified, then the trigger name may not be qualified. */
97594 if( pName2->n>0 ){
97595 sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
97596 goto trigger_cleanup;
97598 iDb = 1;
97599 pName = pName1;
97600 }else{
97601 /* Figure out the db that the the trigger will be created in */
97602 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
97603 if( iDb<0 ){
97604 goto trigger_cleanup;
97607 if( !pTableName || db->mallocFailed ){
97608 goto trigger_cleanup;
97611 /* A long-standing parser bug is that this syntax was allowed:
97613 ** CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
97614 ** ^^^^^^^^
97616 ** To maintain backwards compatibility, ignore the database
97617 ** name on pTableName if we are reparsing our of SQLITE_MASTER.
97619 if( db->init.busy && iDb!=1 ){
97620 sqlite3DbFree(db, pTableName->a[0].zDatabase);
97621 pTableName->a[0].zDatabase = 0;
97624 /* If the trigger name was unqualified, and the table is a temp table,
97625 ** then set iDb to 1 to create the trigger in the temporary database.
97626 ** If sqlite3SrcListLookup() returns 0, indicating the table does not
97627 ** exist, the error is caught by the block below.
97629 pTab = sqlite3SrcListLookup(pParse, pTableName);
97630 if( db->init.busy==0 && pName2->n==0 && pTab
97631 && pTab->pSchema==db->aDb[1].pSchema ){
97632 iDb = 1;
97635 /* Ensure the table name matches database name and that the table exists */
97636 if( db->mallocFailed ) goto trigger_cleanup;
97637 assert( pTableName->nSrc==1 );
97638 if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) &&
97639 sqlite3FixSrcList(&sFix, pTableName) ){
97640 goto trigger_cleanup;
97642 pTab = sqlite3SrcListLookup(pParse, pTableName);
97643 if( !pTab ){
97644 /* The table does not exist. */
97645 if( db->init.iDb==1 ){
97646 /* Ticket #3810.
97647 ** Normally, whenever a table is dropped, all associated triggers are
97648 ** dropped too. But if a TEMP trigger is created on a non-TEMP table
97649 ** and the table is dropped by a different database connection, the
97650 ** trigger is not visible to the database connection that does the
97651 ** drop so the trigger cannot be dropped. This results in an
97652 ** "orphaned trigger" - a trigger whose associated table is missing.
97654 db->init.orphanTrigger = 1;
97656 goto trigger_cleanup;
97658 if( IsVirtual(pTab) ){
97659 sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
97660 goto trigger_cleanup;
97663 /* Check that the trigger name is not reserved and that no trigger of the
97664 ** specified name exists */
97665 zName = sqlite3NameFromToken(db, pName);
97666 if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
97667 goto trigger_cleanup;
97669 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
97670 if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),
97671 zName, sqlite3Strlen30(zName)) ){
97672 if( !noErr ){
97673 sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
97674 }else{
97675 assert( !db->init.busy );
97676 sqlite3CodeVerifySchema(pParse, iDb);
97678 goto trigger_cleanup;
97681 /* Do not create a trigger on a system table */
97682 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
97683 sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
97684 pParse->nErr++;
97685 goto trigger_cleanup;
97688 /* INSTEAD of triggers are only for views and views only support INSTEAD
97689 ** of triggers.
97691 if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
97692 sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
97693 (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
97694 goto trigger_cleanup;
97696 if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
97697 sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
97698 " trigger on table: %S", pTableName, 0);
97699 goto trigger_cleanup;
97701 iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
97703 #ifndef SQLITE_OMIT_AUTHORIZATION
97705 int code = SQLITE_CREATE_TRIGGER;
97706 const char *zDb = db->aDb[iTabDb].zName;
97707 const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
97708 if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
97709 if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
97710 goto trigger_cleanup;
97712 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
97713 goto trigger_cleanup;
97716 #endif
97718 /* INSTEAD OF triggers can only appear on views and BEFORE triggers
97719 ** cannot appear on views. So we might as well translate every
97720 ** INSTEAD OF trigger into a BEFORE trigger. It simplifies code
97721 ** elsewhere.
97723 if (tr_tm == TK_INSTEAD){
97724 tr_tm = TK_BEFORE;
97727 /* Build the Trigger object */
97728 pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
97729 if( pTrigger==0 ) goto trigger_cleanup;
97730 pTrigger->zName = zName;
97731 zName = 0;
97732 pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
97733 pTrigger->pSchema = db->aDb[iDb].pSchema;
97734 pTrigger->pTabSchema = pTab->pSchema;
97735 pTrigger->op = (u8)op;
97736 pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
97737 pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
97738 pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
97739 assert( pParse->pNewTrigger==0 );
97740 pParse->pNewTrigger = pTrigger;
97742 trigger_cleanup:
97743 sqlite3DbFree(db, zName);
97744 sqlite3SrcListDelete(db, pTableName);
97745 sqlite3IdListDelete(db, pColumns);
97746 sqlite3ExprDelete(db, pWhen);
97747 if( !pParse->pNewTrigger ){
97748 sqlite3DeleteTrigger(db, pTrigger);
97749 }else{
97750 assert( pParse->pNewTrigger==pTrigger );
97755 ** This routine is called after all of the trigger actions have been parsed
97756 ** in order to complete the process of building the trigger.
97758 SQLITE_PRIVATE void sqlite3FinishTrigger(
97759 Parse *pParse, /* Parser context */
97760 TriggerStep *pStepList, /* The triggered program */
97761 Token *pAll /* Token that describes the complete CREATE TRIGGER */
97763 Trigger *pTrig = pParse->pNewTrigger; /* Trigger being finished */
97764 char *zName; /* Name of trigger */
97765 sqlite3 *db = pParse->db; /* The database */
97766 DbFixer sFix; /* Fixer object */
97767 int iDb; /* Database containing the trigger */
97768 Token nameToken; /* Trigger name for error reporting */
97770 pParse->pNewTrigger = 0;
97771 if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
97772 zName = pTrig->zName;
97773 iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
97774 pTrig->step_list = pStepList;
97775 while( pStepList ){
97776 pStepList->pTrig = pTrig;
97777 pStepList = pStepList->pNext;
97779 nameToken.z = pTrig->zName;
97780 nameToken.n = sqlite3Strlen30(nameToken.z);
97781 if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken)
97782 && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
97783 goto triggerfinish_cleanup;
97786 /* if we are not initializing,
97787 ** build the sqlite_master entry
97789 if( !db->init.busy ){
97790 Vdbe *v;
97791 char *z;
97793 /* Make an entry in the sqlite_master table */
97794 v = sqlite3GetVdbe(pParse);
97795 if( v==0 ) goto triggerfinish_cleanup;
97796 sqlite3BeginWriteOperation(pParse, 0, iDb);
97797 z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
97798 sqlite3NestedParse(pParse,
97799 "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
97800 db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
97801 pTrig->table, z);
97802 sqlite3DbFree(db, z);
97803 sqlite3ChangeCookie(pParse, iDb);
97804 sqlite3VdbeAddParseSchemaOp(v, iDb,
97805 sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
97808 if( db->init.busy ){
97809 Trigger *pLink = pTrig;
97810 Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
97811 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
97812 pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);
97813 if( pTrig ){
97814 db->mallocFailed = 1;
97815 }else if( pLink->pSchema==pLink->pTabSchema ){
97816 Table *pTab;
97817 int n = sqlite3Strlen30(pLink->table);
97818 pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
97819 assert( pTab!=0 );
97820 pLink->pNext = pTab->pTrigger;
97821 pTab->pTrigger = pLink;
97825 triggerfinish_cleanup:
97826 sqlite3DeleteTrigger(db, pTrig);
97827 assert( !pParse->pNewTrigger );
97828 sqlite3DeleteTriggerStep(db, pStepList);
97832 ** Turn a SELECT statement (that the pSelect parameter points to) into
97833 ** a trigger step. Return a pointer to a TriggerStep structure.
97835 ** The parser calls this routine when it finds a SELECT statement in
97836 ** body of a TRIGGER.
97838 SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
97839 TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
97840 if( pTriggerStep==0 ) {
97841 sqlite3SelectDelete(db, pSelect);
97842 return 0;
97844 pTriggerStep->op = TK_SELECT;
97845 pTriggerStep->pSelect = pSelect;
97846 pTriggerStep->orconf = OE_Default;
97847 return pTriggerStep;
97851 ** Allocate space to hold a new trigger step. The allocated space
97852 ** holds both the TriggerStep object and the TriggerStep.target.z string.
97854 ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
97856 static TriggerStep *triggerStepAllocate(
97857 sqlite3 *db, /* Database connection */
97858 u8 op, /* Trigger opcode */
97859 Token *pName /* The target name */
97861 TriggerStep *pTriggerStep;
97863 pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
97864 if( pTriggerStep ){
97865 char *z = (char*)&pTriggerStep[1];
97866 memcpy(z, pName->z, pName->n);
97867 pTriggerStep->target.z = z;
97868 pTriggerStep->target.n = pName->n;
97869 pTriggerStep->op = op;
97871 return pTriggerStep;
97875 ** Build a trigger step out of an INSERT statement. Return a pointer
97876 ** to the new trigger step.
97878 ** The parser calls this routine when it sees an INSERT inside the
97879 ** body of a trigger.
97881 SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
97882 sqlite3 *db, /* The database connection */
97883 Token *pTableName, /* Name of the table into which we insert */
97884 IdList *pColumn, /* List of columns in pTableName to insert into */
97885 ExprList *pEList, /* The VALUE clause: a list of values to be inserted */
97886 Select *pSelect, /* A SELECT statement that supplies values */
97887 u8 orconf /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
97889 TriggerStep *pTriggerStep;
97891 assert(pEList == 0 || pSelect == 0);
97892 assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
97894 pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
97895 if( pTriggerStep ){
97896 pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
97897 pTriggerStep->pIdList = pColumn;
97898 pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
97899 pTriggerStep->orconf = orconf;
97900 }else{
97901 sqlite3IdListDelete(db, pColumn);
97903 sqlite3ExprListDelete(db, pEList);
97904 sqlite3SelectDelete(db, pSelect);
97906 return pTriggerStep;
97910 ** Construct a trigger step that implements an UPDATE statement and return
97911 ** a pointer to that trigger step. The parser calls this routine when it
97912 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
97914 SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
97915 sqlite3 *db, /* The database connection */
97916 Token *pTableName, /* Name of the table to be updated */
97917 ExprList *pEList, /* The SET clause: list of column and new values */
97918 Expr *pWhere, /* The WHERE clause */
97919 u8 orconf /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
97921 TriggerStep *pTriggerStep;
97923 pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
97924 if( pTriggerStep ){
97925 pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
97926 pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
97927 pTriggerStep->orconf = orconf;
97929 sqlite3ExprListDelete(db, pEList);
97930 sqlite3ExprDelete(db, pWhere);
97931 return pTriggerStep;
97935 ** Construct a trigger step that implements a DELETE statement and return
97936 ** a pointer to that trigger step. The parser calls this routine when it
97937 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
97939 SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
97940 sqlite3 *db, /* Database connection */
97941 Token *pTableName, /* The table from which rows are deleted */
97942 Expr *pWhere /* The WHERE clause */
97944 TriggerStep *pTriggerStep;
97946 pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
97947 if( pTriggerStep ){
97948 pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
97949 pTriggerStep->orconf = OE_Default;
97951 sqlite3ExprDelete(db, pWhere);
97952 return pTriggerStep;
97956 ** Recursively delete a Trigger structure
97958 SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
97959 if( pTrigger==0 ) return;
97960 sqlite3DeleteTriggerStep(db, pTrigger->step_list);
97961 sqlite3DbFree(db, pTrigger->zName);
97962 sqlite3DbFree(db, pTrigger->table);
97963 sqlite3ExprDelete(db, pTrigger->pWhen);
97964 sqlite3IdListDelete(db, pTrigger->pColumns);
97965 sqlite3DbFree(db, pTrigger);
97969 ** This function is called to drop a trigger from the database schema.
97971 ** This may be called directly from the parser and therefore identifies
97972 ** the trigger by name. The sqlite3DropTriggerPtr() routine does the
97973 ** same job as this routine except it takes a pointer to the trigger
97974 ** instead of the trigger name.
97976 SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
97977 Trigger *pTrigger = 0;
97978 int i;
97979 const char *zDb;
97980 const char *zName;
97981 int nName;
97982 sqlite3 *db = pParse->db;
97984 if( db->mallocFailed ) goto drop_trigger_cleanup;
97985 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
97986 goto drop_trigger_cleanup;
97989 assert( pName->nSrc==1 );
97990 zDb = pName->a[0].zDatabase;
97991 zName = pName->a[0].zName;
97992 nName = sqlite3Strlen30(zName);
97993 assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
97994 for(i=OMIT_TEMPDB; i<db->nDb; i++){
97995 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
97996 if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
97997 assert( sqlite3SchemaMutexHeld(db, j, 0) );
97998 pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
97999 if( pTrigger ) break;
98001 if( !pTrigger ){
98002 if( !noErr ){
98003 sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
98004 }else{
98005 sqlite3CodeVerifyNamedSchema(pParse, zDb);
98007 pParse->checkSchema = 1;
98008 goto drop_trigger_cleanup;
98010 sqlite3DropTriggerPtr(pParse, pTrigger);
98012 drop_trigger_cleanup:
98013 sqlite3SrcListDelete(db, pName);
98017 ** Return a pointer to the Table structure for the table that a trigger
98018 ** is set on.
98020 static Table *tableOfTrigger(Trigger *pTrigger){
98021 int n = sqlite3Strlen30(pTrigger->table);
98022 return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
98027 ** Drop a trigger given a pointer to that trigger.
98029 SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
98030 Table *pTable;
98031 Vdbe *v;
98032 sqlite3 *db = pParse->db;
98033 int iDb;
98035 iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
98036 assert( iDb>=0 && iDb<db->nDb );
98037 pTable = tableOfTrigger(pTrigger);
98038 assert( pTable );
98039 assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
98040 #ifndef SQLITE_OMIT_AUTHORIZATION
98042 int code = SQLITE_DROP_TRIGGER;
98043 const char *zDb = db->aDb[iDb].zName;
98044 const char *zTab = SCHEMA_TABLE(iDb);
98045 if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
98046 if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
98047 sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
98048 return;
98051 #endif
98053 /* Generate code to destroy the database record of the trigger.
98055 assert( pTable!=0 );
98056 if( (v = sqlite3GetVdbe(pParse))!=0 ){
98057 int base;
98058 static const VdbeOpList dropTrigger[] = {
98059 { OP_Rewind, 0, ADDR(9), 0},
98060 { OP_String8, 0, 1, 0}, /* 1 */
98061 { OP_Column, 0, 1, 2},
98062 { OP_Ne, 2, ADDR(8), 1},
98063 { OP_String8, 0, 1, 0}, /* 4: "trigger" */
98064 { OP_Column, 0, 0, 2},
98065 { OP_Ne, 2, ADDR(8), 1},
98066 { OP_Delete, 0, 0, 0},
98067 { OP_Next, 0, ADDR(1), 0}, /* 8 */
98070 sqlite3BeginWriteOperation(pParse, 0, iDb);
98071 sqlite3OpenMasterTable(pParse, iDb);
98072 base = sqlite3VdbeAddOpList(v, ArraySize(dropTrigger), dropTrigger);
98073 sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, P4_TRANSIENT);
98074 sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
98075 sqlite3ChangeCookie(pParse, iDb);
98076 sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
98077 sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
98078 if( pParse->nMem<3 ){
98079 pParse->nMem = 3;
98085 ** Remove a trigger from the hash tables of the sqlite* pointer.
98087 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
98088 Trigger *pTrigger;
98089 Hash *pHash;
98091 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
98092 pHash = &(db->aDb[iDb].pSchema->trigHash);
98093 pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0);
98094 if( ALWAYS(pTrigger) ){
98095 if( pTrigger->pSchema==pTrigger->pTabSchema ){
98096 Table *pTab = tableOfTrigger(pTrigger);
98097 Trigger **pp;
98098 for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
98099 *pp = (*pp)->pNext;
98101 sqlite3DeleteTrigger(db, pTrigger);
98102 db->flags |= SQLITE_InternChanges;
98107 ** pEList is the SET clause of an UPDATE statement. Each entry
98108 ** in pEList is of the format <id>=<expr>. If any of the entries
98109 ** in pEList have an <id> which matches an identifier in pIdList,
98110 ** then return TRUE. If pIdList==NULL, then it is considered a
98111 ** wildcard that matches anything. Likewise if pEList==NULL then
98112 ** it matches anything so always return true. Return false only
98113 ** if there is no match.
98115 static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
98116 int e;
98117 if( pIdList==0 || NEVER(pEList==0) ) return 1;
98118 for(e=0; e<pEList->nExpr; e++){
98119 if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
98121 return 0;
98125 ** Return a list of all triggers on table pTab if there exists at least
98126 ** one trigger that must be fired when an operation of type 'op' is
98127 ** performed on the table, and, if that operation is an UPDATE, if at
98128 ** least one of the columns in pChanges is being modified.
98130 SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
98131 Parse *pParse, /* Parse context */
98132 Table *pTab, /* The table the contains the triggers */
98133 int op, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
98134 ExprList *pChanges, /* Columns that change in an UPDATE statement */
98135 int *pMask /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
98137 int mask = 0;
98138 Trigger *pList = 0;
98139 Trigger *p;
98141 if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
98142 pList = sqlite3TriggerList(pParse, pTab);
98144 assert( pList==0 || IsVirtual(pTab)==0 );
98145 for(p=pList; p; p=p->pNext){
98146 if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
98147 mask |= p->tr_tm;
98150 if( pMask ){
98151 *pMask = mask;
98153 return (mask ? pList : 0);
98157 ** Convert the pStep->target token into a SrcList and return a pointer
98158 ** to that SrcList.
98160 ** This routine adds a specific database name, if needed, to the target when
98161 ** forming the SrcList. This prevents a trigger in one database from
98162 ** referring to a target in another database. An exception is when the
98163 ** trigger is in TEMP in which case it can refer to any other database it
98164 ** wants.
98166 static SrcList *targetSrcList(
98167 Parse *pParse, /* The parsing context */
98168 TriggerStep *pStep /* The trigger containing the target token */
98170 int iDb; /* Index of the database to use */
98171 SrcList *pSrc; /* SrcList to be returned */
98173 pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
98174 if( pSrc ){
98175 assert( pSrc->nSrc>0 );
98176 assert( pSrc->a!=0 );
98177 iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
98178 if( iDb==0 || iDb>=2 ){
98179 sqlite3 *db = pParse->db;
98180 assert( iDb<pParse->db->nDb );
98181 pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
98184 return pSrc;
98188 ** Generate VDBE code for the statements inside the body of a single
98189 ** trigger.
98191 static int codeTriggerProgram(
98192 Parse *pParse, /* The parser context */
98193 TriggerStep *pStepList, /* List of statements inside the trigger body */
98194 int orconf /* Conflict algorithm. (OE_Abort, etc) */
98196 TriggerStep *pStep;
98197 Vdbe *v = pParse->pVdbe;
98198 sqlite3 *db = pParse->db;
98200 assert( pParse->pTriggerTab && pParse->pToplevel );
98201 assert( pStepList );
98202 assert( v!=0 );
98203 for(pStep=pStepList; pStep; pStep=pStep->pNext){
98204 /* Figure out the ON CONFLICT policy that will be used for this step
98205 ** of the trigger program. If the statement that caused this trigger
98206 ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
98207 ** the ON CONFLICT policy that was specified as part of the trigger
98208 ** step statement. Example:
98210 ** CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
98211 ** INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
98212 ** END;
98214 ** INSERT INTO t1 ... ; -- insert into t2 uses REPLACE policy
98215 ** INSERT OR IGNORE INTO t1 ... ; -- insert into t2 uses IGNORE policy
98217 pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
98219 switch( pStep->op ){
98220 case TK_UPDATE: {
98221 sqlite3Update(pParse,
98222 targetSrcList(pParse, pStep),
98223 sqlite3ExprListDup(db, pStep->pExprList, 0),
98224 sqlite3ExprDup(db, pStep->pWhere, 0),
98225 pParse->eOrconf
98227 break;
98229 case TK_INSERT: {
98230 sqlite3Insert(pParse,
98231 targetSrcList(pParse, pStep),
98232 sqlite3ExprListDup(db, pStep->pExprList, 0),
98233 sqlite3SelectDup(db, pStep->pSelect, 0),
98234 sqlite3IdListDup(db, pStep->pIdList),
98235 pParse->eOrconf
98237 break;
98239 case TK_DELETE: {
98240 sqlite3DeleteFrom(pParse,
98241 targetSrcList(pParse, pStep),
98242 sqlite3ExprDup(db, pStep->pWhere, 0)
98244 break;
98246 default: assert( pStep->op==TK_SELECT ); {
98247 SelectDest sDest;
98248 Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
98249 sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
98250 sqlite3Select(pParse, pSelect, &sDest);
98251 sqlite3SelectDelete(db, pSelect);
98252 break;
98255 if( pStep->op!=TK_SELECT ){
98256 sqlite3VdbeAddOp0(v, OP_ResetCount);
98260 return 0;
98263 #ifdef SQLITE_DEBUG
98265 ** This function is used to add VdbeComment() annotations to a VDBE
98266 ** program. It is not used in production code, only for debugging.
98268 static const char *onErrorText(int onError){
98269 switch( onError ){
98270 case OE_Abort: return "abort";
98271 case OE_Rollback: return "rollback";
98272 case OE_Fail: return "fail";
98273 case OE_Replace: return "replace";
98274 case OE_Ignore: return "ignore";
98275 case OE_Default: return "default";
98277 return "n/a";
98279 #endif
98282 ** Parse context structure pFrom has just been used to create a sub-vdbe
98283 ** (trigger program). If an error has occurred, transfer error information
98284 ** from pFrom to pTo.
98286 static void transferParseError(Parse *pTo, Parse *pFrom){
98287 assert( pFrom->zErrMsg==0 || pFrom->nErr );
98288 assert( pTo->zErrMsg==0 || pTo->nErr );
98289 if( pTo->nErr==0 ){
98290 pTo->zErrMsg = pFrom->zErrMsg;
98291 pTo->nErr = pFrom->nErr;
98292 }else{
98293 sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
98298 ** Create and populate a new TriggerPrg object with a sub-program
98299 ** implementing trigger pTrigger with ON CONFLICT policy orconf.
98301 static TriggerPrg *codeRowTrigger(
98302 Parse *pParse, /* Current parse context */
98303 Trigger *pTrigger, /* Trigger to code */
98304 Table *pTab, /* The table pTrigger is attached to */
98305 int orconf /* ON CONFLICT policy to code trigger program with */
98307 Parse *pTop = sqlite3ParseToplevel(pParse);
98308 sqlite3 *db = pParse->db; /* Database handle */
98309 TriggerPrg *pPrg; /* Value to return */
98310 Expr *pWhen = 0; /* Duplicate of trigger WHEN expression */
98311 Vdbe *v; /* Temporary VM */
98312 NameContext sNC; /* Name context for sub-vdbe */
98313 SubProgram *pProgram = 0; /* Sub-vdbe for trigger program */
98314 Parse *pSubParse; /* Parse context for sub-vdbe */
98315 int iEndTrigger = 0; /* Label to jump to if WHEN is false */
98317 assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
98318 assert( pTop->pVdbe );
98320 /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
98321 ** are freed if an error occurs, link them into the Parse.pTriggerPrg
98322 ** list of the top-level Parse object sooner rather than later. */
98323 pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
98324 if( !pPrg ) return 0;
98325 pPrg->pNext = pTop->pTriggerPrg;
98326 pTop->pTriggerPrg = pPrg;
98327 pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
98328 if( !pProgram ) return 0;
98329 sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
98330 pPrg->pTrigger = pTrigger;
98331 pPrg->orconf = orconf;
98332 pPrg->aColmask[0] = 0xffffffff;
98333 pPrg->aColmask[1] = 0xffffffff;
98335 /* Allocate and populate a new Parse context to use for coding the
98336 ** trigger sub-program. */
98337 pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
98338 if( !pSubParse ) return 0;
98339 memset(&sNC, 0, sizeof(sNC));
98340 sNC.pParse = pSubParse;
98341 pSubParse->db = db;
98342 pSubParse->pTriggerTab = pTab;
98343 pSubParse->pToplevel = pTop;
98344 pSubParse->zAuthContext = pTrigger->zName;
98345 pSubParse->eTriggerOp = pTrigger->op;
98346 pSubParse->nQueryLoop = pParse->nQueryLoop;
98348 v = sqlite3GetVdbe(pSubParse);
98349 if( v ){
98350 VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
98351 pTrigger->zName, onErrorText(orconf),
98352 (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
98353 (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
98354 (pTrigger->op==TK_INSERT ? "INSERT" : ""),
98355 (pTrigger->op==TK_DELETE ? "DELETE" : ""),
98356 pTab->zName
98358 #ifndef SQLITE_OMIT_TRACE
98359 sqlite3VdbeChangeP4(v, -1,
98360 sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
98362 #endif
98364 /* If one was specified, code the WHEN clause. If it evaluates to false
98365 ** (or NULL) the sub-vdbe is immediately halted by jumping to the
98366 ** OP_Halt inserted at the end of the program. */
98367 if( pTrigger->pWhen ){
98368 pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
98369 if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
98370 && db->mallocFailed==0
98372 iEndTrigger = sqlite3VdbeMakeLabel(v);
98373 sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
98375 sqlite3ExprDelete(db, pWhen);
98378 /* Code the trigger program into the sub-vdbe. */
98379 codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
98381 /* Insert an OP_Halt at the end of the sub-program. */
98382 if( iEndTrigger ){
98383 sqlite3VdbeResolveLabel(v, iEndTrigger);
98385 sqlite3VdbeAddOp0(v, OP_Halt);
98386 VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
98388 transferParseError(pParse, pSubParse);
98389 if( db->mallocFailed==0 ){
98390 pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
98392 pProgram->nMem = pSubParse->nMem;
98393 pProgram->nCsr = pSubParse->nTab;
98394 pProgram->token = (void *)pTrigger;
98395 pPrg->aColmask[0] = pSubParse->oldmask;
98396 pPrg->aColmask[1] = pSubParse->newmask;
98397 sqlite3VdbeDelete(v);
98400 assert( !pSubParse->pAinc && !pSubParse->pZombieTab );
98401 assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
98402 sqlite3StackFree(db, pSubParse);
98404 return pPrg;
98408 ** Return a pointer to a TriggerPrg object containing the sub-program for
98409 ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
98410 ** TriggerPrg object exists, a new object is allocated and populated before
98411 ** being returned.
98413 static TriggerPrg *getRowTrigger(
98414 Parse *pParse, /* Current parse context */
98415 Trigger *pTrigger, /* Trigger to code */
98416 Table *pTab, /* The table trigger pTrigger is attached to */
98417 int orconf /* ON CONFLICT algorithm. */
98419 Parse *pRoot = sqlite3ParseToplevel(pParse);
98420 TriggerPrg *pPrg;
98422 assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
98424 /* It may be that this trigger has already been coded (or is in the
98425 ** process of being coded). If this is the case, then an entry with
98426 ** a matching TriggerPrg.pTrigger field will be present somewhere
98427 ** in the Parse.pTriggerPrg list. Search for such an entry. */
98428 for(pPrg=pRoot->pTriggerPrg;
98429 pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
98430 pPrg=pPrg->pNext
98433 /* If an existing TriggerPrg could not be located, create a new one. */
98434 if( !pPrg ){
98435 pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
98438 return pPrg;
98442 ** Generate code for the trigger program associated with trigger p on
98443 ** table pTab. The reg, orconf and ignoreJump parameters passed to this
98444 ** function are the same as those described in the header function for
98445 ** sqlite3CodeRowTrigger()
98447 SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
98448 Parse *pParse, /* Parse context */
98449 Trigger *p, /* Trigger to code */
98450 Table *pTab, /* The table to code triggers from */
98451 int reg, /* Reg array containing OLD.* and NEW.* values */
98452 int orconf, /* ON CONFLICT policy */
98453 int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
98455 Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
98456 TriggerPrg *pPrg;
98457 pPrg = getRowTrigger(pParse, p, pTab, orconf);
98458 assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
98460 /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
98461 ** is a pointer to the sub-vdbe containing the trigger program. */
98462 if( pPrg ){
98463 int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
98465 sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
98466 sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
98467 VdbeComment(
98468 (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
98470 /* Set the P5 operand of the OP_Program instruction to non-zero if
98471 ** recursive invocation of this trigger program is disallowed. Recursive
98472 ** invocation is disallowed if (a) the sub-program is really a trigger,
98473 ** not a foreign key action, and (b) the flag to enable recursive triggers
98474 ** is clear. */
98475 sqlite3VdbeChangeP5(v, (u8)bRecursive);
98480 ** This is called to code the required FOR EACH ROW triggers for an operation
98481 ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
98482 ** is given by the op paramater. The tr_tm parameter determines whether the
98483 ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
98484 ** parameter pChanges is passed the list of columns being modified.
98486 ** If there are no triggers that fire at the specified time for the specified
98487 ** operation on pTab, this function is a no-op.
98489 ** The reg argument is the address of the first in an array of registers
98490 ** that contain the values substituted for the new.* and old.* references
98491 ** in the trigger program. If N is the number of columns in table pTab
98492 ** (a copy of pTab->nCol), then registers are populated as follows:
98494 ** Register Contains
98495 ** ------------------------------------------------------
98496 ** reg+0 OLD.rowid
98497 ** reg+1 OLD.* value of left-most column of pTab
98498 ** ... ...
98499 ** reg+N OLD.* value of right-most column of pTab
98500 ** reg+N+1 NEW.rowid
98501 ** reg+N+2 OLD.* value of left-most column of pTab
98502 ** ... ...
98503 ** reg+N+N+1 NEW.* value of right-most column of pTab
98505 ** For ON DELETE triggers, the registers containing the NEW.* values will
98506 ** never be accessed by the trigger program, so they are not allocated or
98507 ** populated by the caller (there is no data to populate them with anyway).
98508 ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
98509 ** are never accessed, and so are not allocated by the caller. So, for an
98510 ** ON INSERT trigger, the value passed to this function as parameter reg
98511 ** is not a readable register, although registers (reg+N) through
98512 ** (reg+N+N+1) are.
98514 ** Parameter orconf is the default conflict resolution algorithm for the
98515 ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
98516 ** is the instruction that control should jump to if a trigger program
98517 ** raises an IGNORE exception.
98519 SQLITE_PRIVATE void sqlite3CodeRowTrigger(
98520 Parse *pParse, /* Parse context */
98521 Trigger *pTrigger, /* List of triggers on table pTab */
98522 int op, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
98523 ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
98524 int tr_tm, /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
98525 Table *pTab, /* The table to code triggers from */
98526 int reg, /* The first in an array of registers (see above) */
98527 int orconf, /* ON CONFLICT policy */
98528 int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
98530 Trigger *p; /* Used to iterate through pTrigger list */
98532 assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
98533 assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
98534 assert( (op==TK_UPDATE)==(pChanges!=0) );
98536 for(p=pTrigger; p; p=p->pNext){
98538 /* Sanity checking: The schema for the trigger and for the table are
98539 ** always defined. The trigger must be in the same schema as the table
98540 ** or else it must be a TEMP trigger. */
98541 assert( p->pSchema!=0 );
98542 assert( p->pTabSchema!=0 );
98543 assert( p->pSchema==p->pTabSchema
98544 || p->pSchema==pParse->db->aDb[1].pSchema );
98546 /* Determine whether we should code this trigger */
98547 if( p->op==op
98548 && p->tr_tm==tr_tm
98549 && checkColumnOverlap(p->pColumns, pChanges)
98551 sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
98557 ** Triggers may access values stored in the old.* or new.* pseudo-table.
98558 ** This function returns a 32-bit bitmask indicating which columns of the
98559 ** old.* or new.* tables actually are used by triggers. This information
98560 ** may be used by the caller, for example, to avoid having to load the entire
98561 ** old.* record into memory when executing an UPDATE or DELETE command.
98563 ** Bit 0 of the returned mask is set if the left-most column of the
98564 ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
98565 ** the second leftmost column value is required, and so on. If there
98566 ** are more than 32 columns in the table, and at least one of the columns
98567 ** with an index greater than 32 may be accessed, 0xffffffff is returned.
98569 ** It is not possible to determine if the old.rowid or new.rowid column is
98570 ** accessed by triggers. The caller must always assume that it is.
98572 ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
98573 ** applies to the old.* table. If 1, the new.* table.
98575 ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
98576 ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
98577 ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
98578 ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
98579 ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
98581 SQLITE_PRIVATE u32 sqlite3TriggerColmask(
98582 Parse *pParse, /* Parse context */
98583 Trigger *pTrigger, /* List of triggers on table pTab */
98584 ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
98585 int isNew, /* 1 for new.* ref mask, 0 for old.* ref mask */
98586 int tr_tm, /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
98587 Table *pTab, /* The table to code triggers from */
98588 int orconf /* Default ON CONFLICT policy for trigger steps */
98590 const int op = pChanges ? TK_UPDATE : TK_DELETE;
98591 u32 mask = 0;
98592 Trigger *p;
98594 assert( isNew==1 || isNew==0 );
98595 for(p=pTrigger; p; p=p->pNext){
98596 if( p->op==op && (tr_tm&p->tr_tm)
98597 && checkColumnOverlap(p->pColumns,pChanges)
98599 TriggerPrg *pPrg;
98600 pPrg = getRowTrigger(pParse, p, pTab, orconf);
98601 if( pPrg ){
98602 mask |= pPrg->aColmask[isNew];
98607 return mask;
98610 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
98612 /************** End of trigger.c *********************************************/
98613 /************** Begin file update.c ******************************************/
98615 ** 2001 September 15
98617 ** The author disclaims copyright to this source code. In place of
98618 ** a legal notice, here is a blessing:
98620 ** May you do good and not evil.
98621 ** May you find forgiveness for yourself and forgive others.
98622 ** May you share freely, never taking more than you give.
98624 *************************************************************************
98625 ** This file contains C code routines that are called by the parser
98626 ** to handle UPDATE statements.
98629 #ifndef SQLITE_OMIT_VIRTUALTABLE
98630 /* Forward declaration */
98631 static void updateVirtualTable(
98632 Parse *pParse, /* The parsing context */
98633 SrcList *pSrc, /* The virtual table to be modified */
98634 Table *pTab, /* The virtual table */
98635 ExprList *pChanges, /* The columns to change in the UPDATE statement */
98636 Expr *pRowidExpr, /* Expression used to recompute the rowid */
98637 int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
98638 Expr *pWhere, /* WHERE clause of the UPDATE statement */
98639 int onError /* ON CONFLICT strategy */
98641 #endif /* SQLITE_OMIT_VIRTUALTABLE */
98644 ** The most recently coded instruction was an OP_Column to retrieve the
98645 ** i-th column of table pTab. This routine sets the P4 parameter of the
98646 ** OP_Column to the default value, if any.
98648 ** The default value of a column is specified by a DEFAULT clause in the
98649 ** column definition. This was either supplied by the user when the table
98650 ** was created, or added later to the table definition by an ALTER TABLE
98651 ** command. If the latter, then the row-records in the table btree on disk
98652 ** may not contain a value for the column and the default value, taken
98653 ** from the P4 parameter of the OP_Column instruction, is returned instead.
98654 ** If the former, then all row-records are guaranteed to include a value
98655 ** for the column and the P4 value is not required.
98657 ** Column definitions created by an ALTER TABLE command may only have
98658 ** literal default values specified: a number, null or a string. (If a more
98659 ** complicated default expression value was provided, it is evaluated
98660 ** when the ALTER TABLE is executed and one of the literal values written
98661 ** into the sqlite_master table.)
98663 ** Therefore, the P4 parameter is only required if the default value for
98664 ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
98665 ** function is capable of transforming these types of expressions into
98666 ** sqlite3_value objects.
98668 ** If parameter iReg is not negative, code an OP_RealAffinity instruction
98669 ** on register iReg. This is used when an equivalent integer value is
98670 ** stored in place of an 8-byte floating point value in order to save
98671 ** space.
98673 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
98674 assert( pTab!=0 );
98675 if( !pTab->pSelect ){
98676 sqlite3_value *pValue;
98677 u8 enc = ENC(sqlite3VdbeDb(v));
98678 Column *pCol = &pTab->aCol[i];
98679 VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
98680 assert( i<pTab->nCol );
98681 sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
98682 pCol->affinity, &pValue);
98683 if( pValue ){
98684 sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
98686 #ifndef SQLITE_OMIT_FLOATING_POINT
98687 if( iReg>=0 && pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
98688 sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
98690 #endif
98695 ** Process an UPDATE statement.
98697 ** UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
98698 ** \_______/ \________/ \______/ \________________/
98699 * onError pTabList pChanges pWhere
98701 SQLITE_PRIVATE void sqlite3Update(
98702 Parse *pParse, /* The parser context */
98703 SrcList *pTabList, /* The table in which we should change things */
98704 ExprList *pChanges, /* Things to be changed */
98705 Expr *pWhere, /* The WHERE clause. May be null */
98706 int onError /* How to handle constraint errors */
98708 int i, j; /* Loop counters */
98709 Table *pTab; /* The table to be updated */
98710 int addr = 0; /* VDBE instruction address of the start of the loop */
98711 WhereInfo *pWInfo; /* Information about the WHERE clause */
98712 Vdbe *v; /* The virtual database engine */
98713 Index *pIdx; /* For looping over indices */
98714 int nIdx; /* Number of indices that need updating */
98715 int iCur; /* VDBE Cursor number of pTab */
98716 sqlite3 *db; /* The database structure */
98717 int *aRegIdx = 0; /* One register assigned to each index to be updated */
98718 int *aXRef = 0; /* aXRef[i] is the index in pChanges->a[] of the
98719 ** an expression for the i-th column of the table.
98720 ** aXRef[i]==-1 if the i-th column is not changed. */
98721 int chngRowid; /* True if the record number is being changed */
98722 Expr *pRowidExpr = 0; /* Expression defining the new record number */
98723 int openAll = 0; /* True if all indices need to be opened */
98724 AuthContext sContext; /* The authorization context */
98725 NameContext sNC; /* The name-context to resolve expressions in */
98726 int iDb; /* Database containing the table being updated */
98727 int okOnePass; /* True for one-pass algorithm without the FIFO */
98728 int hasFK; /* True if foreign key processing is required */
98730 #ifndef SQLITE_OMIT_TRIGGER
98731 int isView; /* True when updating a view (INSTEAD OF trigger) */
98732 Trigger *pTrigger; /* List of triggers on pTab, if required */
98733 int tmask; /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
98734 #endif
98735 int newmask; /* Mask of NEW.* columns accessed by BEFORE triggers */
98737 /* Register Allocations */
98738 int regRowCount = 0; /* A count of rows changed */
98739 int regOldRowid; /* The old rowid */
98740 int regNewRowid; /* The new rowid */
98741 int regNew;
98742 int regOld = 0;
98743 int regRowSet = 0; /* Rowset of rows to be updated */
98745 memset(&sContext, 0, sizeof(sContext));
98746 db = pParse->db;
98747 if( pParse->nErr || db->mallocFailed ){
98748 goto update_cleanup;
98750 assert( pTabList->nSrc==1 );
98752 /* Locate the table which we want to update.
98754 pTab = sqlite3SrcListLookup(pParse, pTabList);
98755 if( pTab==0 ) goto update_cleanup;
98756 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
98758 /* Figure out if we have any triggers and if the table being
98759 ** updated is a view.
98761 #ifndef SQLITE_OMIT_TRIGGER
98762 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
98763 isView = pTab->pSelect!=0;
98764 assert( pTrigger || tmask==0 );
98765 #else
98766 # define pTrigger 0
98767 # define isView 0
98768 # define tmask 0
98769 #endif
98770 #ifdef SQLITE_OMIT_VIEW
98771 # undef isView
98772 # define isView 0
98773 #endif
98775 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
98776 goto update_cleanup;
98778 if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
98779 goto update_cleanup;
98781 aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );
98782 if( aXRef==0 ) goto update_cleanup;
98783 for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
98785 /* Allocate a cursors for the main database table and for all indices.
98786 ** The index cursors might not be used, but if they are used they
98787 ** need to occur right after the database cursor. So go ahead and
98788 ** allocate enough space, just in case.
98790 pTabList->a[0].iCursor = iCur = pParse->nTab++;
98791 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
98792 pParse->nTab++;
98795 /* Initialize the name-context */
98796 memset(&sNC, 0, sizeof(sNC));
98797 sNC.pParse = pParse;
98798 sNC.pSrcList = pTabList;
98800 /* Resolve the column names in all the expressions of the
98801 ** of the UPDATE statement. Also find the column index
98802 ** for each column to be updated in the pChanges array. For each
98803 ** column to be updated, make sure we have authorization to change
98804 ** that column.
98806 chngRowid = 0;
98807 for(i=0; i<pChanges->nExpr; i++){
98808 if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
98809 goto update_cleanup;
98811 for(j=0; j<pTab->nCol; j++){
98812 if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
98813 if( j==pTab->iPKey ){
98814 chngRowid = 1;
98815 pRowidExpr = pChanges->a[i].pExpr;
98817 aXRef[j] = i;
98818 break;
98821 if( j>=pTab->nCol ){
98822 if( sqlite3IsRowid(pChanges->a[i].zName) ){
98823 chngRowid = 1;
98824 pRowidExpr = pChanges->a[i].pExpr;
98825 }else{
98826 sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
98827 pParse->checkSchema = 1;
98828 goto update_cleanup;
98831 #ifndef SQLITE_OMIT_AUTHORIZATION
98833 int rc;
98834 rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
98835 pTab->aCol[j].zName, db->aDb[iDb].zName);
98836 if( rc==SQLITE_DENY ){
98837 goto update_cleanup;
98838 }else if( rc==SQLITE_IGNORE ){
98839 aXRef[j] = -1;
98842 #endif
98845 hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngRowid);
98847 /* Allocate memory for the array aRegIdx[]. There is one entry in the
98848 ** array for each index associated with table being updated. Fill in
98849 ** the value with a register number for indices that are to be used
98850 ** and with zero for unused indices.
98852 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
98853 if( nIdx>0 ){
98854 aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );
98855 if( aRegIdx==0 ) goto update_cleanup;
98857 for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
98858 int reg;
98859 if( hasFK || chngRowid ){
98860 reg = ++pParse->nMem;
98861 }else{
98862 reg = 0;
98863 for(i=0; i<pIdx->nColumn; i++){
98864 if( aXRef[pIdx->aiColumn[i]]>=0 ){
98865 reg = ++pParse->nMem;
98866 break;
98870 aRegIdx[j] = reg;
98873 /* Begin generating code. */
98874 v = sqlite3GetVdbe(pParse);
98875 if( v==0 ) goto update_cleanup;
98876 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
98877 sqlite3BeginWriteOperation(pParse, 1, iDb);
98879 #ifndef SQLITE_OMIT_VIRTUALTABLE
98880 /* Virtual tables must be handled separately */
98881 if( IsVirtual(pTab) ){
98882 updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
98883 pWhere, onError);
98884 pWhere = 0;
98885 pTabList = 0;
98886 goto update_cleanup;
98888 #endif
98890 /* Allocate required registers. */
98891 regOldRowid = regNewRowid = ++pParse->nMem;
98892 if( pTrigger || hasFK ){
98893 regOld = pParse->nMem + 1;
98894 pParse->nMem += pTab->nCol;
98896 if( chngRowid || pTrigger || hasFK ){
98897 regNewRowid = ++pParse->nMem;
98899 regNew = pParse->nMem + 1;
98900 pParse->nMem += pTab->nCol;
98902 /* Start the view context. */
98903 if( isView ){
98904 sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
98907 /* If we are trying to update a view, realize that view into
98908 ** a ephemeral table.
98910 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
98911 if( isView ){
98912 sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
98914 #endif
98916 /* Resolve the column names in all the expressions in the
98917 ** WHERE clause.
98919 if( sqlite3ResolveExprNames(&sNC, pWhere) ){
98920 goto update_cleanup;
98923 /* Begin the database scan
98925 sqlite3VdbeAddOp2(v, OP_Null, 0, regOldRowid);
98926 pWInfo = sqlite3WhereBegin(
98927 pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED
98929 if( pWInfo==0 ) goto update_cleanup;
98930 okOnePass = pWInfo->okOnePass;
98932 /* Remember the rowid of every item to be updated.
98934 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
98935 if( !okOnePass ){
98936 regRowSet = ++pParse->nMem;
98937 sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
98940 /* End the database scan loop.
98942 sqlite3WhereEnd(pWInfo);
98944 /* Initialize the count of updated rows
98946 if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
98947 regRowCount = ++pParse->nMem;
98948 sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
98951 if( !isView ){
98953 ** Open every index that needs updating. Note that if any
98954 ** index could potentially invoke a REPLACE conflict resolution
98955 ** action, then we need to open all indices because we might need
98956 ** to be deleting some records.
98958 if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite);
98959 if( onError==OE_Replace ){
98960 openAll = 1;
98961 }else{
98962 openAll = 0;
98963 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
98964 if( pIdx->onError==OE_Replace ){
98965 openAll = 1;
98966 break;
98970 for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
98971 assert( aRegIdx );
98972 if( openAll || aRegIdx[i]>0 ){
98973 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
98974 sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
98975 (char*)pKey, P4_KEYINFO_HANDOFF);
98976 assert( pParse->nTab>iCur+i+1 );
98981 /* Top of the update loop */
98982 if( okOnePass ){
98983 int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
98984 addr = sqlite3VdbeAddOp0(v, OP_Goto);
98985 sqlite3VdbeJumpHere(v, a1);
98986 }else{
98987 addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid);
98990 /* Make cursor iCur point to the record that is being updated. If
98991 ** this record does not exist for some reason (deleted by a trigger,
98992 ** for example, then jump to the next iteration of the RowSet loop. */
98993 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
98995 /* If the record number will change, set register regNewRowid to
98996 ** contain the new value. If the record number is not being modified,
98997 ** then regNewRowid is the same register as regOldRowid, which is
98998 ** already populated. */
98999 assert( chngRowid || pTrigger || hasFK || regOldRowid==regNewRowid );
99000 if( chngRowid ){
99001 sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
99002 sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
99005 /* If there are triggers on this table, populate an array of registers
99006 ** with the required old.* column data. */
99007 if( hasFK || pTrigger ){
99008 u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
99009 oldmask |= sqlite3TriggerColmask(pParse,
99010 pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
99012 for(i=0; i<pTab->nCol; i++){
99013 if( aXRef[i]<0 || oldmask==0xffffffff || (i<32 && (oldmask & (1<<i))) ){
99014 sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOld+i);
99015 }else{
99016 sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
99019 if( chngRowid==0 ){
99020 sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
99024 /* Populate the array of registers beginning at regNew with the new
99025 ** row data. This array is used to check constaints, create the new
99026 ** table and index records, and as the values for any new.* references
99027 ** made by triggers.
99029 ** If there are one or more BEFORE triggers, then do not populate the
99030 ** registers associated with columns that are (a) not modified by
99031 ** this UPDATE statement and (b) not accessed by new.* references. The
99032 ** values for registers not modified by the UPDATE must be reloaded from
99033 ** the database after the BEFORE triggers are fired anyway (as the trigger
99034 ** may have modified them). So not loading those that are not going to
99035 ** be used eliminates some redundant opcodes.
99037 newmask = sqlite3TriggerColmask(
99038 pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
99040 for(i=0; i<pTab->nCol; i++){
99041 if( i==pTab->iPKey ){
99042 sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
99043 }else{
99044 j = aXRef[i];
99045 if( j>=0 ){
99046 sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
99047 }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask&(1<<i)) ){
99048 /* This branch loads the value of a column that will not be changed
99049 ** into a register. This is done if there are no BEFORE triggers, or
99050 ** if there are one or more BEFORE triggers that use this value via
99051 ** a new.* reference in a trigger program.
99053 testcase( i==31 );
99054 testcase( i==32 );
99055 sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
99056 sqlite3ColumnDefault(v, pTab, i, regNew+i);
99061 /* Fire any BEFORE UPDATE triggers. This happens before constraints are
99062 ** verified. One could argue that this is wrong.
99064 if( tmask&TRIGGER_BEFORE ){
99065 sqlite3VdbeAddOp2(v, OP_Affinity, regNew, pTab->nCol);
99066 sqlite3TableAffinityStr(v, pTab);
99067 sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
99068 TRIGGER_BEFORE, pTab, regOldRowid, onError, addr);
99070 /* The row-trigger may have deleted the row being updated. In this
99071 ** case, jump to the next row. No updates or AFTER triggers are
99072 ** required. This behaviour - what happens when the row being updated
99073 ** is deleted or renamed by a BEFORE trigger - is left undefined in the
99074 ** documentation.
99076 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
99078 /* If it did not delete it, the row-trigger may still have modified
99079 ** some of the columns of the row being updated. Load the values for
99080 ** all columns not modified by the update statement into their
99081 ** registers in case this has happened.
99083 for(i=0; i<pTab->nCol; i++){
99084 if( aXRef[i]<0 && i!=pTab->iPKey ){
99085 sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
99086 sqlite3ColumnDefault(v, pTab, i, regNew+i);
99091 if( !isView ){
99092 int j1; /* Address of jump instruction */
99094 /* Do constraint checks. */
99095 sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
99096 aRegIdx, (chngRowid?regOldRowid:0), 1, onError, addr, 0);
99098 /* Do FK constraint checks. */
99099 if( hasFK ){
99100 sqlite3FkCheck(pParse, pTab, regOldRowid, 0);
99103 /* Delete the index entries associated with the current record. */
99104 j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
99105 sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
99107 /* If changing the record number, delete the old record. */
99108 if( hasFK || chngRowid ){
99109 sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
99111 sqlite3VdbeJumpHere(v, j1);
99113 if( hasFK ){
99114 sqlite3FkCheck(pParse, pTab, 0, regNewRowid);
99117 /* Insert the new index entries and the new record. */
99118 sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, aRegIdx, 1, 0, 0);
99120 /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
99121 ** handle rows (possibly in other tables) that refer via a foreign key
99122 ** to the row just updated. */
99123 if( hasFK ){
99124 sqlite3FkActions(pParse, pTab, pChanges, regOldRowid);
99128 /* Increment the row counter
99130 if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
99131 sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
99134 sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
99135 TRIGGER_AFTER, pTab, regOldRowid, onError, addr);
99137 /* Repeat the above with the next record to be updated, until
99138 ** all record selected by the WHERE clause have been updated.
99140 sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
99141 sqlite3VdbeJumpHere(v, addr);
99143 /* Close all tables */
99144 for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
99145 assert( aRegIdx );
99146 if( openAll || aRegIdx[i]>0 ){
99147 sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
99150 sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
99152 /* Update the sqlite_sequence table by storing the content of the
99153 ** maximum rowid counter values recorded while inserting into
99154 ** autoincrement tables.
99156 if( pParse->nested==0 && pParse->pTriggerTab==0 ){
99157 sqlite3AutoincrementEnd(pParse);
99161 ** Return the number of rows that were changed. If this routine is
99162 ** generating code because of a call to sqlite3NestedParse(), do not
99163 ** invoke the callback function.
99165 if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
99166 sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
99167 sqlite3VdbeSetNumCols(v, 1);
99168 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
99171 update_cleanup:
99172 sqlite3AuthContextPop(&sContext);
99173 sqlite3DbFree(db, aRegIdx);
99174 sqlite3DbFree(db, aXRef);
99175 sqlite3SrcListDelete(db, pTabList);
99176 sqlite3ExprListDelete(db, pChanges);
99177 sqlite3ExprDelete(db, pWhere);
99178 return;
99180 /* Make sure "isView" and other macros defined above are undefined. Otherwise
99181 ** thely may interfere with compilation of other functions in this file
99182 ** (or in another file, if this file becomes part of the amalgamation). */
99183 #ifdef isView
99184 #undef isView
99185 #endif
99186 #ifdef pTrigger
99187 #undef pTrigger
99188 #endif
99190 #ifndef SQLITE_OMIT_VIRTUALTABLE
99192 ** Generate code for an UPDATE of a virtual table.
99194 ** The strategy is that we create an ephemerial table that contains
99195 ** for each row to be changed:
99197 ** (A) The original rowid of that row.
99198 ** (B) The revised rowid for the row. (note1)
99199 ** (C) The content of every column in the row.
99201 ** Then we loop over this ephemeral table and for each row in
99202 ** the ephermeral table call VUpdate.
99204 ** When finished, drop the ephemeral table.
99206 ** (note1) Actually, if we know in advance that (A) is always the same
99207 ** as (B) we only store (A), then duplicate (A) when pulling
99208 ** it out of the ephemeral table before calling VUpdate.
99210 static void updateVirtualTable(
99211 Parse *pParse, /* The parsing context */
99212 SrcList *pSrc, /* The virtual table to be modified */
99213 Table *pTab, /* The virtual table */
99214 ExprList *pChanges, /* The columns to change in the UPDATE statement */
99215 Expr *pRowid, /* Expression used to recompute the rowid */
99216 int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
99217 Expr *pWhere, /* WHERE clause of the UPDATE statement */
99218 int onError /* ON CONFLICT strategy */
99220 Vdbe *v = pParse->pVdbe; /* Virtual machine under construction */
99221 ExprList *pEList = 0; /* The result set of the SELECT statement */
99222 Select *pSelect = 0; /* The SELECT statement */
99223 Expr *pExpr; /* Temporary expression */
99224 int ephemTab; /* Table holding the result of the SELECT */
99225 int i; /* Loop counter */
99226 int addr; /* Address of top of loop */
99227 int iReg; /* First register in set passed to OP_VUpdate */
99228 sqlite3 *db = pParse->db; /* Database connection */
99229 const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
99230 SelectDest dest;
99232 /* Construct the SELECT statement that will find the new values for
99233 ** all updated rows.
99235 pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
99236 if( pRowid ){
99237 pEList = sqlite3ExprListAppend(pParse, pEList,
99238 sqlite3ExprDup(db, pRowid, 0));
99240 assert( pTab->iPKey<0 );
99241 for(i=0; i<pTab->nCol; i++){
99242 if( aXRef[i]>=0 ){
99243 pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
99244 }else{
99245 pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
99247 pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
99249 pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
99251 /* Create the ephemeral table into which the update results will
99252 ** be stored.
99254 assert( v );
99255 ephemTab = pParse->nTab++;
99256 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
99257 sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
99259 /* fill the ephemeral table
99261 sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
99262 sqlite3Select(pParse, pSelect, &dest);
99264 /* Generate code to scan the ephemeral table and call VUpdate. */
99265 iReg = ++pParse->nMem;
99266 pParse->nMem += pTab->nCol+1;
99267 addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
99268 sqlite3VdbeAddOp3(v, OP_Column, ephemTab, 0, iReg);
99269 sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
99270 for(i=0; i<pTab->nCol; i++){
99271 sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
99273 sqlite3VtabMakeWritable(pParse, pTab);
99274 sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
99275 sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
99276 sqlite3MayAbort(pParse);
99277 sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1);
99278 sqlite3VdbeJumpHere(v, addr);
99279 sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
99281 /* Cleanup */
99282 sqlite3SelectDelete(db, pSelect);
99284 #endif /* SQLITE_OMIT_VIRTUALTABLE */
99286 /************** End of update.c **********************************************/
99287 /************** Begin file vacuum.c ******************************************/
99289 ** 2003 April 6
99291 ** The author disclaims copyright to this source code. In place of
99292 ** a legal notice, here is a blessing:
99294 ** May you do good and not evil.
99295 ** May you find forgiveness for yourself and forgive others.
99296 ** May you share freely, never taking more than you give.
99298 *************************************************************************
99299 ** This file contains code used to implement the VACUUM command.
99301 ** Most of the code in this file may be omitted by defining the
99302 ** SQLITE_OMIT_VACUUM macro.
99305 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
99307 ** Finalize a prepared statement. If there was an error, store the
99308 ** text of the error message in *pzErrMsg. Return the result code.
99310 static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
99311 int rc;
99312 rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
99313 if( rc ){
99314 sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
99316 return rc;
99320 ** Execute zSql on database db. Return an error code.
99322 static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
99323 sqlite3_stmt *pStmt;
99324 VVA_ONLY( int rc; )
99325 if( !zSql ){
99326 return SQLITE_NOMEM;
99328 if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
99329 sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
99330 return sqlite3_errcode(db);
99332 VVA_ONLY( rc = ) sqlite3_step(pStmt);
99333 assert( rc!=SQLITE_ROW || (db->flags&SQLITE_CountRows) );
99334 return vacuumFinalize(db, pStmt, pzErrMsg);
99338 ** Execute zSql on database db. The statement returns exactly
99339 ** one column. Execute this as SQL on the same database.
99341 static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
99342 sqlite3_stmt *pStmt;
99343 int rc;
99345 rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
99346 if( rc!=SQLITE_OK ) return rc;
99348 while( SQLITE_ROW==sqlite3_step(pStmt) ){
99349 rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
99350 if( rc!=SQLITE_OK ){
99351 vacuumFinalize(db, pStmt, pzErrMsg);
99352 return rc;
99356 return vacuumFinalize(db, pStmt, pzErrMsg);
99360 ** The non-standard VACUUM command is used to clean up the database,
99361 ** collapse free space, etc. It is modelled after the VACUUM command
99362 ** in PostgreSQL.
99364 ** In version 1.0.x of SQLite, the VACUUM command would call
99365 ** gdbm_reorganize() on all the database tables. But beginning
99366 ** with 2.0.0, SQLite no longer uses GDBM so this command has
99367 ** become a no-op.
99369 SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
99370 Vdbe *v = sqlite3GetVdbe(pParse);
99371 if( v ){
99372 sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
99374 return;
99378 ** This routine implements the OP_Vacuum opcode of the VDBE.
99380 SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
99381 int rc = SQLITE_OK; /* Return code from service routines */
99382 Btree *pMain; /* The database being vacuumed */
99383 Btree *pTemp; /* The temporary database we vacuum into */
99384 char *zSql = 0; /* SQL statements */
99385 int saved_flags; /* Saved value of the db->flags */
99386 int saved_nChange; /* Saved value of db->nChange */
99387 int saved_nTotalChange; /* Saved value of db->nTotalChange */
99388 void (*saved_xTrace)(void*,const char*); /* Saved db->xTrace */
99389 Db *pDb = 0; /* Database to detach at end of vacuum */
99390 int isMemDb; /* True if vacuuming a :memory: database */
99391 int nRes; /* Bytes of reserved space at the end of each page */
99392 int nDb; /* Number of attached databases */
99394 if( !db->autoCommit ){
99395 sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
99396 return SQLITE_ERROR;
99398 if( db->activeVdbeCnt>1 ){
99399 sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
99400 return SQLITE_ERROR;
99403 /* Save the current value of the database flags so that it can be
99404 ** restored before returning. Then set the writable-schema flag, and
99405 ** disable CHECK and foreign key constraints. */
99406 saved_flags = db->flags;
99407 saved_nChange = db->nChange;
99408 saved_nTotalChange = db->nTotalChange;
99409 saved_xTrace = db->xTrace;
99410 db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
99411 db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
99412 db->xTrace = 0;
99414 pMain = db->aDb[0].pBt;
99415 isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
99417 /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
99418 ** can be set to 'off' for this file, as it is not recovered if a crash
99419 ** occurs anyway. The integrity of the database is maintained by a
99420 ** (possibly synchronous) transaction opened on the main database before
99421 ** sqlite3BtreeCopyFile() is called.
99423 ** An optimisation would be to use a non-journaled pager.
99424 ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
99425 ** that actually made the VACUUM run slower. Very little journalling
99426 ** actually occurs when doing a vacuum since the vacuum_db is initially
99427 ** empty. Only the journal header is written. Apparently it takes more
99428 ** time to parse and run the PRAGMA to turn journalling off than it does
99429 ** to write the journal header file.
99431 nDb = db->nDb;
99432 if( sqlite3TempInMemory(db) ){
99433 zSql = "ATTACH ':memory:' AS vacuum_db;";
99434 }else{
99435 zSql = "ATTACH '' AS vacuum_db;";
99437 rc = execSql(db, pzErrMsg, zSql);
99438 if( db->nDb>nDb ){
99439 pDb = &db->aDb[db->nDb-1];
99440 assert( strcmp(pDb->zName,"vacuum_db")==0 );
99442 if( rc!=SQLITE_OK ) goto end_of_vacuum;
99443 pTemp = db->aDb[db->nDb-1].pBt;
99445 /* The call to execSql() to attach the temp database has left the file
99446 ** locked (as there was more than one active statement when the transaction
99447 ** to read the schema was concluded. Unlock it here so that this doesn't
99448 ** cause problems for the call to BtreeSetPageSize() below. */
99449 sqlite3BtreeCommit(pTemp);
99451 nRes = sqlite3BtreeGetReserve(pMain);
99453 /* A VACUUM cannot change the pagesize of an encrypted database. */
99454 #ifdef SQLITE_HAS_CODEC
99455 if( db->nextPagesize ){
99456 extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
99457 int nKey;
99458 char *zKey;
99459 sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
99460 if( nKey ) db->nextPagesize = 0;
99462 #endif
99464 /* Do not attempt to change the page size for a WAL database */
99465 if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
99466 ==PAGER_JOURNALMODE_WAL ){
99467 db->nextPagesize = 0;
99470 if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
99471 || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
99472 || NEVER(db->mallocFailed)
99474 rc = SQLITE_NOMEM;
99475 goto end_of_vacuum;
99477 rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
99478 if( rc!=SQLITE_OK ){
99479 goto end_of_vacuum;
99482 #ifndef SQLITE_OMIT_AUTOVACUUM
99483 sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
99484 sqlite3BtreeGetAutoVacuum(pMain));
99485 #endif
99487 /* Begin a transaction */
99488 rc = execSql(db, pzErrMsg, "BEGIN EXCLUSIVE;");
99489 if( rc!=SQLITE_OK ) goto end_of_vacuum;
99491 /* Query the schema of the main database. Create a mirror schema
99492 ** in the temporary database.
99494 rc = execExecSql(db, pzErrMsg,
99495 "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
99496 " FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
99497 " AND rootpage>0"
99499 if( rc!=SQLITE_OK ) goto end_of_vacuum;
99500 rc = execExecSql(db, pzErrMsg,
99501 "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
99502 " FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
99503 if( rc!=SQLITE_OK ) goto end_of_vacuum;
99504 rc = execExecSql(db, pzErrMsg,
99505 "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
99506 " FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
99507 if( rc!=SQLITE_OK ) goto end_of_vacuum;
99509 /* Loop through the tables in the main database. For each, do
99510 ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
99511 ** the contents to the temporary database.
99513 rc = execExecSql(db, pzErrMsg,
99514 "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
99515 "|| ' SELECT * FROM main.' || quote(name) || ';'"
99516 "FROM main.sqlite_master "
99517 "WHERE type = 'table' AND name!='sqlite_sequence' "
99518 " AND rootpage>0"
99520 if( rc!=SQLITE_OK ) goto end_of_vacuum;
99522 /* Copy over the sequence table
99524 rc = execExecSql(db, pzErrMsg,
99525 "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
99526 "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
99528 if( rc!=SQLITE_OK ) goto end_of_vacuum;
99529 rc = execExecSql(db, pzErrMsg,
99530 "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
99531 "|| ' SELECT * FROM main.' || quote(name) || ';' "
99532 "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
99534 if( rc!=SQLITE_OK ) goto end_of_vacuum;
99537 /* Copy the triggers, views, and virtual tables from the main database
99538 ** over to the temporary database. None of these objects has any
99539 ** associated storage, so all we have to do is copy their entries
99540 ** from the SQLITE_MASTER table.
99542 rc = execSql(db, pzErrMsg,
99543 "INSERT INTO vacuum_db.sqlite_master "
99544 " SELECT type, name, tbl_name, rootpage, sql"
99545 " FROM main.sqlite_master"
99546 " WHERE type='view' OR type='trigger'"
99547 " OR (type='table' AND rootpage=0)"
99549 if( rc ) goto end_of_vacuum;
99551 /* At this point, there is a write transaction open on both the
99552 ** vacuum database and the main database. Assuming no error occurs,
99553 ** both transactions are closed by this block - the main database
99554 ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
99555 ** call to sqlite3BtreeCommit().
99558 u32 meta;
99559 int i;
99561 /* This array determines which meta meta values are preserved in the
99562 ** vacuum. Even entries are the meta value number and odd entries
99563 ** are an increment to apply to the meta value after the vacuum.
99564 ** The increment is used to increase the schema cookie so that other
99565 ** connections to the same database will know to reread the schema.
99567 static const unsigned char aCopy[] = {
99568 BTREE_SCHEMA_VERSION, 1, /* Add one to the old schema cookie */
99569 BTREE_DEFAULT_CACHE_SIZE, 0, /* Preserve the default page cache size */
99570 BTREE_TEXT_ENCODING, 0, /* Preserve the text encoding */
99571 BTREE_USER_VERSION, 0, /* Preserve the user version */
99574 assert( 1==sqlite3BtreeIsInTrans(pTemp) );
99575 assert( 1==sqlite3BtreeIsInTrans(pMain) );
99577 /* Copy Btree meta values */
99578 for(i=0; i<ArraySize(aCopy); i+=2){
99579 /* GetMeta() and UpdateMeta() cannot fail in this context because
99580 ** we already have page 1 loaded into cache and marked dirty. */
99581 sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
99582 rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
99583 if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
99586 rc = sqlite3BtreeCopyFile(pMain, pTemp);
99587 if( rc!=SQLITE_OK ) goto end_of_vacuum;
99588 rc = sqlite3BtreeCommit(pTemp);
99589 if( rc!=SQLITE_OK ) goto end_of_vacuum;
99590 #ifndef SQLITE_OMIT_AUTOVACUUM
99591 sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
99592 #endif
99595 assert( rc==SQLITE_OK );
99596 rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
99598 end_of_vacuum:
99599 /* Restore the original value of db->flags */
99600 db->flags = saved_flags;
99601 db->nChange = saved_nChange;
99602 db->nTotalChange = saved_nTotalChange;
99603 db->xTrace = saved_xTrace;
99604 sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
99606 /* Currently there is an SQL level transaction open on the vacuum
99607 ** database. No locks are held on any other files (since the main file
99608 ** was committed at the btree level). So it safe to end the transaction
99609 ** by manually setting the autoCommit flag to true and detaching the
99610 ** vacuum database. The vacuum_db journal file is deleted when the pager
99611 ** is closed by the DETACH.
99613 db->autoCommit = 1;
99615 if( pDb ){
99616 sqlite3BtreeClose(pDb->pBt);
99617 pDb->pBt = 0;
99618 pDb->pSchema = 0;
99621 /* This both clears the schemas and reduces the size of the db->aDb[]
99622 ** array. */
99623 sqlite3ResetInternalSchema(db, -1);
99625 return rc;
99628 #endif /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
99630 /************** End of vacuum.c **********************************************/
99631 /************** Begin file vtab.c ********************************************/
99633 ** 2006 June 10
99635 ** The author disclaims copyright to this source code. In place of
99636 ** a legal notice, here is a blessing:
99638 ** May you do good and not evil.
99639 ** May you find forgiveness for yourself and forgive others.
99640 ** May you share freely, never taking more than you give.
99642 *************************************************************************
99643 ** This file contains code used to help implement virtual tables.
99645 #ifndef SQLITE_OMIT_VIRTUALTABLE
99648 ** Before a virtual table xCreate() or xConnect() method is invoked, the
99649 ** sqlite3.pVtabCtx member variable is set to point to an instance of
99650 ** this struct allocated on the stack. It is used by the implementation of
99651 ** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
99652 ** are invoked only from within xCreate and xConnect methods.
99654 struct VtabCtx {
99655 Table *pTab;
99656 VTable *pVTable;
99660 ** The actual function that does the work of creating a new module.
99661 ** This function implements the sqlite3_create_module() and
99662 ** sqlite3_create_module_v2() interfaces.
99664 static int createModule(
99665 sqlite3 *db, /* Database in which module is registered */
99666 const char *zName, /* Name assigned to this module */
99667 const sqlite3_module *pModule, /* The definition of the module */
99668 void *pAux, /* Context pointer for xCreate/xConnect */
99669 void (*xDestroy)(void *) /* Module destructor function */
99671 int rc, nName;
99672 Module *pMod;
99674 sqlite3_mutex_enter(db->mutex);
99675 nName = sqlite3Strlen30(zName);
99676 pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
99677 if( pMod ){
99678 Module *pDel;
99679 char *zCopy = (char *)(&pMod[1]);
99680 memcpy(zCopy, zName, nName+1);
99681 pMod->zName = zCopy;
99682 pMod->pModule = pModule;
99683 pMod->pAux = pAux;
99684 pMod->xDestroy = xDestroy;
99685 pDel = (Module *)sqlite3HashInsert(&db->aModule, zCopy, nName, (void*)pMod);
99686 if( pDel && pDel->xDestroy ){
99687 sqlite3ResetInternalSchema(db, -1);
99688 pDel->xDestroy(pDel->pAux);
99690 sqlite3DbFree(db, pDel);
99691 if( pDel==pMod ){
99692 db->mallocFailed = 1;
99694 }else if( xDestroy ){
99695 xDestroy(pAux);
99697 rc = sqlite3ApiExit(db, SQLITE_OK);
99698 sqlite3_mutex_leave(db->mutex);
99699 return rc;
99704 ** External API function used to create a new virtual-table module.
99706 SQLITE_API int sqlite3_create_module(
99707 sqlite3 *db, /* Database in which module is registered */
99708 const char *zName, /* Name assigned to this module */
99709 const sqlite3_module *pModule, /* The definition of the module */
99710 void *pAux /* Context pointer for xCreate/xConnect */
99712 return createModule(db, zName, pModule, pAux, 0);
99716 ** External API function used to create a new virtual-table module.
99718 SQLITE_API int sqlite3_create_module_v2(
99719 sqlite3 *db, /* Database in which module is registered */
99720 const char *zName, /* Name assigned to this module */
99721 const sqlite3_module *pModule, /* The definition of the module */
99722 void *pAux, /* Context pointer for xCreate/xConnect */
99723 void (*xDestroy)(void *) /* Module destructor function */
99725 return createModule(db, zName, pModule, pAux, xDestroy);
99729 ** Lock the virtual table so that it cannot be disconnected.
99730 ** Locks nest. Every lock should have a corresponding unlock.
99731 ** If an unlock is omitted, resources leaks will occur.
99733 ** If a disconnect is attempted while a virtual table is locked,
99734 ** the disconnect is deferred until all locks have been removed.
99736 SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
99737 pVTab->nRef++;
99742 ** pTab is a pointer to a Table structure representing a virtual-table.
99743 ** Return a pointer to the VTable object used by connection db to access
99744 ** this virtual-table, if one has been created, or NULL otherwise.
99746 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
99747 VTable *pVtab;
99748 assert( IsVirtual(pTab) );
99749 for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
99750 return pVtab;
99754 ** Decrement the ref-count on a virtual table object. When the ref-count
99755 ** reaches zero, call the xDisconnect() method to delete the object.
99757 SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
99758 sqlite3 *db = pVTab->db;
99760 assert( db );
99761 assert( pVTab->nRef>0 );
99762 assert( sqlite3SafetyCheckOk(db) );
99764 pVTab->nRef--;
99765 if( pVTab->nRef==0 ){
99766 sqlite3_vtab *p = pVTab->pVtab;
99767 if( p ){
99768 p->pModule->xDisconnect(p);
99770 sqlite3DbFree(db, pVTab);
99775 ** Table p is a virtual table. This function moves all elements in the
99776 ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
99777 ** database connections to be disconnected at the next opportunity.
99778 ** Except, if argument db is not NULL, then the entry associated with
99779 ** connection db is left in the p->pVTable list.
99781 static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
99782 VTable *pRet = 0;
99783 VTable *pVTable = p->pVTable;
99784 p->pVTable = 0;
99786 /* Assert that the mutex (if any) associated with the BtShared database
99787 ** that contains table p is held by the caller. See header comments
99788 ** above function sqlite3VtabUnlockList() for an explanation of why
99789 ** this makes it safe to access the sqlite3.pDisconnect list of any
99790 ** database connection that may have an entry in the p->pVTable list.
99792 assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
99794 while( pVTable ){
99795 sqlite3 *db2 = pVTable->db;
99796 VTable *pNext = pVTable->pNext;
99797 assert( db2 );
99798 if( db2==db ){
99799 pRet = pVTable;
99800 p->pVTable = pRet;
99801 pRet->pNext = 0;
99802 }else{
99803 pVTable->pNext = db2->pDisconnect;
99804 db2->pDisconnect = pVTable;
99806 pVTable = pNext;
99809 assert( !db || pRet );
99810 return pRet;
99815 ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
99817 ** This function may only be called when the mutexes associated with all
99818 ** shared b-tree databases opened using connection db are held by the
99819 ** caller. This is done to protect the sqlite3.pDisconnect list. The
99820 ** sqlite3.pDisconnect list is accessed only as follows:
99822 ** 1) By this function. In this case, all BtShared mutexes and the mutex
99823 ** associated with the database handle itself must be held.
99825 ** 2) By function vtabDisconnectAll(), when it adds a VTable entry to
99826 ** the sqlite3.pDisconnect list. In this case either the BtShared mutex
99827 ** associated with the database the virtual table is stored in is held
99828 ** or, if the virtual table is stored in a non-sharable database, then
99829 ** the database handle mutex is held.
99831 ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
99832 ** by multiple threads. It is thread-safe.
99834 SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
99835 VTable *p = db->pDisconnect;
99836 db->pDisconnect = 0;
99838 assert( sqlite3BtreeHoldsAllMutexes(db) );
99839 assert( sqlite3_mutex_held(db->mutex) );
99841 if( p ){
99842 sqlite3ExpirePreparedStatements(db);
99843 do {
99844 VTable *pNext = p->pNext;
99845 sqlite3VtabUnlock(p);
99846 p = pNext;
99847 }while( p );
99852 ** Clear any and all virtual-table information from the Table record.
99853 ** This routine is called, for example, just before deleting the Table
99854 ** record.
99856 ** Since it is a virtual-table, the Table structure contains a pointer
99857 ** to the head of a linked list of VTable structures. Each VTable
99858 ** structure is associated with a single sqlite3* user of the schema.
99859 ** The reference count of the VTable structure associated with database
99860 ** connection db is decremented immediately (which may lead to the
99861 ** structure being xDisconnected and free). Any other VTable structures
99862 ** in the list are moved to the sqlite3.pDisconnect list of the associated
99863 ** database connection.
99865 SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
99866 if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
99867 if( p->azModuleArg ){
99868 int i;
99869 for(i=0; i<p->nModuleArg; i++){
99870 sqlite3DbFree(db, p->azModuleArg[i]);
99872 sqlite3DbFree(db, p->azModuleArg);
99877 ** Add a new module argument to pTable->azModuleArg[].
99878 ** The string is not copied - the pointer is stored. The
99879 ** string will be freed automatically when the table is
99880 ** deleted.
99882 static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
99883 int i = pTable->nModuleArg++;
99884 int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
99885 char **azModuleArg;
99886 azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
99887 if( azModuleArg==0 ){
99888 int j;
99889 for(j=0; j<i; j++){
99890 sqlite3DbFree(db, pTable->azModuleArg[j]);
99892 sqlite3DbFree(db, zArg);
99893 sqlite3DbFree(db, pTable->azModuleArg);
99894 pTable->nModuleArg = 0;
99895 }else{
99896 azModuleArg[i] = zArg;
99897 azModuleArg[i+1] = 0;
99899 pTable->azModuleArg = azModuleArg;
99903 ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
99904 ** statement. The module name has been parsed, but the optional list
99905 ** of parameters that follow the module name are still pending.
99907 SQLITE_PRIVATE void sqlite3VtabBeginParse(
99908 Parse *pParse, /* Parsing context */
99909 Token *pName1, /* Name of new table, or database name */
99910 Token *pName2, /* Name of new table or NULL */
99911 Token *pModuleName /* Name of the module for the virtual table */
99913 int iDb; /* The database the table is being created in */
99914 Table *pTable; /* The new virtual table */
99915 sqlite3 *db; /* Database connection */
99917 sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, 0);
99918 pTable = pParse->pNewTable;
99919 if( pTable==0 ) return;
99920 assert( 0==pTable->pIndex );
99922 db = pParse->db;
99923 iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
99924 assert( iDb>=0 );
99926 pTable->tabFlags |= TF_Virtual;
99927 pTable->nModuleArg = 0;
99928 addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
99929 addModuleArgument(db, pTable, sqlite3DbStrDup(db, db->aDb[iDb].zName));
99930 addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
99931 pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
99933 #ifndef SQLITE_OMIT_AUTHORIZATION
99934 /* Creating a virtual table invokes the authorization callback twice.
99935 ** The first invocation, to obtain permission to INSERT a row into the
99936 ** sqlite_master table, has already been made by sqlite3StartTable().
99937 ** The second call, to obtain permission to create the table, is made now.
99939 if( pTable->azModuleArg ){
99940 sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
99941 pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
99943 #endif
99947 ** This routine takes the module argument that has been accumulating
99948 ** in pParse->zArg[] and appends it to the list of arguments on the
99949 ** virtual table currently under construction in pParse->pTable.
99951 static void addArgumentToVtab(Parse *pParse){
99952 if( pParse->sArg.z && ALWAYS(pParse->pNewTable) ){
99953 const char *z = (const char*)pParse->sArg.z;
99954 int n = pParse->sArg.n;
99955 sqlite3 *db = pParse->db;
99956 addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
99961 ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
99962 ** has been completely parsed.
99964 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
99965 Table *pTab = pParse->pNewTable; /* The table being constructed */
99966 sqlite3 *db = pParse->db; /* The database connection */
99968 if( pTab==0 ) return;
99969 addArgumentToVtab(pParse);
99970 pParse->sArg.z = 0;
99971 if( pTab->nModuleArg<1 ) return;
99973 /* If the CREATE VIRTUAL TABLE statement is being entered for the
99974 ** first time (in other words if the virtual table is actually being
99975 ** created now instead of just being read out of sqlite_master) then
99976 ** do additional initialization work and store the statement text
99977 ** in the sqlite_master table.
99979 if( !db->init.busy ){
99980 char *zStmt;
99981 char *zWhere;
99982 int iDb;
99983 Vdbe *v;
99985 /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
99986 if( pEnd ){
99987 pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
99989 zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
99991 /* A slot for the record has already been allocated in the
99992 ** SQLITE_MASTER table. We just need to update that slot with all
99993 ** the information we've collected.
99995 ** The VM register number pParse->regRowid holds the rowid of an
99996 ** entry in the sqlite_master table tht was created for this vtab
99997 ** by sqlite3StartTable().
99999 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
100000 sqlite3NestedParse(pParse,
100001 "UPDATE %Q.%s "
100002 "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
100003 "WHERE rowid=#%d",
100004 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
100005 pTab->zName,
100006 pTab->zName,
100007 zStmt,
100008 pParse->regRowid
100010 sqlite3DbFree(db, zStmt);
100011 v = sqlite3GetVdbe(pParse);
100012 sqlite3ChangeCookie(pParse, iDb);
100014 sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
100015 zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
100016 sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
100017 sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0,
100018 pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
100021 /* If we are rereading the sqlite_master table create the in-memory
100022 ** record of the table. The xConnect() method is not called until
100023 ** the first time the virtual table is used in an SQL statement. This
100024 ** allows a schema that contains virtual tables to be loaded before
100025 ** the required virtual table implementations are registered. */
100026 else {
100027 Table *pOld;
100028 Schema *pSchema = pTab->pSchema;
100029 const char *zName = pTab->zName;
100030 int nName = sqlite3Strlen30(zName);
100031 assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
100032 pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
100033 if( pOld ){
100034 db->mallocFailed = 1;
100035 assert( pTab==pOld ); /* Malloc must have failed inside HashInsert() */
100036 return;
100038 pParse->pNewTable = 0;
100043 ** The parser calls this routine when it sees the first token
100044 ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
100046 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
100047 addArgumentToVtab(pParse);
100048 pParse->sArg.z = 0;
100049 pParse->sArg.n = 0;
100053 ** The parser calls this routine for each token after the first token
100054 ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
100056 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
100057 Token *pArg = &pParse->sArg;
100058 if( pArg->z==0 ){
100059 pArg->z = p->z;
100060 pArg->n = p->n;
100061 }else{
100062 assert(pArg->z < p->z);
100063 pArg->n = (int)(&p->z[p->n] - pArg->z);
100068 ** Invoke a virtual table constructor (either xCreate or xConnect). The
100069 ** pointer to the function to invoke is passed as the fourth parameter
100070 ** to this procedure.
100072 static int vtabCallConstructor(
100073 sqlite3 *db,
100074 Table *pTab,
100075 Module *pMod,
100076 int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
100077 char **pzErr
100079 VtabCtx sCtx;
100080 VTable *pVTable;
100081 int rc;
100082 const char *const*azArg = (const char *const*)pTab->azModuleArg;
100083 int nArg = pTab->nModuleArg;
100084 char *zErr = 0;
100085 char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
100087 if( !zModuleName ){
100088 return SQLITE_NOMEM;
100091 pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
100092 if( !pVTable ){
100093 sqlite3DbFree(db, zModuleName);
100094 return SQLITE_NOMEM;
100096 pVTable->db = db;
100097 pVTable->pMod = pMod;
100099 /* Invoke the virtual table constructor */
100100 assert( &db->pVtabCtx );
100101 assert( xConstruct );
100102 sCtx.pTab = pTab;
100103 sCtx.pVTable = pVTable;
100104 db->pVtabCtx = &sCtx;
100105 rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
100106 db->pVtabCtx = 0;
100107 if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
100109 if( SQLITE_OK!=rc ){
100110 if( zErr==0 ){
100111 *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
100112 }else {
100113 *pzErr = sqlite3MPrintf(db, "%s", zErr);
100114 sqlite3_free(zErr);
100116 sqlite3DbFree(db, pVTable);
100117 }else if( ALWAYS(pVTable->pVtab) ){
100118 /* Justification of ALWAYS(): A correct vtab constructor must allocate
100119 ** the sqlite3_vtab object if successful. */
100120 pVTable->pVtab->pModule = pMod->pModule;
100121 pVTable->nRef = 1;
100122 if( sCtx.pTab ){
100123 const char *zFormat = "vtable constructor did not declare schema: %s";
100124 *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
100125 sqlite3VtabUnlock(pVTable);
100126 rc = SQLITE_ERROR;
100127 }else{
100128 int iCol;
100129 /* If everything went according to plan, link the new VTable structure
100130 ** into the linked list headed by pTab->pVTable. Then loop through the
100131 ** columns of the table to see if any of them contain the token "hidden".
100132 ** If so, set the Column.isHidden flag and remove the token from
100133 ** the type string. */
100134 pVTable->pNext = pTab->pVTable;
100135 pTab->pVTable = pVTable;
100137 for(iCol=0; iCol<pTab->nCol; iCol++){
100138 char *zType = pTab->aCol[iCol].zType;
100139 int nType;
100140 int i = 0;
100141 if( !zType ) continue;
100142 nType = sqlite3Strlen30(zType);
100143 if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
100144 for(i=0; i<nType; i++){
100145 if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
100146 && (zType[i+7]=='\0' || zType[i+7]==' ')
100149 break;
100153 if( i<nType ){
100154 int j;
100155 int nDel = 6 + (zType[i+6] ? 1 : 0);
100156 for(j=i; (j+nDel)<=nType; j++){
100157 zType[j] = zType[j+nDel];
100159 if( zType[i]=='\0' && i>0 ){
100160 assert(zType[i-1]==' ');
100161 zType[i-1] = '\0';
100163 pTab->aCol[iCol].isHidden = 1;
100169 sqlite3DbFree(db, zModuleName);
100170 return rc;
100174 ** This function is invoked by the parser to call the xConnect() method
100175 ** of the virtual table pTab. If an error occurs, an error code is returned
100176 ** and an error left in pParse.
100178 ** This call is a no-op if table pTab is not a virtual table.
100180 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
100181 sqlite3 *db = pParse->db;
100182 const char *zMod;
100183 Module *pMod;
100184 int rc;
100186 assert( pTab );
100187 if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
100188 return SQLITE_OK;
100191 /* Locate the required virtual table module */
100192 zMod = pTab->azModuleArg[0];
100193 pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
100195 if( !pMod ){
100196 const char *zModule = pTab->azModuleArg[0];
100197 sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
100198 rc = SQLITE_ERROR;
100199 }else{
100200 char *zErr = 0;
100201 rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
100202 if( rc!=SQLITE_OK ){
100203 sqlite3ErrorMsg(pParse, "%s", zErr);
100205 sqlite3DbFree(db, zErr);
100208 return rc;
100211 ** Grow the db->aVTrans[] array so that there is room for at least one
100212 ** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
100214 static int growVTrans(sqlite3 *db){
100215 const int ARRAY_INCR = 5;
100217 /* Grow the sqlite3.aVTrans array if required */
100218 if( (db->nVTrans%ARRAY_INCR)==0 ){
100219 VTable **aVTrans;
100220 int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
100221 aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
100222 if( !aVTrans ){
100223 return SQLITE_NOMEM;
100225 memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
100226 db->aVTrans = aVTrans;
100229 return SQLITE_OK;
100233 ** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
100234 ** have already been reserved using growVTrans().
100236 static void addToVTrans(sqlite3 *db, VTable *pVTab){
100237 /* Add pVtab to the end of sqlite3.aVTrans */
100238 db->aVTrans[db->nVTrans++] = pVTab;
100239 sqlite3VtabLock(pVTab);
100243 ** This function is invoked by the vdbe to call the xCreate method
100244 ** of the virtual table named zTab in database iDb.
100246 ** If an error occurs, *pzErr is set to point an an English language
100247 ** description of the error and an SQLITE_XXX error code is returned.
100248 ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
100250 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
100251 int rc = SQLITE_OK;
100252 Table *pTab;
100253 Module *pMod;
100254 const char *zMod;
100256 pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
100257 assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
100259 /* Locate the required virtual table module */
100260 zMod = pTab->azModuleArg[0];
100261 pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
100263 /* If the module has been registered and includes a Create method,
100264 ** invoke it now. If the module has not been registered, return an
100265 ** error. Otherwise, do nothing.
100267 if( !pMod ){
100268 *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
100269 rc = SQLITE_ERROR;
100270 }else{
100271 rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
100274 /* Justification of ALWAYS(): The xConstructor method is required to
100275 ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
100276 if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
100277 rc = growVTrans(db);
100278 if( rc==SQLITE_OK ){
100279 addToVTrans(db, sqlite3GetVTable(db, pTab));
100283 return rc;
100287 ** This function is used to set the schema of a virtual table. It is only
100288 ** valid to call this function from within the xCreate() or xConnect() of a
100289 ** virtual table module.
100291 SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
100292 Parse *pParse;
100294 int rc = SQLITE_OK;
100295 Table *pTab;
100296 char *zErr = 0;
100298 sqlite3_mutex_enter(db->mutex);
100299 if( !db->pVtabCtx || !(pTab = db->pVtabCtx->pTab) ){
100300 sqlite3Error(db, SQLITE_MISUSE, 0);
100301 sqlite3_mutex_leave(db->mutex);
100302 return SQLITE_MISUSE_BKPT;
100304 assert( (pTab->tabFlags & TF_Virtual)!=0 );
100306 pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
100307 if( pParse==0 ){
100308 rc = SQLITE_NOMEM;
100309 }else{
100310 pParse->declareVtab = 1;
100311 pParse->db = db;
100312 pParse->nQueryLoop = 1;
100314 if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr)
100315 && pParse->pNewTable
100316 && !db->mallocFailed
100317 && !pParse->pNewTable->pSelect
100318 && (pParse->pNewTable->tabFlags & TF_Virtual)==0
100320 if( !pTab->aCol ){
100321 pTab->aCol = pParse->pNewTable->aCol;
100322 pTab->nCol = pParse->pNewTable->nCol;
100323 pParse->pNewTable->nCol = 0;
100324 pParse->pNewTable->aCol = 0;
100326 db->pVtabCtx->pTab = 0;
100327 }else{
100328 sqlite3Error(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
100329 sqlite3DbFree(db, zErr);
100330 rc = SQLITE_ERROR;
100332 pParse->declareVtab = 0;
100334 if( pParse->pVdbe ){
100335 sqlite3VdbeFinalize(pParse->pVdbe);
100337 sqlite3DeleteTable(db, pParse->pNewTable);
100338 sqlite3StackFree(db, pParse);
100341 assert( (rc&0xff)==rc );
100342 rc = sqlite3ApiExit(db, rc);
100343 sqlite3_mutex_leave(db->mutex);
100344 return rc;
100348 ** This function is invoked by the vdbe to call the xDestroy method
100349 ** of the virtual table named zTab in database iDb. This occurs
100350 ** when a DROP TABLE is mentioned.
100352 ** This call is a no-op if zTab is not a virtual table.
100354 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
100355 int rc = SQLITE_OK;
100356 Table *pTab;
100358 pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
100359 if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
100360 VTable *p = vtabDisconnectAll(db, pTab);
100362 assert( rc==SQLITE_OK );
100363 rc = p->pMod->pModule->xDestroy(p->pVtab);
100365 /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
100366 if( rc==SQLITE_OK ){
100367 assert( pTab->pVTable==p && p->pNext==0 );
100368 p->pVtab = 0;
100369 pTab->pVTable = 0;
100370 sqlite3VtabUnlock(p);
100374 return rc;
100378 ** This function invokes either the xRollback or xCommit method
100379 ** of each of the virtual tables in the sqlite3.aVTrans array. The method
100380 ** called is identified by the second argument, "offset", which is
100381 ** the offset of the method to call in the sqlite3_module structure.
100383 ** The array is cleared after invoking the callbacks.
100385 static void callFinaliser(sqlite3 *db, int offset){
100386 int i;
100387 if( db->aVTrans ){
100388 for(i=0; i<db->nVTrans; i++){
100389 VTable *pVTab = db->aVTrans[i];
100390 sqlite3_vtab *p = pVTab->pVtab;
100391 if( p ){
100392 int (*x)(sqlite3_vtab *);
100393 x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
100394 if( x ) x(p);
100396 pVTab->iSavepoint = 0;
100397 sqlite3VtabUnlock(pVTab);
100399 sqlite3DbFree(db, db->aVTrans);
100400 db->nVTrans = 0;
100401 db->aVTrans = 0;
100406 ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
100407 ** array. Return the error code for the first error that occurs, or
100408 ** SQLITE_OK if all xSync operations are successful.
100410 ** Set *pzErrmsg to point to a buffer that should be released using
100411 ** sqlite3DbFree() containing an error message, if one is available.
100413 SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, char **pzErrmsg){
100414 int i;
100415 int rc = SQLITE_OK;
100416 VTable **aVTrans = db->aVTrans;
100418 db->aVTrans = 0;
100419 for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
100420 int (*x)(sqlite3_vtab *);
100421 sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
100422 if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
100423 rc = x(pVtab);
100424 sqlite3DbFree(db, *pzErrmsg);
100425 *pzErrmsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
100426 sqlite3_free(pVtab->zErrMsg);
100429 db->aVTrans = aVTrans;
100430 return rc;
100434 ** Invoke the xRollback method of all virtual tables in the
100435 ** sqlite3.aVTrans array. Then clear the array itself.
100437 SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
100438 callFinaliser(db, offsetof(sqlite3_module,xRollback));
100439 return SQLITE_OK;
100443 ** Invoke the xCommit method of all virtual tables in the
100444 ** sqlite3.aVTrans array. Then clear the array itself.
100446 SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
100447 callFinaliser(db, offsetof(sqlite3_module,xCommit));
100448 return SQLITE_OK;
100452 ** If the virtual table pVtab supports the transaction interface
100453 ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
100454 ** not currently open, invoke the xBegin method now.
100456 ** If the xBegin call is successful, place the sqlite3_vtab pointer
100457 ** in the sqlite3.aVTrans array.
100459 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
100460 int rc = SQLITE_OK;
100461 const sqlite3_module *pModule;
100463 /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
100464 ** than zero, then this function is being called from within a
100465 ** virtual module xSync() callback. It is illegal to write to
100466 ** virtual module tables in this case, so return SQLITE_LOCKED.
100468 if( sqlite3VtabInSync(db) ){
100469 return SQLITE_LOCKED;
100471 if( !pVTab ){
100472 return SQLITE_OK;
100474 pModule = pVTab->pVtab->pModule;
100476 if( pModule->xBegin ){
100477 int i;
100479 /* If pVtab is already in the aVTrans array, return early */
100480 for(i=0; i<db->nVTrans; i++){
100481 if( db->aVTrans[i]==pVTab ){
100482 return SQLITE_OK;
100486 /* Invoke the xBegin method. If successful, add the vtab to the
100487 ** sqlite3.aVTrans[] array. */
100488 rc = growVTrans(db);
100489 if( rc==SQLITE_OK ){
100490 rc = pModule->xBegin(pVTab->pVtab);
100491 if( rc==SQLITE_OK ){
100492 addToVTrans(db, pVTab);
100496 return rc;
100500 ** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
100501 ** virtual tables that currently have an open transaction. Pass iSavepoint
100502 ** as the second argument to the virtual table method invoked.
100504 ** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
100505 ** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is
100506 ** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
100507 ** an open transaction is invoked.
100509 ** If any virtual table method returns an error code other than SQLITE_OK,
100510 ** processing is abandoned and the error returned to the caller of this
100511 ** function immediately. If all calls to virtual table methods are successful,
100512 ** SQLITE_OK is returned.
100514 SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
100515 int rc = SQLITE_OK;
100517 assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
100518 assert( iSavepoint>=0 );
100519 if( db->aVTrans ){
100520 int i;
100521 for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
100522 VTable *pVTab = db->aVTrans[i];
100523 const sqlite3_module *pMod = pVTab->pMod->pModule;
100524 if( pVTab->pVtab && pMod->iVersion>=2 ){
100525 int (*xMethod)(sqlite3_vtab *, int);
100526 switch( op ){
100527 case SAVEPOINT_BEGIN:
100528 xMethod = pMod->xSavepoint;
100529 pVTab->iSavepoint = iSavepoint+1;
100530 break;
100531 case SAVEPOINT_ROLLBACK:
100532 xMethod = pMod->xRollbackTo;
100533 break;
100534 default:
100535 xMethod = pMod->xRelease;
100536 break;
100538 if( xMethod && pVTab->iSavepoint>iSavepoint ){
100539 rc = xMethod(pVTab->pVtab, iSavepoint);
100544 return rc;
100548 ** The first parameter (pDef) is a function implementation. The
100549 ** second parameter (pExpr) is the first argument to this function.
100550 ** If pExpr is a column in a virtual table, then let the virtual
100551 ** table implementation have an opportunity to overload the function.
100553 ** This routine is used to allow virtual table implementations to
100554 ** overload MATCH, LIKE, GLOB, and REGEXP operators.
100556 ** Return either the pDef argument (indicating no change) or a
100557 ** new FuncDef structure that is marked as ephemeral using the
100558 ** SQLITE_FUNC_EPHEM flag.
100560 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
100561 sqlite3 *db, /* Database connection for reporting malloc problems */
100562 FuncDef *pDef, /* Function to possibly overload */
100563 int nArg, /* Number of arguments to the function */
100564 Expr *pExpr /* First argument to the function */
100566 Table *pTab;
100567 sqlite3_vtab *pVtab;
100568 sqlite3_module *pMod;
100569 void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
100570 void *pArg = 0;
100571 FuncDef *pNew;
100572 int rc = 0;
100573 char *zLowerName;
100574 unsigned char *z;
100577 /* Check to see the left operand is a column in a virtual table */
100578 if( NEVER(pExpr==0) ) return pDef;
100579 if( pExpr->op!=TK_COLUMN ) return pDef;
100580 pTab = pExpr->pTab;
100581 if( NEVER(pTab==0) ) return pDef;
100582 if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
100583 pVtab = sqlite3GetVTable(db, pTab)->pVtab;
100584 assert( pVtab!=0 );
100585 assert( pVtab->pModule!=0 );
100586 pMod = (sqlite3_module *)pVtab->pModule;
100587 if( pMod->xFindFunction==0 ) return pDef;
100589 /* Call the xFindFunction method on the virtual table implementation
100590 ** to see if the implementation wants to overload this function
100592 zLowerName = sqlite3DbStrDup(db, pDef->zName);
100593 if( zLowerName ){
100594 for(z=(unsigned char*)zLowerName; *z; z++){
100595 *z = sqlite3UpperToLower[*z];
100597 rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
100598 sqlite3DbFree(db, zLowerName);
100600 if( rc==0 ){
100601 return pDef;
100604 /* Create a new ephemeral function definition for the overloaded
100605 ** function */
100606 pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
100607 + sqlite3Strlen30(pDef->zName) + 1);
100608 if( pNew==0 ){
100609 return pDef;
100611 *pNew = *pDef;
100612 pNew->zName = (char *)&pNew[1];
100613 memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
100614 pNew->xFunc = xFunc;
100615 pNew->pUserData = pArg;
100616 pNew->flags |= SQLITE_FUNC_EPHEM;
100617 return pNew;
100621 ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
100622 ** array so that an OP_VBegin will get generated for it. Add pTab to the
100623 ** array if it is missing. If pTab is already in the array, this routine
100624 ** is a no-op.
100626 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
100627 Parse *pToplevel = sqlite3ParseToplevel(pParse);
100628 int i, n;
100629 Table **apVtabLock;
100631 assert( IsVirtual(pTab) );
100632 for(i=0; i<pToplevel->nVtabLock; i++){
100633 if( pTab==pToplevel->apVtabLock[i] ) return;
100635 n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
100636 apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);
100637 if( apVtabLock ){
100638 pToplevel->apVtabLock = apVtabLock;
100639 pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
100640 }else{
100641 pToplevel->db->mallocFailed = 1;
100646 ** Return the ON CONFLICT resolution mode in effect for the virtual
100647 ** table update operation currently in progress.
100649 ** The results of this routine are undefined unless it is called from
100650 ** within an xUpdate method.
100652 SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){
100653 static const unsigned char aMap[] = {
100654 SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE
100656 assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
100657 assert( OE_Ignore==4 && OE_Replace==5 );
100658 assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
100659 return (int)aMap[db->vtabOnConflict-1];
100663 ** Call from within the xCreate() or xConnect() methods to provide
100664 ** the SQLite core with additional information about the behavior
100665 ** of the virtual table being implemented.
100667 SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){
100668 va_list ap;
100669 int rc = SQLITE_OK;
100671 sqlite3_mutex_enter(db->mutex);
100673 va_start(ap, op);
100674 switch( op ){
100675 case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
100676 VtabCtx *p = db->pVtabCtx;
100677 if( !p ){
100678 rc = SQLITE_MISUSE_BKPT;
100679 }else{
100680 assert( p->pTab==0 || (p->pTab->tabFlags & TF_Virtual)!=0 );
100681 p->pVTable->bConstraint = (u8)va_arg(ap, int);
100683 break;
100685 default:
100686 rc = SQLITE_MISUSE_BKPT;
100687 break;
100689 va_end(ap);
100691 if( rc!=SQLITE_OK ) sqlite3Error(db, rc, 0);
100692 sqlite3_mutex_leave(db->mutex);
100693 return rc;
100696 #endif /* SQLITE_OMIT_VIRTUALTABLE */
100698 /************** End of vtab.c ************************************************/
100699 /************** Begin file where.c *******************************************/
100701 ** 2001 September 15
100703 ** The author disclaims copyright to this source code. In place of
100704 ** a legal notice, here is a blessing:
100706 ** May you do good and not evil.
100707 ** May you find forgiveness for yourself and forgive others.
100708 ** May you share freely, never taking more than you give.
100710 *************************************************************************
100711 ** This module contains C code that generates VDBE code used to process
100712 ** the WHERE clause of SQL statements. This module is responsible for
100713 ** generating the code that loops through a table looking for applicable
100714 ** rows. Indices are selected and used to speed the search when doing
100715 ** so is applicable. Because this module is responsible for selecting
100716 ** indices, you might also think of this module as the "query optimizer".
100721 ** Trace output macros
100723 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
100724 SQLITE_PRIVATE int sqlite3WhereTrace = 0;
100725 #endif
100726 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
100727 # define WHERETRACE(X) if(sqlite3WhereTrace) sqlite3DebugPrintf X
100728 #else
100729 # define WHERETRACE(X)
100730 #endif
100732 /* Forward reference
100734 typedef struct WhereClause WhereClause;
100735 typedef struct WhereMaskSet WhereMaskSet;
100736 typedef struct WhereOrInfo WhereOrInfo;
100737 typedef struct WhereAndInfo WhereAndInfo;
100738 typedef struct WhereCost WhereCost;
100741 ** The query generator uses an array of instances of this structure to
100742 ** help it analyze the subexpressions of the WHERE clause. Each WHERE
100743 ** clause subexpression is separated from the others by AND operators,
100744 ** usually, or sometimes subexpressions separated by OR.
100746 ** All WhereTerms are collected into a single WhereClause structure.
100747 ** The following identity holds:
100749 ** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
100751 ** When a term is of the form:
100753 ** X <op> <expr>
100755 ** where X is a column name and <op> is one of certain operators,
100756 ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
100757 ** cursor number and column number for X. WhereTerm.eOperator records
100758 ** the <op> using a bitmask encoding defined by WO_xxx below. The
100759 ** use of a bitmask encoding for the operator allows us to search
100760 ** quickly for terms that match any of several different operators.
100762 ** A WhereTerm might also be two or more subterms connected by OR:
100764 ** (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
100766 ** In this second case, wtFlag as the TERM_ORINFO set and eOperator==WO_OR
100767 ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
100768 ** is collected about the
100770 ** If a term in the WHERE clause does not match either of the two previous
100771 ** categories, then eOperator==0. The WhereTerm.pExpr field is still set
100772 ** to the original subexpression content and wtFlags is set up appropriately
100773 ** but no other fields in the WhereTerm object are meaningful.
100775 ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
100776 ** but they do so indirectly. A single WhereMaskSet structure translates
100777 ** cursor number into bits and the translated bit is stored in the prereq
100778 ** fields. The translation is used in order to maximize the number of
100779 ** bits that will fit in a Bitmask. The VDBE cursor numbers might be
100780 ** spread out over the non-negative integers. For example, the cursor
100781 ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The WhereMaskSet
100782 ** translates these sparse cursor numbers into consecutive integers
100783 ** beginning with 0 in order to make the best possible use of the available
100784 ** bits in the Bitmask. So, in the example above, the cursor numbers
100785 ** would be mapped into integers 0 through 7.
100787 ** The number of terms in a join is limited by the number of bits
100788 ** in prereqRight and prereqAll. The default is 64 bits, hence SQLite
100789 ** is only able to process joins with 64 or fewer tables.
100791 typedef struct WhereTerm WhereTerm;
100792 struct WhereTerm {
100793 Expr *pExpr; /* Pointer to the subexpression that is this term */
100794 int iParent; /* Disable pWC->a[iParent] when this term disabled */
100795 int leftCursor; /* Cursor number of X in "X <op> <expr>" */
100796 union {
100797 int leftColumn; /* Column number of X in "X <op> <expr>" */
100798 WhereOrInfo *pOrInfo; /* Extra information if eOperator==WO_OR */
100799 WhereAndInfo *pAndInfo; /* Extra information if eOperator==WO_AND */
100801 u16 eOperator; /* A WO_xx value describing <op> */
100802 u8 wtFlags; /* TERM_xxx bit flags. See below */
100803 u8 nChild; /* Number of children that must disable us */
100804 WhereClause *pWC; /* The clause this term is part of */
100805 Bitmask prereqRight; /* Bitmask of tables used by pExpr->pRight */
100806 Bitmask prereqAll; /* Bitmask of tables referenced by pExpr */
100810 ** Allowed values of WhereTerm.wtFlags
100812 #define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(db, pExpr) */
100813 #define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */
100814 #define TERM_CODED 0x04 /* This term is already coded */
100815 #define TERM_COPIED 0x08 /* Has a child */
100816 #define TERM_ORINFO 0x10 /* Need to free the WhereTerm.u.pOrInfo object */
100817 #define TERM_ANDINFO 0x20 /* Need to free the WhereTerm.u.pAndInfo obj */
100818 #define TERM_OR_OK 0x40 /* Used during OR-clause processing */
100819 #ifdef SQLITE_ENABLE_STAT3
100820 # define TERM_VNULL 0x80 /* Manufactured x>NULL or x<=NULL term */
100821 #else
100822 # define TERM_VNULL 0x00 /* Disabled if not using stat3 */
100823 #endif
100826 ** An instance of the following structure holds all information about a
100827 ** WHERE clause. Mostly this is a container for one or more WhereTerms.
100829 ** Explanation of pOuter: For a WHERE clause of the form
100831 ** a AND ((b AND c) OR (d AND e)) AND f
100833 ** There are separate WhereClause objects for the whole clause and for
100834 ** the subclauses "(b AND c)" and "(d AND e)". The pOuter field of the
100835 ** subclauses points to the WhereClause object for the whole clause.
100837 struct WhereClause {
100838 Parse *pParse; /* The parser context */
100839 WhereMaskSet *pMaskSet; /* Mapping of table cursor numbers to bitmasks */
100840 Bitmask vmask; /* Bitmask identifying virtual table cursors */
100841 WhereClause *pOuter; /* Outer conjunction */
100842 u8 op; /* Split operator. TK_AND or TK_OR */
100843 u16 wctrlFlags; /* Might include WHERE_AND_ONLY */
100844 int nTerm; /* Number of terms */
100845 int nSlot; /* Number of entries in a[] */
100846 WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */
100847 #if defined(SQLITE_SMALL_STACK)
100848 WhereTerm aStatic[1]; /* Initial static space for a[] */
100849 #else
100850 WhereTerm aStatic[8]; /* Initial static space for a[] */
100851 #endif
100855 ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
100856 ** a dynamically allocated instance of the following structure.
100858 struct WhereOrInfo {
100859 WhereClause wc; /* Decomposition into subterms */
100860 Bitmask indexable; /* Bitmask of all indexable tables in the clause */
100864 ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
100865 ** a dynamically allocated instance of the following structure.
100867 struct WhereAndInfo {
100868 WhereClause wc; /* The subexpression broken out */
100872 ** An instance of the following structure keeps track of a mapping
100873 ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
100875 ** The VDBE cursor numbers are small integers contained in
100876 ** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
100877 ** clause, the cursor numbers might not begin with 0 and they might
100878 ** contain gaps in the numbering sequence. But we want to make maximum
100879 ** use of the bits in our bitmasks. This structure provides a mapping
100880 ** from the sparse cursor numbers into consecutive integers beginning
100881 ** with 0.
100883 ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
100884 ** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
100886 ** For example, if the WHERE clause expression used these VDBE
100887 ** cursors: 4, 5, 8, 29, 57, 73. Then the WhereMaskSet structure
100888 ** would map those cursor numbers into bits 0 through 5.
100890 ** Note that the mapping is not necessarily ordered. In the example
100891 ** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
100892 ** 57->5, 73->4. Or one of 719 other combinations might be used. It
100893 ** does not really matter. What is important is that sparse cursor
100894 ** numbers all get mapped into bit numbers that begin with 0 and contain
100895 ** no gaps.
100897 struct WhereMaskSet {
100898 int n; /* Number of assigned cursor values */
100899 int ix[BMS]; /* Cursor assigned to each bit */
100903 ** A WhereCost object records a lookup strategy and the estimated
100904 ** cost of pursuing that strategy.
100906 struct WhereCost {
100907 WherePlan plan; /* The lookup strategy */
100908 double rCost; /* Overall cost of pursuing this search strategy */
100909 Bitmask used; /* Bitmask of cursors used by this plan */
100913 ** Bitmasks for the operators that indices are able to exploit. An
100914 ** OR-ed combination of these values can be used when searching for
100915 ** terms in the where clause.
100917 #define WO_IN 0x001
100918 #define WO_EQ 0x002
100919 #define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
100920 #define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
100921 #define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
100922 #define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
100923 #define WO_MATCH 0x040
100924 #define WO_ISNULL 0x080
100925 #define WO_OR 0x100 /* Two or more OR-connected terms */
100926 #define WO_AND 0x200 /* Two or more AND-connected terms */
100927 #define WO_NOOP 0x800 /* This term does not restrict search space */
100929 #define WO_ALL 0xfff /* Mask of all possible WO_* values */
100930 #define WO_SINGLE 0x0ff /* Mask of all non-compound WO_* values */
100933 ** Value for wsFlags returned by bestIndex() and stored in
100934 ** WhereLevel.wsFlags. These flags determine which search
100935 ** strategies are appropriate.
100937 ** The least significant 12 bits is reserved as a mask for WO_ values above.
100938 ** The WhereLevel.wsFlags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
100939 ** But if the table is the right table of a left join, WhereLevel.wsFlags
100940 ** is set to WO_IN|WO_EQ. The WhereLevel.wsFlags field can then be used as
100941 ** the "op" parameter to findTerm when we are resolving equality constraints.
100942 ** ISNULL constraints will then not be used on the right table of a left
100943 ** join. Tickets #2177 and #2189.
100945 #define WHERE_ROWID_EQ 0x00001000 /* rowid=EXPR or rowid IN (...) */
100946 #define WHERE_ROWID_RANGE 0x00002000 /* rowid<EXPR and/or rowid>EXPR */
100947 #define WHERE_COLUMN_EQ 0x00010000 /* x=EXPR or x IN (...) or x IS NULL */
100948 #define WHERE_COLUMN_RANGE 0x00020000 /* x<EXPR and/or x>EXPR */
100949 #define WHERE_COLUMN_IN 0x00040000 /* x IN (...) */
100950 #define WHERE_COLUMN_NULL 0x00080000 /* x IS NULL */
100951 #define WHERE_INDEXED 0x000f0000 /* Anything that uses an index */
100952 #define WHERE_NOT_FULLSCAN 0x100f3000 /* Does not do a full table scan */
100953 #define WHERE_IN_ABLE 0x000f1000 /* Able to support an IN operator */
100954 #define WHERE_TOP_LIMIT 0x00100000 /* x<EXPR or x<=EXPR constraint */
100955 #define WHERE_BTM_LIMIT 0x00200000 /* x>EXPR or x>=EXPR constraint */
100956 #define WHERE_BOTH_LIMIT 0x00300000 /* Both x>EXPR and x<EXPR */
100957 #define WHERE_IDX_ONLY 0x00800000 /* Use index only - omit table */
100958 #define WHERE_ORDERBY 0x01000000 /* Output will appear in correct order */
100959 #define WHERE_REVERSE 0x02000000 /* Scan in reverse order */
100960 #define WHERE_UNIQUE 0x04000000 /* Selects no more than one row */
100961 #define WHERE_VIRTUALTABLE 0x08000000 /* Use virtual-table processing */
100962 #define WHERE_MULTI_OR 0x10000000 /* OR using multiple indices */
100963 #define WHERE_TEMP_INDEX 0x20000000 /* Uses an ephemeral index */
100964 #define WHERE_DISTINCT 0x40000000 /* Correct order for DISTINCT */
100967 ** Initialize a preallocated WhereClause structure.
100969 static void whereClauseInit(
100970 WhereClause *pWC, /* The WhereClause to be initialized */
100971 Parse *pParse, /* The parsing context */
100972 WhereMaskSet *pMaskSet, /* Mapping from table cursor numbers to bitmasks */
100973 u16 wctrlFlags /* Might include WHERE_AND_ONLY */
100975 pWC->pParse = pParse;
100976 pWC->pMaskSet = pMaskSet;
100977 pWC->pOuter = 0;
100978 pWC->nTerm = 0;
100979 pWC->nSlot = ArraySize(pWC->aStatic);
100980 pWC->a = pWC->aStatic;
100981 pWC->vmask = 0;
100982 pWC->wctrlFlags = wctrlFlags;
100985 /* Forward reference */
100986 static void whereClauseClear(WhereClause*);
100989 ** Deallocate all memory associated with a WhereOrInfo object.
100991 static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
100992 whereClauseClear(&p->wc);
100993 sqlite3DbFree(db, p);
100997 ** Deallocate all memory associated with a WhereAndInfo object.
100999 static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
101000 whereClauseClear(&p->wc);
101001 sqlite3DbFree(db, p);
101005 ** Deallocate a WhereClause structure. The WhereClause structure
101006 ** itself is not freed. This routine is the inverse of whereClauseInit().
101008 static void whereClauseClear(WhereClause *pWC){
101009 int i;
101010 WhereTerm *a;
101011 sqlite3 *db = pWC->pParse->db;
101012 for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
101013 if( a->wtFlags & TERM_DYNAMIC ){
101014 sqlite3ExprDelete(db, a->pExpr);
101016 if( a->wtFlags & TERM_ORINFO ){
101017 whereOrInfoDelete(db, a->u.pOrInfo);
101018 }else if( a->wtFlags & TERM_ANDINFO ){
101019 whereAndInfoDelete(db, a->u.pAndInfo);
101022 if( pWC->a!=pWC->aStatic ){
101023 sqlite3DbFree(db, pWC->a);
101028 ** Add a single new WhereTerm entry to the WhereClause object pWC.
101029 ** The new WhereTerm object is constructed from Expr p and with wtFlags.
101030 ** The index in pWC->a[] of the new WhereTerm is returned on success.
101031 ** 0 is returned if the new WhereTerm could not be added due to a memory
101032 ** allocation error. The memory allocation failure will be recorded in
101033 ** the db->mallocFailed flag so that higher-level functions can detect it.
101035 ** This routine will increase the size of the pWC->a[] array as necessary.
101037 ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
101038 ** for freeing the expression p is assumed by the WhereClause object pWC.
101039 ** This is true even if this routine fails to allocate a new WhereTerm.
101041 ** WARNING: This routine might reallocate the space used to store
101042 ** WhereTerms. All pointers to WhereTerms should be invalidated after
101043 ** calling this routine. Such pointers may be reinitialized by referencing
101044 ** the pWC->a[] array.
101046 static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
101047 WhereTerm *pTerm;
101048 int idx;
101049 testcase( wtFlags & TERM_VIRTUAL ); /* EV: R-00211-15100 */
101050 if( pWC->nTerm>=pWC->nSlot ){
101051 WhereTerm *pOld = pWC->a;
101052 sqlite3 *db = pWC->pParse->db;
101053 pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
101054 if( pWC->a==0 ){
101055 if( wtFlags & TERM_DYNAMIC ){
101056 sqlite3ExprDelete(db, p);
101058 pWC->a = pOld;
101059 return 0;
101061 memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
101062 if( pOld!=pWC->aStatic ){
101063 sqlite3DbFree(db, pOld);
101065 pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
101067 pTerm = &pWC->a[idx = pWC->nTerm++];
101068 pTerm->pExpr = p;
101069 pTerm->wtFlags = wtFlags;
101070 pTerm->pWC = pWC;
101071 pTerm->iParent = -1;
101072 return idx;
101076 ** This routine identifies subexpressions in the WHERE clause where
101077 ** each subexpression is separated by the AND operator or some other
101078 ** operator specified in the op parameter. The WhereClause structure
101079 ** is filled with pointers to subexpressions. For example:
101081 ** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
101082 ** \________/ \_______________/ \________________/
101083 ** slot[0] slot[1] slot[2]
101085 ** The original WHERE clause in pExpr is unaltered. All this routine
101086 ** does is make slot[] entries point to substructure within pExpr.
101088 ** In the previous sentence and in the diagram, "slot[]" refers to
101089 ** the WhereClause.a[] array. The slot[] array grows as needed to contain
101090 ** all terms of the WHERE clause.
101092 static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
101093 pWC->op = (u8)op;
101094 if( pExpr==0 ) return;
101095 if( pExpr->op!=op ){
101096 whereClauseInsert(pWC, pExpr, 0);
101097 }else{
101098 whereSplit(pWC, pExpr->pLeft, op);
101099 whereSplit(pWC, pExpr->pRight, op);
101104 ** Initialize an expression mask set (a WhereMaskSet object)
101106 #define initMaskSet(P) memset(P, 0, sizeof(*P))
101109 ** Return the bitmask for the given cursor number. Return 0 if
101110 ** iCursor is not in the set.
101112 static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
101113 int i;
101114 assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
101115 for(i=0; i<pMaskSet->n; i++){
101116 if( pMaskSet->ix[i]==iCursor ){
101117 return ((Bitmask)1)<<i;
101120 return 0;
101124 ** Create a new mask for cursor iCursor.
101126 ** There is one cursor per table in the FROM clause. The number of
101127 ** tables in the FROM clause is limited by a test early in the
101128 ** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
101129 ** array will never overflow.
101131 static void createMask(WhereMaskSet *pMaskSet, int iCursor){
101132 assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
101133 pMaskSet->ix[pMaskSet->n++] = iCursor;
101137 ** This routine walks (recursively) an expression tree and generates
101138 ** a bitmask indicating which tables are used in that expression
101139 ** tree.
101141 ** In order for this routine to work, the calling function must have
101142 ** previously invoked sqlite3ResolveExprNames() on the expression. See
101143 ** the header comment on that routine for additional information.
101144 ** The sqlite3ResolveExprNames() routines looks for column names and
101145 ** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
101146 ** the VDBE cursor number of the table. This routine just has to
101147 ** translate the cursor numbers into bitmask values and OR all
101148 ** the bitmasks together.
101150 static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
101151 static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
101152 static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
101153 Bitmask mask = 0;
101154 if( p==0 ) return 0;
101155 if( p->op==TK_COLUMN ){
101156 mask = getMask(pMaskSet, p->iTable);
101157 return mask;
101159 mask = exprTableUsage(pMaskSet, p->pRight);
101160 mask |= exprTableUsage(pMaskSet, p->pLeft);
101161 if( ExprHasProperty(p, EP_xIsSelect) ){
101162 mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
101163 }else{
101164 mask |= exprListTableUsage(pMaskSet, p->x.pList);
101166 return mask;
101168 static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
101169 int i;
101170 Bitmask mask = 0;
101171 if( pList ){
101172 for(i=0; i<pList->nExpr; i++){
101173 mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
101176 return mask;
101178 static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
101179 Bitmask mask = 0;
101180 while( pS ){
101181 SrcList *pSrc = pS->pSrc;
101182 mask |= exprListTableUsage(pMaskSet, pS->pEList);
101183 mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
101184 mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
101185 mask |= exprTableUsage(pMaskSet, pS->pWhere);
101186 mask |= exprTableUsage(pMaskSet, pS->pHaving);
101187 if( ALWAYS(pSrc!=0) ){
101188 int i;
101189 for(i=0; i<pSrc->nSrc; i++){
101190 mask |= exprSelectTableUsage(pMaskSet, pSrc->a[i].pSelect);
101191 mask |= exprTableUsage(pMaskSet, pSrc->a[i].pOn);
101194 pS = pS->pPrior;
101196 return mask;
101200 ** Return TRUE if the given operator is one of the operators that is
101201 ** allowed for an indexable WHERE clause term. The allowed operators are
101202 ** "=", "<", ">", "<=", ">=", and "IN".
101204 ** IMPLEMENTATION-OF: R-59926-26393 To be usable by an index a term must be
101205 ** of one of the following forms: column = expression column > expression
101206 ** column >= expression column < expression column <= expression
101207 ** expression = column expression > column expression >= column
101208 ** expression < column expression <= column column IN
101209 ** (expression-list) column IN (subquery) column IS NULL
101211 static int allowedOp(int op){
101212 assert( TK_GT>TK_EQ && TK_GT<TK_GE );
101213 assert( TK_LT>TK_EQ && TK_LT<TK_GE );
101214 assert( TK_LE>TK_EQ && TK_LE<TK_GE );
101215 assert( TK_GE==TK_EQ+4 );
101216 return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
101220 ** Swap two objects of type TYPE.
101222 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
101225 ** Commute a comparison operator. Expressions of the form "X op Y"
101226 ** are converted into "Y op X".
101228 ** If a collation sequence is associated with either the left or right
101229 ** side of the comparison, it remains associated with the same side after
101230 ** the commutation. So "Y collate NOCASE op X" becomes
101231 ** "X collate NOCASE op Y". This is because any collation sequence on
101232 ** the left hand side of a comparison overrides any collation sequence
101233 ** attached to the right. For the same reason the EP_ExpCollate flag
101234 ** is not commuted.
101236 static void exprCommute(Parse *pParse, Expr *pExpr){
101237 u16 expRight = (pExpr->pRight->flags & EP_ExpCollate);
101238 u16 expLeft = (pExpr->pLeft->flags & EP_ExpCollate);
101239 assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
101240 pExpr->pRight->pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
101241 pExpr->pLeft->pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
101242 SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
101243 pExpr->pRight->flags = (pExpr->pRight->flags & ~EP_ExpCollate) | expLeft;
101244 pExpr->pLeft->flags = (pExpr->pLeft->flags & ~EP_ExpCollate) | expRight;
101245 SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
101246 if( pExpr->op>=TK_GT ){
101247 assert( TK_LT==TK_GT+2 );
101248 assert( TK_GE==TK_LE+2 );
101249 assert( TK_GT>TK_EQ );
101250 assert( TK_GT<TK_LE );
101251 assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
101252 pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
101257 ** Translate from TK_xx operator to WO_xx bitmask.
101259 static u16 operatorMask(int op){
101260 u16 c;
101261 assert( allowedOp(op) );
101262 if( op==TK_IN ){
101263 c = WO_IN;
101264 }else if( op==TK_ISNULL ){
101265 c = WO_ISNULL;
101266 }else{
101267 assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
101268 c = (u16)(WO_EQ<<(op-TK_EQ));
101270 assert( op!=TK_ISNULL || c==WO_ISNULL );
101271 assert( op!=TK_IN || c==WO_IN );
101272 assert( op!=TK_EQ || c==WO_EQ );
101273 assert( op!=TK_LT || c==WO_LT );
101274 assert( op!=TK_LE || c==WO_LE );
101275 assert( op!=TK_GT || c==WO_GT );
101276 assert( op!=TK_GE || c==WO_GE );
101277 return c;
101281 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
101282 ** where X is a reference to the iColumn of table iCur and <op> is one of
101283 ** the WO_xx operator codes specified by the op parameter.
101284 ** Return a pointer to the term. Return 0 if not found.
101286 static WhereTerm *findTerm(
101287 WhereClause *pWC, /* The WHERE clause to be searched */
101288 int iCur, /* Cursor number of LHS */
101289 int iColumn, /* Column number of LHS */
101290 Bitmask notReady, /* RHS must not overlap with this mask */
101291 u32 op, /* Mask of WO_xx values describing operator */
101292 Index *pIdx /* Must be compatible with this index, if not NULL */
101294 WhereTerm *pTerm;
101295 int k;
101296 assert( iCur>=0 );
101297 op &= WO_ALL;
101298 for(; pWC; pWC=pWC->pOuter){
101299 for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
101300 if( pTerm->leftCursor==iCur
101301 && (pTerm->prereqRight & notReady)==0
101302 && pTerm->u.leftColumn==iColumn
101303 && (pTerm->eOperator & op)!=0
101305 if( pIdx && pTerm->eOperator!=WO_ISNULL ){
101306 Expr *pX = pTerm->pExpr;
101307 CollSeq *pColl;
101308 char idxaff;
101309 int j;
101310 Parse *pParse = pWC->pParse;
101312 idxaff = pIdx->pTable->aCol[iColumn].affinity;
101313 if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
101315 /* Figure out the collation sequence required from an index for
101316 ** it to be useful for optimising expression pX. Store this
101317 ** value in variable pColl.
101319 assert(pX->pLeft);
101320 pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
101321 assert(pColl || pParse->nErr);
101323 for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
101324 if( NEVER(j>=pIdx->nColumn) ) return 0;
101326 if( pColl && sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue;
101328 return pTerm;
101332 return 0;
101335 /* Forward reference */
101336 static void exprAnalyze(SrcList*, WhereClause*, int);
101339 ** Call exprAnalyze on all terms in a WHERE clause.
101343 static void exprAnalyzeAll(
101344 SrcList *pTabList, /* the FROM clause */
101345 WhereClause *pWC /* the WHERE clause to be analyzed */
101347 int i;
101348 for(i=pWC->nTerm-1; i>=0; i--){
101349 exprAnalyze(pTabList, pWC, i);
101353 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
101355 ** Check to see if the given expression is a LIKE or GLOB operator that
101356 ** can be optimized using inequality constraints. Return TRUE if it is
101357 ** so and false if not.
101359 ** In order for the operator to be optimizible, the RHS must be a string
101360 ** literal that does not begin with a wildcard.
101362 static int isLikeOrGlob(
101363 Parse *pParse, /* Parsing and code generating context */
101364 Expr *pExpr, /* Test this expression */
101365 Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
101366 int *pisComplete, /* True if the only wildcard is % in the last character */
101367 int *pnoCase /* True if uppercase is equivalent to lowercase */
101369 const char *z = 0; /* String on RHS of LIKE operator */
101370 Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
101371 ExprList *pList; /* List of operands to the LIKE operator */
101372 int c; /* One character in z[] */
101373 int cnt; /* Number of non-wildcard prefix characters */
101374 char wc[3]; /* Wildcard characters */
101375 sqlite3 *db = pParse->db; /* Database connection */
101376 sqlite3_value *pVal = 0;
101377 int op; /* Opcode of pRight */
101379 if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
101380 return 0;
101382 #ifdef SQLITE_EBCDIC
101383 if( *pnoCase ) return 0;
101384 #endif
101385 pList = pExpr->x.pList;
101386 pLeft = pList->a[1].pExpr;
101387 if( pLeft->op!=TK_COLUMN || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT ){
101388 /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
101389 ** be the name of an indexed column with TEXT affinity. */
101390 return 0;
101392 assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
101394 pRight = pList->a[0].pExpr;
101395 op = pRight->op;
101396 if( op==TK_REGISTER ){
101397 op = pRight->op2;
101399 if( op==TK_VARIABLE ){
101400 Vdbe *pReprepare = pParse->pReprepare;
101401 int iCol = pRight->iColumn;
101402 pVal = sqlite3VdbeGetValue(pReprepare, iCol, SQLITE_AFF_NONE);
101403 if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
101404 z = (char *)sqlite3_value_text(pVal);
101406 sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
101407 assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
101408 }else if( op==TK_STRING ){
101409 z = pRight->u.zToken;
101411 if( z ){
101412 cnt = 0;
101413 while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
101414 cnt++;
101416 if( cnt!=0 && 255!=(u8)z[cnt-1] ){
101417 Expr *pPrefix;
101418 *pisComplete = c==wc[0] && z[cnt+1]==0;
101419 pPrefix = sqlite3Expr(db, TK_STRING, z);
101420 if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
101421 *ppPrefix = pPrefix;
101422 if( op==TK_VARIABLE ){
101423 Vdbe *v = pParse->pVdbe;
101424 sqlite3VdbeSetVarmask(v, pRight->iColumn);
101425 if( *pisComplete && pRight->u.zToken[1] ){
101426 /* If the rhs of the LIKE expression is a variable, and the current
101427 ** value of the variable means there is no need to invoke the LIKE
101428 ** function, then no OP_Variable will be added to the program.
101429 ** This causes problems for the sqlite3_bind_parameter_name()
101430 ** API. To workaround them, add a dummy OP_Variable here.
101432 int r1 = sqlite3GetTempReg(pParse);
101433 sqlite3ExprCodeTarget(pParse, pRight, r1);
101434 sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
101435 sqlite3ReleaseTempReg(pParse, r1);
101438 }else{
101439 z = 0;
101443 sqlite3ValueFree(pVal);
101444 return (z!=0);
101446 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
101449 #ifndef SQLITE_OMIT_VIRTUALTABLE
101451 ** Check to see if the given expression is of the form
101453 ** column MATCH expr
101455 ** If it is then return TRUE. If not, return FALSE.
101457 static int isMatchOfColumn(
101458 Expr *pExpr /* Test this expression */
101460 ExprList *pList;
101462 if( pExpr->op!=TK_FUNCTION ){
101463 return 0;
101465 if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
101466 return 0;
101468 pList = pExpr->x.pList;
101469 if( pList->nExpr!=2 ){
101470 return 0;
101472 if( pList->a[1].pExpr->op != TK_COLUMN ){
101473 return 0;
101475 return 1;
101477 #endif /* SQLITE_OMIT_VIRTUALTABLE */
101480 ** If the pBase expression originated in the ON or USING clause of
101481 ** a join, then transfer the appropriate markings over to derived.
101483 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
101484 pDerived->flags |= pBase->flags & EP_FromJoin;
101485 pDerived->iRightJoinTable = pBase->iRightJoinTable;
101488 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
101490 ** Analyze a term that consists of two or more OR-connected
101491 ** subterms. So in:
101493 ** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
101494 ** ^^^^^^^^^^^^^^^^^^^^
101496 ** This routine analyzes terms such as the middle term in the above example.
101497 ** A WhereOrTerm object is computed and attached to the term under
101498 ** analysis, regardless of the outcome of the analysis. Hence:
101500 ** WhereTerm.wtFlags |= TERM_ORINFO
101501 ** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
101503 ** The term being analyzed must have two or more of OR-connected subterms.
101504 ** A single subterm might be a set of AND-connected sub-subterms.
101505 ** Examples of terms under analysis:
101507 ** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
101508 ** (B) x=expr1 OR expr2=x OR x=expr3
101509 ** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
101510 ** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
101511 ** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
101513 ** CASE 1:
101515 ** If all subterms are of the form T.C=expr for some single column of C
101516 ** a single table T (as shown in example B above) then create a new virtual
101517 ** term that is an equivalent IN expression. In other words, if the term
101518 ** being analyzed is:
101520 ** x = expr1 OR expr2 = x OR x = expr3
101522 ** then create a new virtual term like this:
101524 ** x IN (expr1,expr2,expr3)
101526 ** CASE 2:
101528 ** If all subterms are indexable by a single table T, then set
101530 ** WhereTerm.eOperator = WO_OR
101531 ** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
101533 ** A subterm is "indexable" if it is of the form
101534 ** "T.C <op> <expr>" where C is any column of table T and
101535 ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
101536 ** A subterm is also indexable if it is an AND of two or more
101537 ** subsubterms at least one of which is indexable. Indexable AND
101538 ** subterms have their eOperator set to WO_AND and they have
101539 ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
101541 ** From another point of view, "indexable" means that the subterm could
101542 ** potentially be used with an index if an appropriate index exists.
101543 ** This analysis does not consider whether or not the index exists; that
101544 ** is something the bestIndex() routine will determine. This analysis
101545 ** only looks at whether subterms appropriate for indexing exist.
101547 ** All examples A through E above all satisfy case 2. But if a term
101548 ** also statisfies case 1 (such as B) we know that the optimizer will
101549 ** always prefer case 1, so in that case we pretend that case 2 is not
101550 ** satisfied.
101552 ** It might be the case that multiple tables are indexable. For example,
101553 ** (E) above is indexable on tables P, Q, and R.
101555 ** Terms that satisfy case 2 are candidates for lookup by using
101556 ** separate indices to find rowids for each subterm and composing
101557 ** the union of all rowids using a RowSet object. This is similar
101558 ** to "bitmap indices" in other database engines.
101560 ** OTHERWISE:
101562 ** If neither case 1 nor case 2 apply, then leave the eOperator set to
101563 ** zero. This term is not useful for search.
101565 static void exprAnalyzeOrTerm(
101566 SrcList *pSrc, /* the FROM clause */
101567 WhereClause *pWC, /* the complete WHERE clause */
101568 int idxTerm /* Index of the OR-term to be analyzed */
101570 Parse *pParse = pWC->pParse; /* Parser context */
101571 sqlite3 *db = pParse->db; /* Database connection */
101572 WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
101573 Expr *pExpr = pTerm->pExpr; /* The expression of the term */
101574 WhereMaskSet *pMaskSet = pWC->pMaskSet; /* Table use masks */
101575 int i; /* Loop counters */
101576 WhereClause *pOrWc; /* Breakup of pTerm into subterms */
101577 WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
101578 WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
101579 Bitmask chngToIN; /* Tables that might satisfy case 1 */
101580 Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
101583 ** Break the OR clause into its separate subterms. The subterms are
101584 ** stored in a WhereClause structure containing within the WhereOrInfo
101585 ** object that is attached to the original OR clause term.
101587 assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
101588 assert( pExpr->op==TK_OR );
101589 pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
101590 if( pOrInfo==0 ) return;
101591 pTerm->wtFlags |= TERM_ORINFO;
101592 pOrWc = &pOrInfo->wc;
101593 whereClauseInit(pOrWc, pWC->pParse, pMaskSet, pWC->wctrlFlags);
101594 whereSplit(pOrWc, pExpr, TK_OR);
101595 exprAnalyzeAll(pSrc, pOrWc);
101596 if( db->mallocFailed ) return;
101597 assert( pOrWc->nTerm>=2 );
101600 ** Compute the set of tables that might satisfy cases 1 or 2.
101602 indexable = ~(Bitmask)0;
101603 chngToIN = ~(pWC->vmask);
101604 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
101605 if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
101606 WhereAndInfo *pAndInfo;
101607 assert( pOrTerm->eOperator==0 );
101608 assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
101609 chngToIN = 0;
101610 pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
101611 if( pAndInfo ){
101612 WhereClause *pAndWC;
101613 WhereTerm *pAndTerm;
101614 int j;
101615 Bitmask b = 0;
101616 pOrTerm->u.pAndInfo = pAndInfo;
101617 pOrTerm->wtFlags |= TERM_ANDINFO;
101618 pOrTerm->eOperator = WO_AND;
101619 pAndWC = &pAndInfo->wc;
101620 whereClauseInit(pAndWC, pWC->pParse, pMaskSet, pWC->wctrlFlags);
101621 whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
101622 exprAnalyzeAll(pSrc, pAndWC);
101623 pAndWC->pOuter = pWC;
101624 testcase( db->mallocFailed );
101625 if( !db->mallocFailed ){
101626 for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
101627 assert( pAndTerm->pExpr );
101628 if( allowedOp(pAndTerm->pExpr->op) ){
101629 b |= getMask(pMaskSet, pAndTerm->leftCursor);
101633 indexable &= b;
101635 }else if( pOrTerm->wtFlags & TERM_COPIED ){
101636 /* Skip this term for now. We revisit it when we process the
101637 ** corresponding TERM_VIRTUAL term */
101638 }else{
101639 Bitmask b;
101640 b = getMask(pMaskSet, pOrTerm->leftCursor);
101641 if( pOrTerm->wtFlags & TERM_VIRTUAL ){
101642 WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
101643 b |= getMask(pMaskSet, pOther->leftCursor);
101645 indexable &= b;
101646 if( pOrTerm->eOperator!=WO_EQ ){
101647 chngToIN = 0;
101648 }else{
101649 chngToIN &= b;
101655 ** Record the set of tables that satisfy case 2. The set might be
101656 ** empty.
101658 pOrInfo->indexable = indexable;
101659 pTerm->eOperator = indexable==0 ? 0 : WO_OR;
101662 ** chngToIN holds a set of tables that *might* satisfy case 1. But
101663 ** we have to do some additional checking to see if case 1 really
101664 ** is satisfied.
101666 ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
101667 ** that there is no possibility of transforming the OR clause into an
101668 ** IN operator because one or more terms in the OR clause contain
101669 ** something other than == on a column in the single table. The 1-bit
101670 ** case means that every term of the OR clause is of the form
101671 ** "table.column=expr" for some single table. The one bit that is set
101672 ** will correspond to the common table. We still need to check to make
101673 ** sure the same column is used on all terms. The 2-bit case is when
101674 ** the all terms are of the form "table1.column=table2.column". It
101675 ** might be possible to form an IN operator with either table1.column
101676 ** or table2.column as the LHS if either is common to every term of
101677 ** the OR clause.
101679 ** Note that terms of the form "table.column1=table.column2" (the
101680 ** same table on both sizes of the ==) cannot be optimized.
101682 if( chngToIN ){
101683 int okToChngToIN = 0; /* True if the conversion to IN is valid */
101684 int iColumn = -1; /* Column index on lhs of IN operator */
101685 int iCursor = -1; /* Table cursor common to all terms */
101686 int j = 0; /* Loop counter */
101688 /* Search for a table and column that appears on one side or the
101689 ** other of the == operator in every subterm. That table and column
101690 ** will be recorded in iCursor and iColumn. There might not be any
101691 ** such table and column. Set okToChngToIN if an appropriate table
101692 ** and column is found but leave okToChngToIN false if not found.
101694 for(j=0; j<2 && !okToChngToIN; j++){
101695 pOrTerm = pOrWc->a;
101696 for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
101697 assert( pOrTerm->eOperator==WO_EQ );
101698 pOrTerm->wtFlags &= ~TERM_OR_OK;
101699 if( pOrTerm->leftCursor==iCursor ){
101700 /* This is the 2-bit case and we are on the second iteration and
101701 ** current term is from the first iteration. So skip this term. */
101702 assert( j==1 );
101703 continue;
101705 if( (chngToIN & getMask(pMaskSet, pOrTerm->leftCursor))==0 ){
101706 /* This term must be of the form t1.a==t2.b where t2 is in the
101707 ** chngToIN set but t1 is not. This term will be either preceeded
101708 ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
101709 ** and use its inversion. */
101710 testcase( pOrTerm->wtFlags & TERM_COPIED );
101711 testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
101712 assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
101713 continue;
101715 iColumn = pOrTerm->u.leftColumn;
101716 iCursor = pOrTerm->leftCursor;
101717 break;
101719 if( i<0 ){
101720 /* No candidate table+column was found. This can only occur
101721 ** on the second iteration */
101722 assert( j==1 );
101723 assert( (chngToIN&(chngToIN-1))==0 );
101724 assert( chngToIN==getMask(pMaskSet, iCursor) );
101725 break;
101727 testcase( j==1 );
101729 /* We have found a candidate table and column. Check to see if that
101730 ** table and column is common to every term in the OR clause */
101731 okToChngToIN = 1;
101732 for(; i>=0 && okToChngToIN; i--, pOrTerm++){
101733 assert( pOrTerm->eOperator==WO_EQ );
101734 if( pOrTerm->leftCursor!=iCursor ){
101735 pOrTerm->wtFlags &= ~TERM_OR_OK;
101736 }else if( pOrTerm->u.leftColumn!=iColumn ){
101737 okToChngToIN = 0;
101738 }else{
101739 int affLeft, affRight;
101740 /* If the right-hand side is also a column, then the affinities
101741 ** of both right and left sides must be such that no type
101742 ** conversions are required on the right. (Ticket #2249)
101744 affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
101745 affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
101746 if( affRight!=0 && affRight!=affLeft ){
101747 okToChngToIN = 0;
101748 }else{
101749 pOrTerm->wtFlags |= TERM_OR_OK;
101755 /* At this point, okToChngToIN is true if original pTerm satisfies
101756 ** case 1. In that case, construct a new virtual term that is
101757 ** pTerm converted into an IN operator.
101759 ** EV: R-00211-15100
101761 if( okToChngToIN ){
101762 Expr *pDup; /* A transient duplicate expression */
101763 ExprList *pList = 0; /* The RHS of the IN operator */
101764 Expr *pLeft = 0; /* The LHS of the IN operator */
101765 Expr *pNew; /* The complete IN operator */
101767 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
101768 if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
101769 assert( pOrTerm->eOperator==WO_EQ );
101770 assert( pOrTerm->leftCursor==iCursor );
101771 assert( pOrTerm->u.leftColumn==iColumn );
101772 pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
101773 pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup);
101774 pLeft = pOrTerm->pExpr->pLeft;
101776 assert( pLeft!=0 );
101777 pDup = sqlite3ExprDup(db, pLeft, 0);
101778 pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
101779 if( pNew ){
101780 int idxNew;
101781 transferJoinMarkings(pNew, pExpr);
101782 assert( !ExprHasProperty(pNew, EP_xIsSelect) );
101783 pNew->x.pList = pList;
101784 idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
101785 testcase( idxNew==0 );
101786 exprAnalyze(pSrc, pWC, idxNew);
101787 pTerm = &pWC->a[idxTerm];
101788 pWC->a[idxNew].iParent = idxTerm;
101789 pTerm->nChild = 1;
101790 }else{
101791 sqlite3ExprListDelete(db, pList);
101793 pTerm->eOperator = WO_NOOP; /* case 1 trumps case 2 */
101797 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
101801 ** The input to this routine is an WhereTerm structure with only the
101802 ** "pExpr" field filled in. The job of this routine is to analyze the
101803 ** subexpression and populate all the other fields of the WhereTerm
101804 ** structure.
101806 ** If the expression is of the form "<expr> <op> X" it gets commuted
101807 ** to the standard form of "X <op> <expr>".
101809 ** If the expression is of the form "X <op> Y" where both X and Y are
101810 ** columns, then the original expression is unchanged and a new virtual
101811 ** term of the form "Y <op> X" is added to the WHERE clause and
101812 ** analyzed separately. The original term is marked with TERM_COPIED
101813 ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
101814 ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
101815 ** is a commuted copy of a prior term.) The original term has nChild=1
101816 ** and the copy has idxParent set to the index of the original term.
101818 static void exprAnalyze(
101819 SrcList *pSrc, /* the FROM clause */
101820 WhereClause *pWC, /* the WHERE clause */
101821 int idxTerm /* Index of the term to be analyzed */
101823 WhereTerm *pTerm; /* The term to be analyzed */
101824 WhereMaskSet *pMaskSet; /* Set of table index masks */
101825 Expr *pExpr; /* The expression to be analyzed */
101826 Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
101827 Bitmask prereqAll; /* Prerequesites of pExpr */
101828 Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
101829 Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
101830 int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
101831 int noCase = 0; /* LIKE/GLOB distinguishes case */
101832 int op; /* Top-level operator. pExpr->op */
101833 Parse *pParse = pWC->pParse; /* Parsing context */
101834 sqlite3 *db = pParse->db; /* Database connection */
101836 if( db->mallocFailed ){
101837 return;
101839 pTerm = &pWC->a[idxTerm];
101840 pMaskSet = pWC->pMaskSet;
101841 pExpr = pTerm->pExpr;
101842 prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
101843 op = pExpr->op;
101844 if( op==TK_IN ){
101845 assert( pExpr->pRight==0 );
101846 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
101847 pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
101848 }else{
101849 pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
101851 }else if( op==TK_ISNULL ){
101852 pTerm->prereqRight = 0;
101853 }else{
101854 pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
101856 prereqAll = exprTableUsage(pMaskSet, pExpr);
101857 if( ExprHasProperty(pExpr, EP_FromJoin) ){
101858 Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
101859 prereqAll |= x;
101860 extraRight = x-1; /* ON clause terms may not be used with an index
101861 ** on left table of a LEFT JOIN. Ticket #3015 */
101863 pTerm->prereqAll = prereqAll;
101864 pTerm->leftCursor = -1;
101865 pTerm->iParent = -1;
101866 pTerm->eOperator = 0;
101867 if( allowedOp(op) && (pTerm->prereqRight & prereqLeft)==0 ){
101868 Expr *pLeft = pExpr->pLeft;
101869 Expr *pRight = pExpr->pRight;
101870 if( pLeft->op==TK_COLUMN ){
101871 pTerm->leftCursor = pLeft->iTable;
101872 pTerm->u.leftColumn = pLeft->iColumn;
101873 pTerm->eOperator = operatorMask(op);
101875 if( pRight && pRight->op==TK_COLUMN ){
101876 WhereTerm *pNew;
101877 Expr *pDup;
101878 if( pTerm->leftCursor>=0 ){
101879 int idxNew;
101880 pDup = sqlite3ExprDup(db, pExpr, 0);
101881 if( db->mallocFailed ){
101882 sqlite3ExprDelete(db, pDup);
101883 return;
101885 idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
101886 if( idxNew==0 ) return;
101887 pNew = &pWC->a[idxNew];
101888 pNew->iParent = idxTerm;
101889 pTerm = &pWC->a[idxTerm];
101890 pTerm->nChild = 1;
101891 pTerm->wtFlags |= TERM_COPIED;
101892 }else{
101893 pDup = pExpr;
101894 pNew = pTerm;
101896 exprCommute(pParse, pDup);
101897 pLeft = pDup->pLeft;
101898 pNew->leftCursor = pLeft->iTable;
101899 pNew->u.leftColumn = pLeft->iColumn;
101900 testcase( (prereqLeft | extraRight) != prereqLeft );
101901 pNew->prereqRight = prereqLeft | extraRight;
101902 pNew->prereqAll = prereqAll;
101903 pNew->eOperator = operatorMask(pDup->op);
101907 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
101908 /* If a term is the BETWEEN operator, create two new virtual terms
101909 ** that define the range that the BETWEEN implements. For example:
101911 ** a BETWEEN b AND c
101913 ** is converted into:
101915 ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
101917 ** The two new terms are added onto the end of the WhereClause object.
101918 ** The new terms are "dynamic" and are children of the original BETWEEN
101919 ** term. That means that if the BETWEEN term is coded, the children are
101920 ** skipped. Or, if the children are satisfied by an index, the original
101921 ** BETWEEN term is skipped.
101923 else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
101924 ExprList *pList = pExpr->x.pList;
101925 int i;
101926 static const u8 ops[] = {TK_GE, TK_LE};
101927 assert( pList!=0 );
101928 assert( pList->nExpr==2 );
101929 for(i=0; i<2; i++){
101930 Expr *pNewExpr;
101931 int idxNew;
101932 pNewExpr = sqlite3PExpr(pParse, ops[i],
101933 sqlite3ExprDup(db, pExpr->pLeft, 0),
101934 sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
101935 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
101936 testcase( idxNew==0 );
101937 exprAnalyze(pSrc, pWC, idxNew);
101938 pTerm = &pWC->a[idxTerm];
101939 pWC->a[idxNew].iParent = idxTerm;
101941 pTerm->nChild = 2;
101943 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
101945 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
101946 /* Analyze a term that is composed of two or more subterms connected by
101947 ** an OR operator.
101949 else if( pExpr->op==TK_OR ){
101950 assert( pWC->op==TK_AND );
101951 exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
101952 pTerm = &pWC->a[idxTerm];
101954 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
101956 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
101957 /* Add constraints to reduce the search space on a LIKE or GLOB
101958 ** operator.
101960 ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
101962 ** x>='abc' AND x<'abd' AND x LIKE 'abc%'
101964 ** The last character of the prefix "abc" is incremented to form the
101965 ** termination condition "abd".
101967 if( pWC->op==TK_AND
101968 && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
101970 Expr *pLeft; /* LHS of LIKE/GLOB operator */
101971 Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
101972 Expr *pNewExpr1;
101973 Expr *pNewExpr2;
101974 int idxNew1;
101975 int idxNew2;
101976 CollSeq *pColl; /* Collating sequence to use */
101978 pLeft = pExpr->x.pList->a[1].pExpr;
101979 pStr2 = sqlite3ExprDup(db, pStr1, 0);
101980 if( !db->mallocFailed ){
101981 u8 c, *pC; /* Last character before the first wildcard */
101982 pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
101983 c = *pC;
101984 if( noCase ){
101985 /* The point is to increment the last character before the first
101986 ** wildcard. But if we increment '@', that will push it into the
101987 ** alphabetic range where case conversions will mess up the
101988 ** inequality. To avoid this, make sure to also run the full
101989 ** LIKE on all candidate expressions by clearing the isComplete flag
101991 if( c=='A'-1 ) isComplete = 0; /* EV: R-64339-08207 */
101994 c = sqlite3UpperToLower[c];
101996 *pC = c + 1;
101998 pColl = sqlite3FindCollSeq(db, SQLITE_UTF8, noCase ? "NOCASE" : "BINARY",0);
101999 pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
102000 sqlite3ExprSetColl(sqlite3ExprDup(db,pLeft,0), pColl),
102001 pStr1, 0);
102002 idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
102003 testcase( idxNew1==0 );
102004 exprAnalyze(pSrc, pWC, idxNew1);
102005 pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
102006 sqlite3ExprSetColl(sqlite3ExprDup(db,pLeft,0), pColl),
102007 pStr2, 0);
102008 idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
102009 testcase( idxNew2==0 );
102010 exprAnalyze(pSrc, pWC, idxNew2);
102011 pTerm = &pWC->a[idxTerm];
102012 if( isComplete ){
102013 pWC->a[idxNew1].iParent = idxTerm;
102014 pWC->a[idxNew2].iParent = idxTerm;
102015 pTerm->nChild = 2;
102018 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
102020 #ifndef SQLITE_OMIT_VIRTUALTABLE
102021 /* Add a WO_MATCH auxiliary term to the constraint set if the
102022 ** current expression is of the form: column MATCH expr.
102023 ** This information is used by the xBestIndex methods of
102024 ** virtual tables. The native query optimizer does not attempt
102025 ** to do anything with MATCH functions.
102027 if( isMatchOfColumn(pExpr) ){
102028 int idxNew;
102029 Expr *pRight, *pLeft;
102030 WhereTerm *pNewTerm;
102031 Bitmask prereqColumn, prereqExpr;
102033 pRight = pExpr->x.pList->a[0].pExpr;
102034 pLeft = pExpr->x.pList->a[1].pExpr;
102035 prereqExpr = exprTableUsage(pMaskSet, pRight);
102036 prereqColumn = exprTableUsage(pMaskSet, pLeft);
102037 if( (prereqExpr & prereqColumn)==0 ){
102038 Expr *pNewExpr;
102039 pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
102040 0, sqlite3ExprDup(db, pRight, 0), 0);
102041 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
102042 testcase( idxNew==0 );
102043 pNewTerm = &pWC->a[idxNew];
102044 pNewTerm->prereqRight = prereqExpr;
102045 pNewTerm->leftCursor = pLeft->iTable;
102046 pNewTerm->u.leftColumn = pLeft->iColumn;
102047 pNewTerm->eOperator = WO_MATCH;
102048 pNewTerm->iParent = idxTerm;
102049 pTerm = &pWC->a[idxTerm];
102050 pTerm->nChild = 1;
102051 pTerm->wtFlags |= TERM_COPIED;
102052 pNewTerm->prereqAll = pTerm->prereqAll;
102055 #endif /* SQLITE_OMIT_VIRTUALTABLE */
102057 #ifdef SQLITE_ENABLE_STAT3
102058 /* When sqlite_stat3 histogram data is available an operator of the
102059 ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
102060 ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
102061 ** virtual term of that form.
102063 ** Note that the virtual term must be tagged with TERM_VNULL. This
102064 ** TERM_VNULL tag will suppress the not-null check at the beginning
102065 ** of the loop. Without the TERM_VNULL flag, the not-null check at
102066 ** the start of the loop will prevent any results from being returned.
102068 if( pExpr->op==TK_NOTNULL
102069 && pExpr->pLeft->op==TK_COLUMN
102070 && pExpr->pLeft->iColumn>=0
102072 Expr *pNewExpr;
102073 Expr *pLeft = pExpr->pLeft;
102074 int idxNew;
102075 WhereTerm *pNewTerm;
102077 pNewExpr = sqlite3PExpr(pParse, TK_GT,
102078 sqlite3ExprDup(db, pLeft, 0),
102079 sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
102081 idxNew = whereClauseInsert(pWC, pNewExpr,
102082 TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
102083 if( idxNew ){
102084 pNewTerm = &pWC->a[idxNew];
102085 pNewTerm->prereqRight = 0;
102086 pNewTerm->leftCursor = pLeft->iTable;
102087 pNewTerm->u.leftColumn = pLeft->iColumn;
102088 pNewTerm->eOperator = WO_GT;
102089 pNewTerm->iParent = idxTerm;
102090 pTerm = &pWC->a[idxTerm];
102091 pTerm->nChild = 1;
102092 pTerm->wtFlags |= TERM_COPIED;
102093 pNewTerm->prereqAll = pTerm->prereqAll;
102096 #endif /* SQLITE_ENABLE_STAT */
102098 /* Prevent ON clause terms of a LEFT JOIN from being used to drive
102099 ** an index for tables to the left of the join.
102101 pTerm->prereqRight |= extraRight;
102105 ** Return TRUE if any of the expressions in pList->a[iFirst...] contain
102106 ** a reference to any table other than the iBase table.
102108 static int referencesOtherTables(
102109 ExprList *pList, /* Search expressions in ths list */
102110 WhereMaskSet *pMaskSet, /* Mapping from tables to bitmaps */
102111 int iFirst, /* Be searching with the iFirst-th expression */
102112 int iBase /* Ignore references to this table */
102114 Bitmask allowed = ~getMask(pMaskSet, iBase);
102115 while( iFirst<pList->nExpr ){
102116 if( (exprTableUsage(pMaskSet, pList->a[iFirst++].pExpr)&allowed)!=0 ){
102117 return 1;
102120 return 0;
102124 ** This function searches the expression list passed as the second argument
102125 ** for an expression of type TK_COLUMN that refers to the same column and
102126 ** uses the same collation sequence as the iCol'th column of index pIdx.
102127 ** Argument iBase is the cursor number used for the table that pIdx refers
102128 ** to.
102130 ** If such an expression is found, its index in pList->a[] is returned. If
102131 ** no expression is found, -1 is returned.
102133 static int findIndexCol(
102134 Parse *pParse, /* Parse context */
102135 ExprList *pList, /* Expression list to search */
102136 int iBase, /* Cursor for table associated with pIdx */
102137 Index *pIdx, /* Index to match column of */
102138 int iCol /* Column of index to match */
102140 int i;
102141 const char *zColl = pIdx->azColl[iCol];
102143 for(i=0; i<pList->nExpr; i++){
102144 Expr *p = pList->a[i].pExpr;
102145 if( p->op==TK_COLUMN
102146 && p->iColumn==pIdx->aiColumn[iCol]
102147 && p->iTable==iBase
102149 CollSeq *pColl = sqlite3ExprCollSeq(pParse, p);
102150 if( ALWAYS(pColl) && 0==sqlite3StrICmp(pColl->zName, zColl) ){
102151 return i;
102156 return -1;
102160 ** This routine determines if pIdx can be used to assist in processing a
102161 ** DISTINCT qualifier. In other words, it tests whether or not using this
102162 ** index for the outer loop guarantees that rows with equal values for
102163 ** all expressions in the pDistinct list are delivered grouped together.
102165 ** For example, the query
102167 ** SELECT DISTINCT a, b, c FROM tbl WHERE a = ?
102169 ** can benefit from any index on columns "b" and "c".
102171 static int isDistinctIndex(
102172 Parse *pParse, /* Parsing context */
102173 WhereClause *pWC, /* The WHERE clause */
102174 Index *pIdx, /* The index being considered */
102175 int base, /* Cursor number for the table pIdx is on */
102176 ExprList *pDistinct, /* The DISTINCT expressions */
102177 int nEqCol /* Number of index columns with == */
102179 Bitmask mask = 0; /* Mask of unaccounted for pDistinct exprs */
102180 int i; /* Iterator variable */
102182 if( pIdx->zName==0 || pDistinct==0 || pDistinct->nExpr>=BMS ) return 0;
102183 testcase( pDistinct->nExpr==BMS-1 );
102185 /* Loop through all the expressions in the distinct list. If any of them
102186 ** are not simple column references, return early. Otherwise, test if the
102187 ** WHERE clause contains a "col=X" clause. If it does, the expression
102188 ** can be ignored. If it does not, and the column does not belong to the
102189 ** same table as index pIdx, return early. Finally, if there is no
102190 ** matching "col=X" expression and the column is on the same table as pIdx,
102191 ** set the corresponding bit in variable mask.
102193 for(i=0; i<pDistinct->nExpr; i++){
102194 WhereTerm *pTerm;
102195 Expr *p = pDistinct->a[i].pExpr;
102196 if( p->op!=TK_COLUMN ) return 0;
102197 pTerm = findTerm(pWC, p->iTable, p->iColumn, ~(Bitmask)0, WO_EQ, 0);
102198 if( pTerm ){
102199 Expr *pX = pTerm->pExpr;
102200 CollSeq *p1 = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
102201 CollSeq *p2 = sqlite3ExprCollSeq(pParse, p);
102202 if( p1==p2 ) continue;
102204 if( p->iTable!=base ) return 0;
102205 mask |= (((Bitmask)1) << i);
102208 for(i=nEqCol; mask && i<pIdx->nColumn; i++){
102209 int iExpr = findIndexCol(pParse, pDistinct, base, pIdx, i);
102210 if( iExpr<0 ) break;
102211 mask &= ~(((Bitmask)1) << iExpr);
102214 return (mask==0);
102219 ** Return true if the DISTINCT expression-list passed as the third argument
102220 ** is redundant. A DISTINCT list is redundant if the database contains a
102221 ** UNIQUE index that guarantees that the result of the query will be distinct
102222 ** anyway.
102224 static int isDistinctRedundant(
102225 Parse *pParse,
102226 SrcList *pTabList,
102227 WhereClause *pWC,
102228 ExprList *pDistinct
102230 Table *pTab;
102231 Index *pIdx;
102232 int i;
102233 int iBase;
102235 /* If there is more than one table or sub-select in the FROM clause of
102236 ** this query, then it will not be possible to show that the DISTINCT
102237 ** clause is redundant. */
102238 if( pTabList->nSrc!=1 ) return 0;
102239 iBase = pTabList->a[0].iCursor;
102240 pTab = pTabList->a[0].pTab;
102242 /* If any of the expressions is an IPK column on table iBase, then return
102243 ** true. Note: The (p->iTable==iBase) part of this test may be false if the
102244 ** current SELECT is a correlated sub-query.
102246 for(i=0; i<pDistinct->nExpr; i++){
102247 Expr *p = pDistinct->a[i].pExpr;
102248 if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
102251 /* Loop through all indices on the table, checking each to see if it makes
102252 ** the DISTINCT qualifier redundant. It does so if:
102254 ** 1. The index is itself UNIQUE, and
102256 ** 2. All of the columns in the index are either part of the pDistinct
102257 ** list, or else the WHERE clause contains a term of the form "col=X",
102258 ** where X is a constant value. The collation sequences of the
102259 ** comparison and select-list expressions must match those of the index.
102261 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
102262 if( pIdx->onError==OE_None ) continue;
102263 for(i=0; i<pIdx->nColumn; i++){
102264 int iCol = pIdx->aiColumn[i];
102265 if( 0==findTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx)
102266 && 0>findIndexCol(pParse, pDistinct, iBase, pIdx, i)
102268 break;
102271 if( i==pIdx->nColumn ){
102272 /* This index implies that the DISTINCT qualifier is redundant. */
102273 return 1;
102277 return 0;
102281 ** This routine decides if pIdx can be used to satisfy the ORDER BY
102282 ** clause. If it can, it returns 1. If pIdx cannot satisfy the
102283 ** ORDER BY clause, this routine returns 0.
102285 ** pOrderBy is an ORDER BY clause from a SELECT statement. pTab is the
102286 ** left-most table in the FROM clause of that same SELECT statement and
102287 ** the table has a cursor number of "base". pIdx is an index on pTab.
102289 ** nEqCol is the number of columns of pIdx that are used as equality
102290 ** constraints. Any of these columns may be missing from the ORDER BY
102291 ** clause and the match can still be a success.
102293 ** All terms of the ORDER BY that match against the index must be either
102294 ** ASC or DESC. (Terms of the ORDER BY clause past the end of a UNIQUE
102295 ** index do not need to satisfy this constraint.) The *pbRev value is
102296 ** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
102297 ** the ORDER BY clause is all ASC.
102299 static int isSortingIndex(
102300 Parse *pParse, /* Parsing context */
102301 WhereMaskSet *pMaskSet, /* Mapping from table cursor numbers to bitmaps */
102302 Index *pIdx, /* The index we are testing */
102303 int base, /* Cursor number for the table to be sorted */
102304 ExprList *pOrderBy, /* The ORDER BY clause */
102305 int nEqCol, /* Number of index columns with == constraints */
102306 int wsFlags, /* Index usages flags */
102307 int *pbRev /* Set to 1 if ORDER BY is DESC */
102309 int i, j; /* Loop counters */
102310 int sortOrder = 0; /* XOR of index and ORDER BY sort direction */
102311 int nTerm; /* Number of ORDER BY terms */
102312 struct ExprList_item *pTerm; /* A term of the ORDER BY clause */
102313 sqlite3 *db = pParse->db;
102315 if( !pOrderBy ) return 0;
102316 if( wsFlags & WHERE_COLUMN_IN ) return 0;
102317 if( pIdx->bUnordered ) return 0;
102319 nTerm = pOrderBy->nExpr;
102320 assert( nTerm>0 );
102322 /* Argument pIdx must either point to a 'real' named index structure,
102323 ** or an index structure allocated on the stack by bestBtreeIndex() to
102324 ** represent the rowid index that is part of every table. */
102325 assert( pIdx->zName || (pIdx->nColumn==1 && pIdx->aiColumn[0]==-1) );
102327 /* Match terms of the ORDER BY clause against columns of
102328 ** the index.
102330 ** Note that indices have pIdx->nColumn regular columns plus
102331 ** one additional column containing the rowid. The rowid column
102332 ** of the index is also allowed to match against the ORDER BY
102333 ** clause.
102335 for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<=pIdx->nColumn; i++){
102336 Expr *pExpr; /* The expression of the ORDER BY pTerm */
102337 CollSeq *pColl; /* The collating sequence of pExpr */
102338 int termSortOrder; /* Sort order for this term */
102339 int iColumn; /* The i-th column of the index. -1 for rowid */
102340 int iSortOrder; /* 1 for DESC, 0 for ASC on the i-th index term */
102341 const char *zColl; /* Name of the collating sequence for i-th index term */
102343 pExpr = pTerm->pExpr;
102344 if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
102345 /* Can not use an index sort on anything that is not a column in the
102346 ** left-most table of the FROM clause */
102347 break;
102349 pColl = sqlite3ExprCollSeq(pParse, pExpr);
102350 if( !pColl ){
102351 pColl = db->pDfltColl;
102353 if( pIdx->zName && i<pIdx->nColumn ){
102354 iColumn = pIdx->aiColumn[i];
102355 if( iColumn==pIdx->pTable->iPKey ){
102356 iColumn = -1;
102358 iSortOrder = pIdx->aSortOrder[i];
102359 zColl = pIdx->azColl[i];
102360 }else{
102361 iColumn = -1;
102362 iSortOrder = 0;
102363 zColl = pColl->zName;
102365 if( pExpr->iColumn!=iColumn || sqlite3StrICmp(pColl->zName, zColl) ){
102366 /* Term j of the ORDER BY clause does not match column i of the index */
102367 if( i<nEqCol ){
102368 /* If an index column that is constrained by == fails to match an
102369 ** ORDER BY term, that is OK. Just ignore that column of the index
102371 continue;
102372 }else if( i==pIdx->nColumn ){
102373 /* Index column i is the rowid. All other terms match. */
102374 break;
102375 }else{
102376 /* If an index column fails to match and is not constrained by ==
102377 ** then the index cannot satisfy the ORDER BY constraint.
102379 return 0;
102382 assert( pIdx->aSortOrder!=0 || iColumn==-1 );
102383 assert( pTerm->sortOrder==0 || pTerm->sortOrder==1 );
102384 assert( iSortOrder==0 || iSortOrder==1 );
102385 termSortOrder = iSortOrder ^ pTerm->sortOrder;
102386 if( i>nEqCol ){
102387 if( termSortOrder!=sortOrder ){
102388 /* Indices can only be used if all ORDER BY terms past the
102389 ** equality constraints are all either DESC or ASC. */
102390 return 0;
102392 }else{
102393 sortOrder = termSortOrder;
102396 pTerm++;
102397 if( iColumn<0 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
102398 /* If the indexed column is the primary key and everything matches
102399 ** so far and none of the ORDER BY terms to the right reference other
102400 ** tables in the join, then we are assured that the index can be used
102401 ** to sort because the primary key is unique and so none of the other
102402 ** columns will make any difference
102404 j = nTerm;
102408 *pbRev = sortOrder!=0;
102409 if( j>=nTerm ){
102410 /* All terms of the ORDER BY clause are covered by this index so
102411 ** this index can be used for sorting. */
102412 return 1;
102414 if( pIdx->onError!=OE_None && i==pIdx->nColumn
102415 && (wsFlags & WHERE_COLUMN_NULL)==0
102416 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
102417 /* All terms of this index match some prefix of the ORDER BY clause
102418 ** and the index is UNIQUE and no terms on the tail of the ORDER BY
102419 ** clause reference other tables in a join. If this is all true then
102420 ** the order by clause is superfluous. Not that if the matching
102421 ** condition is IS NULL then the result is not necessarily unique
102422 ** even on a UNIQUE index, so disallow those cases. */
102423 return 1;
102425 return 0;
102429 ** Prepare a crude estimate of the logarithm of the input value.
102430 ** The results need not be exact. This is only used for estimating
102431 ** the total cost of performing operations with O(logN) or O(NlogN)
102432 ** complexity. Because N is just a guess, it is no great tragedy if
102433 ** logN is a little off.
102435 static double estLog(double N){
102436 double logN = 1;
102437 double x = 10;
102438 while( N>x ){
102439 logN += 1;
102440 x *= 10;
102442 return logN;
102446 ** Two routines for printing the content of an sqlite3_index_info
102447 ** structure. Used for testing and debugging only. If neither
102448 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
102449 ** are no-ops.
102451 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
102452 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
102453 int i;
102454 if( !sqlite3WhereTrace ) return;
102455 for(i=0; i<p->nConstraint; i++){
102456 sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
102458 p->aConstraint[i].iColumn,
102459 p->aConstraint[i].iTermOffset,
102460 p->aConstraint[i].op,
102461 p->aConstraint[i].usable);
102463 for(i=0; i<p->nOrderBy; i++){
102464 sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
102466 p->aOrderBy[i].iColumn,
102467 p->aOrderBy[i].desc);
102470 static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
102471 int i;
102472 if( !sqlite3WhereTrace ) return;
102473 for(i=0; i<p->nConstraint; i++){
102474 sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
102476 p->aConstraintUsage[i].argvIndex,
102477 p->aConstraintUsage[i].omit);
102479 sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
102480 sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
102481 sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
102482 sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
102484 #else
102485 #define TRACE_IDX_INPUTS(A)
102486 #define TRACE_IDX_OUTPUTS(A)
102487 #endif
102490 ** Required because bestIndex() is called by bestOrClauseIndex()
102492 static void bestIndex(
102493 Parse*, WhereClause*, struct SrcList_item*,
102494 Bitmask, Bitmask, ExprList*, WhereCost*);
102497 ** This routine attempts to find an scanning strategy that can be used
102498 ** to optimize an 'OR' expression that is part of a WHERE clause.
102500 ** The table associated with FROM clause term pSrc may be either a
102501 ** regular B-Tree table or a virtual table.
102503 static void bestOrClauseIndex(
102504 Parse *pParse, /* The parsing context */
102505 WhereClause *pWC, /* The WHERE clause */
102506 struct SrcList_item *pSrc, /* The FROM clause term to search */
102507 Bitmask notReady, /* Mask of cursors not available for indexing */
102508 Bitmask notValid, /* Cursors not available for any purpose */
102509 ExprList *pOrderBy, /* The ORDER BY clause */
102510 WhereCost *pCost /* Lowest cost query plan */
102512 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
102513 const int iCur = pSrc->iCursor; /* The cursor of the table to be accessed */
102514 const Bitmask maskSrc = getMask(pWC->pMaskSet, iCur); /* Bitmask for pSrc */
102515 WhereTerm * const pWCEnd = &pWC->a[pWC->nTerm]; /* End of pWC->a[] */
102516 WhereTerm *pTerm; /* A single term of the WHERE clause */
102518 /* The OR-clause optimization is disallowed if the INDEXED BY or
102519 ** NOT INDEXED clauses are used or if the WHERE_AND_ONLY bit is set. */
102520 if( pSrc->notIndexed || pSrc->pIndex!=0 ){
102521 return;
102523 if( pWC->wctrlFlags & WHERE_AND_ONLY ){
102524 return;
102527 /* Search the WHERE clause terms for a usable WO_OR term. */
102528 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
102529 if( pTerm->eOperator==WO_OR
102530 && ((pTerm->prereqAll & ~maskSrc) & notReady)==0
102531 && (pTerm->u.pOrInfo->indexable & maskSrc)!=0
102533 WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
102534 WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
102535 WhereTerm *pOrTerm;
102536 int flags = WHERE_MULTI_OR;
102537 double rTotal = 0;
102538 double nRow = 0;
102539 Bitmask used = 0;
102541 for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
102542 WhereCost sTermCost;
102543 WHERETRACE(("... Multi-index OR testing for term %d of %d....\n",
102544 (pOrTerm - pOrWC->a), (pTerm - pWC->a)
102546 if( pOrTerm->eOperator==WO_AND ){
102547 WhereClause *pAndWC = &pOrTerm->u.pAndInfo->wc;
102548 bestIndex(pParse, pAndWC, pSrc, notReady, notValid, 0, &sTermCost);
102549 }else if( pOrTerm->leftCursor==iCur ){
102550 WhereClause tempWC;
102551 tempWC.pParse = pWC->pParse;
102552 tempWC.pMaskSet = pWC->pMaskSet;
102553 tempWC.pOuter = pWC;
102554 tempWC.op = TK_AND;
102555 tempWC.a = pOrTerm;
102556 tempWC.wctrlFlags = 0;
102557 tempWC.nTerm = 1;
102558 bestIndex(pParse, &tempWC, pSrc, notReady, notValid, 0, &sTermCost);
102559 }else{
102560 continue;
102562 rTotal += sTermCost.rCost;
102563 nRow += sTermCost.plan.nRow;
102564 used |= sTermCost.used;
102565 if( rTotal>=pCost->rCost ) break;
102568 /* If there is an ORDER BY clause, increase the scan cost to account
102569 ** for the cost of the sort. */
102570 if( pOrderBy!=0 ){
102571 WHERETRACE(("... sorting increases OR cost %.9g to %.9g\n",
102572 rTotal, rTotal+nRow*estLog(nRow)));
102573 rTotal += nRow*estLog(nRow);
102576 /* If the cost of scanning using this OR term for optimization is
102577 ** less than the current cost stored in pCost, replace the contents
102578 ** of pCost. */
102579 WHERETRACE(("... multi-index OR cost=%.9g nrow=%.9g\n", rTotal, nRow));
102580 if( rTotal<pCost->rCost ){
102581 pCost->rCost = rTotal;
102582 pCost->used = used;
102583 pCost->plan.nRow = nRow;
102584 pCost->plan.wsFlags = flags;
102585 pCost->plan.u.pTerm = pTerm;
102589 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
102592 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
102594 ** Return TRUE if the WHERE clause term pTerm is of a form where it
102595 ** could be used with an index to access pSrc, assuming an appropriate
102596 ** index existed.
102598 static int termCanDriveIndex(
102599 WhereTerm *pTerm, /* WHERE clause term to check */
102600 struct SrcList_item *pSrc, /* Table we are trying to access */
102601 Bitmask notReady /* Tables in outer loops of the join */
102603 char aff;
102604 if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
102605 if( pTerm->eOperator!=WO_EQ ) return 0;
102606 if( (pTerm->prereqRight & notReady)!=0 ) return 0;
102607 aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
102608 if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
102609 return 1;
102611 #endif
102613 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
102615 ** If the query plan for pSrc specified in pCost is a full table scan
102616 ** and indexing is allows (if there is no NOT INDEXED clause) and it
102617 ** possible to construct a transient index that would perform better
102618 ** than a full table scan even when the cost of constructing the index
102619 ** is taken into account, then alter the query plan to use the
102620 ** transient index.
102622 static void bestAutomaticIndex(
102623 Parse *pParse, /* The parsing context */
102624 WhereClause *pWC, /* The WHERE clause */
102625 struct SrcList_item *pSrc, /* The FROM clause term to search */
102626 Bitmask notReady, /* Mask of cursors that are not available */
102627 WhereCost *pCost /* Lowest cost query plan */
102629 double nTableRow; /* Rows in the input table */
102630 double logN; /* log(nTableRow) */
102631 double costTempIdx; /* per-query cost of the transient index */
102632 WhereTerm *pTerm; /* A single term of the WHERE clause */
102633 WhereTerm *pWCEnd; /* End of pWC->a[] */
102634 Table *pTable; /* Table tht might be indexed */
102636 if( pParse->nQueryLoop<=(double)1 ){
102637 /* There is no point in building an automatic index for a single scan */
102638 return;
102640 if( (pParse->db->flags & SQLITE_AutoIndex)==0 ){
102641 /* Automatic indices are disabled at run-time */
102642 return;
102644 if( (pCost->plan.wsFlags & WHERE_NOT_FULLSCAN)!=0 ){
102645 /* We already have some kind of index in use for this query. */
102646 return;
102648 if( pSrc->notIndexed ){
102649 /* The NOT INDEXED clause appears in the SQL. */
102650 return;
102652 if( pSrc->isCorrelated ){
102653 /* The source is a correlated sub-query. No point in indexing it. */
102654 return;
102657 assert( pParse->nQueryLoop >= (double)1 );
102658 pTable = pSrc->pTab;
102659 nTableRow = pTable->nRowEst;
102660 logN = estLog(nTableRow);
102661 costTempIdx = 2*logN*(nTableRow/pParse->nQueryLoop + 1);
102662 if( costTempIdx>=pCost->rCost ){
102663 /* The cost of creating the transient table would be greater than
102664 ** doing the full table scan */
102665 return;
102668 /* Search for any equality comparison term */
102669 pWCEnd = &pWC->a[pWC->nTerm];
102670 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
102671 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
102672 WHERETRACE(("auto-index reduces cost from %.1f to %.1f\n",
102673 pCost->rCost, costTempIdx));
102674 pCost->rCost = costTempIdx;
102675 pCost->plan.nRow = logN + 1;
102676 pCost->plan.wsFlags = WHERE_TEMP_INDEX;
102677 pCost->used = pTerm->prereqRight;
102678 break;
102682 #else
102683 # define bestAutomaticIndex(A,B,C,D,E) /* no-op */
102684 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
102687 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
102689 ** Generate code to construct the Index object for an automatic index
102690 ** and to set up the WhereLevel object pLevel so that the code generator
102691 ** makes use of the automatic index.
102693 static void constructAutomaticIndex(
102694 Parse *pParse, /* The parsing context */
102695 WhereClause *pWC, /* The WHERE clause */
102696 struct SrcList_item *pSrc, /* The FROM clause term to get the next index */
102697 Bitmask notReady, /* Mask of cursors that are not available */
102698 WhereLevel *pLevel /* Write new index here */
102700 int nColumn; /* Number of columns in the constructed index */
102701 WhereTerm *pTerm; /* A single term of the WHERE clause */
102702 WhereTerm *pWCEnd; /* End of pWC->a[] */
102703 int nByte; /* Byte of memory needed for pIdx */
102704 Index *pIdx; /* Object describing the transient index */
102705 Vdbe *v; /* Prepared statement under construction */
102706 int regIsInit; /* Register set by initialization */
102707 int addrInit; /* Address of the initialization bypass jump */
102708 Table *pTable; /* The table being indexed */
102709 KeyInfo *pKeyinfo; /* Key information for the index */
102710 int addrTop; /* Top of the index fill loop */
102711 int regRecord; /* Register holding an index record */
102712 int n; /* Column counter */
102713 int i; /* Loop counter */
102714 int mxBitCol; /* Maximum column in pSrc->colUsed */
102715 CollSeq *pColl; /* Collating sequence to on a column */
102716 Bitmask idxCols; /* Bitmap of columns used for indexing */
102717 Bitmask extraCols; /* Bitmap of additional columns */
102719 /* Generate code to skip over the creation and initialization of the
102720 ** transient index on 2nd and subsequent iterations of the loop. */
102721 v = pParse->pVdbe;
102722 assert( v!=0 );
102723 regIsInit = ++pParse->nMem;
102724 addrInit = sqlite3VdbeAddOp1(v, OP_Once, regIsInit);
102726 /* Count the number of columns that will be added to the index
102727 ** and used to match WHERE clause constraints */
102728 nColumn = 0;
102729 pTable = pSrc->pTab;
102730 pWCEnd = &pWC->a[pWC->nTerm];
102731 idxCols = 0;
102732 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
102733 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
102734 int iCol = pTerm->u.leftColumn;
102735 Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
102736 testcase( iCol==BMS );
102737 testcase( iCol==BMS-1 );
102738 if( (idxCols & cMask)==0 ){
102739 nColumn++;
102740 idxCols |= cMask;
102744 assert( nColumn>0 );
102745 pLevel->plan.nEq = nColumn;
102747 /* Count the number of additional columns needed to create a
102748 ** covering index. A "covering index" is an index that contains all
102749 ** columns that are needed by the query. With a covering index, the
102750 ** original table never needs to be accessed. Automatic indices must
102751 ** be a covering index because the index will not be updated if the
102752 ** original table changes and the index and table cannot both be used
102753 ** if they go out of sync.
102755 extraCols = pSrc->colUsed & (~idxCols | (((Bitmask)1)<<(BMS-1)));
102756 mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
102757 testcase( pTable->nCol==BMS-1 );
102758 testcase( pTable->nCol==BMS-2 );
102759 for(i=0; i<mxBitCol; i++){
102760 if( extraCols & (((Bitmask)1)<<i) ) nColumn++;
102762 if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
102763 nColumn += pTable->nCol - BMS + 1;
102765 pLevel->plan.wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WO_EQ;
102767 /* Construct the Index object to describe this index */
102768 nByte = sizeof(Index);
102769 nByte += nColumn*sizeof(int); /* Index.aiColumn */
102770 nByte += nColumn*sizeof(char*); /* Index.azColl */
102771 nByte += nColumn; /* Index.aSortOrder */
102772 pIdx = sqlite3DbMallocZero(pParse->db, nByte);
102773 if( pIdx==0 ) return;
102774 pLevel->plan.u.pIdx = pIdx;
102775 pIdx->azColl = (char**)&pIdx[1];
102776 pIdx->aiColumn = (int*)&pIdx->azColl[nColumn];
102777 pIdx->aSortOrder = (u8*)&pIdx->aiColumn[nColumn];
102778 pIdx->zName = "auto-index";
102779 pIdx->nColumn = nColumn;
102780 pIdx->pTable = pTable;
102781 n = 0;
102782 idxCols = 0;
102783 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
102784 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
102785 int iCol = pTerm->u.leftColumn;
102786 Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
102787 if( (idxCols & cMask)==0 ){
102788 Expr *pX = pTerm->pExpr;
102789 idxCols |= cMask;
102790 pIdx->aiColumn[n] = pTerm->u.leftColumn;
102791 pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
102792 pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
102797 assert( (u32)n==pLevel->plan.nEq );
102799 /* Add additional columns needed to make the automatic index into
102800 ** a covering index */
102801 for(i=0; i<mxBitCol; i++){
102802 if( extraCols & (((Bitmask)1)<<i) ){
102803 pIdx->aiColumn[n] = i;
102804 pIdx->azColl[n] = "BINARY";
102808 if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
102809 for(i=BMS-1; i<pTable->nCol; i++){
102810 pIdx->aiColumn[n] = i;
102811 pIdx->azColl[n] = "BINARY";
102815 assert( n==nColumn );
102817 /* Create the automatic index */
102818 pKeyinfo = sqlite3IndexKeyinfo(pParse, pIdx);
102819 assert( pLevel->iIdxCur>=0 );
102820 sqlite3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nColumn+1, 0,
102821 (char*)pKeyinfo, P4_KEYINFO_HANDOFF);
102822 VdbeComment((v, "for %s", pTable->zName));
102824 /* Fill the automatic index with content */
102825 addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur);
102826 regRecord = sqlite3GetTempReg(pParse);
102827 sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 1);
102828 sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
102829 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
102830 sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
102831 sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
102832 sqlite3VdbeJumpHere(v, addrTop);
102833 sqlite3ReleaseTempReg(pParse, regRecord);
102835 /* Jump here when skipping the initialization */
102836 sqlite3VdbeJumpHere(v, addrInit);
102838 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
102840 #ifndef SQLITE_OMIT_VIRTUALTABLE
102842 ** Allocate and populate an sqlite3_index_info structure. It is the
102843 ** responsibility of the caller to eventually release the structure
102844 ** by passing the pointer returned by this function to sqlite3_free().
102846 static sqlite3_index_info *allocateIndexInfo(
102847 Parse *pParse,
102848 WhereClause *pWC,
102849 struct SrcList_item *pSrc,
102850 ExprList *pOrderBy
102852 int i, j;
102853 int nTerm;
102854 struct sqlite3_index_constraint *pIdxCons;
102855 struct sqlite3_index_orderby *pIdxOrderBy;
102856 struct sqlite3_index_constraint_usage *pUsage;
102857 WhereTerm *pTerm;
102858 int nOrderBy;
102859 sqlite3_index_info *pIdxInfo;
102861 WHERETRACE(("Recomputing index info for %s...\n", pSrc->pTab->zName));
102863 /* Count the number of possible WHERE clause constraints referring
102864 ** to this virtual table */
102865 for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
102866 if( pTerm->leftCursor != pSrc->iCursor ) continue;
102867 assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
102868 testcase( pTerm->eOperator==WO_IN );
102869 testcase( pTerm->eOperator==WO_ISNULL );
102870 if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
102871 if( pTerm->wtFlags & TERM_VNULL ) continue;
102872 nTerm++;
102875 /* If the ORDER BY clause contains only columns in the current
102876 ** virtual table then allocate space for the aOrderBy part of
102877 ** the sqlite3_index_info structure.
102879 nOrderBy = 0;
102880 if( pOrderBy ){
102881 for(i=0; i<pOrderBy->nExpr; i++){
102882 Expr *pExpr = pOrderBy->a[i].pExpr;
102883 if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
102885 if( i==pOrderBy->nExpr ){
102886 nOrderBy = pOrderBy->nExpr;
102890 /* Allocate the sqlite3_index_info structure
102892 pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
102893 + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
102894 + sizeof(*pIdxOrderBy)*nOrderBy );
102895 if( pIdxInfo==0 ){
102896 sqlite3ErrorMsg(pParse, "out of memory");
102897 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
102898 return 0;
102901 /* Initialize the structure. The sqlite3_index_info structure contains
102902 ** many fields that are declared "const" to prevent xBestIndex from
102903 ** changing them. We have to do some funky casting in order to
102904 ** initialize those fields.
102906 pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
102907 pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
102908 pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
102909 *(int*)&pIdxInfo->nConstraint = nTerm;
102910 *(int*)&pIdxInfo->nOrderBy = nOrderBy;
102911 *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
102912 *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
102913 *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
102914 pUsage;
102916 for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
102917 if( pTerm->leftCursor != pSrc->iCursor ) continue;
102918 assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
102919 testcase( pTerm->eOperator==WO_IN );
102920 testcase( pTerm->eOperator==WO_ISNULL );
102921 if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
102922 if( pTerm->wtFlags & TERM_VNULL ) continue;
102923 pIdxCons[j].iColumn = pTerm->u.leftColumn;
102924 pIdxCons[j].iTermOffset = i;
102925 pIdxCons[j].op = (u8)pTerm->eOperator;
102926 /* The direct assignment in the previous line is possible only because
102927 ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
102928 ** following asserts verify this fact. */
102929 assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
102930 assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
102931 assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
102932 assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
102933 assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
102934 assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
102935 assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
102938 for(i=0; i<nOrderBy; i++){
102939 Expr *pExpr = pOrderBy->a[i].pExpr;
102940 pIdxOrderBy[i].iColumn = pExpr->iColumn;
102941 pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
102944 return pIdxInfo;
102948 ** The table object reference passed as the second argument to this function
102949 ** must represent a virtual table. This function invokes the xBestIndex()
102950 ** method of the virtual table with the sqlite3_index_info pointer passed
102951 ** as the argument.
102953 ** If an error occurs, pParse is populated with an error message and a
102954 ** non-zero value is returned. Otherwise, 0 is returned and the output
102955 ** part of the sqlite3_index_info structure is left populated.
102957 ** Whether or not an error is returned, it is the responsibility of the
102958 ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
102959 ** that this is required.
102961 static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
102962 sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
102963 int i;
102964 int rc;
102966 WHERETRACE(("xBestIndex for %s\n", pTab->zName));
102967 TRACE_IDX_INPUTS(p);
102968 rc = pVtab->pModule->xBestIndex(pVtab, p);
102969 TRACE_IDX_OUTPUTS(p);
102971 if( rc!=SQLITE_OK ){
102972 if( rc==SQLITE_NOMEM ){
102973 pParse->db->mallocFailed = 1;
102974 }else if( !pVtab->zErrMsg ){
102975 sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
102976 }else{
102977 sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
102980 sqlite3_free(pVtab->zErrMsg);
102981 pVtab->zErrMsg = 0;
102983 for(i=0; i<p->nConstraint; i++){
102984 if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
102985 sqlite3ErrorMsg(pParse,
102986 "table %s: xBestIndex returned an invalid plan", pTab->zName);
102990 return pParse->nErr;
102995 ** Compute the best index for a virtual table.
102997 ** The best index is computed by the xBestIndex method of the virtual
102998 ** table module. This routine is really just a wrapper that sets up
102999 ** the sqlite3_index_info structure that is used to communicate with
103000 ** xBestIndex.
103002 ** In a join, this routine might be called multiple times for the
103003 ** same virtual table. The sqlite3_index_info structure is created
103004 ** and initialized on the first invocation and reused on all subsequent
103005 ** invocations. The sqlite3_index_info structure is also used when
103006 ** code is generated to access the virtual table. The whereInfoDelete()
103007 ** routine takes care of freeing the sqlite3_index_info structure after
103008 ** everybody has finished with it.
103010 static void bestVirtualIndex(
103011 Parse *pParse, /* The parsing context */
103012 WhereClause *pWC, /* The WHERE clause */
103013 struct SrcList_item *pSrc, /* The FROM clause term to search */
103014 Bitmask notReady, /* Mask of cursors not available for index */
103015 Bitmask notValid, /* Cursors not valid for any purpose */
103016 ExprList *pOrderBy, /* The order by clause */
103017 WhereCost *pCost, /* Lowest cost query plan */
103018 sqlite3_index_info **ppIdxInfo /* Index information passed to xBestIndex */
103020 Table *pTab = pSrc->pTab;
103021 sqlite3_index_info *pIdxInfo;
103022 struct sqlite3_index_constraint *pIdxCons;
103023 struct sqlite3_index_constraint_usage *pUsage;
103024 WhereTerm *pTerm;
103025 int i, j;
103026 int nOrderBy;
103027 double rCost;
103029 /* Make sure wsFlags is initialized to some sane value. Otherwise, if the
103030 ** malloc in allocateIndexInfo() fails and this function returns leaving
103031 ** wsFlags in an uninitialized state, the caller may behave unpredictably.
103033 memset(pCost, 0, sizeof(*pCost));
103034 pCost->plan.wsFlags = WHERE_VIRTUALTABLE;
103036 /* If the sqlite3_index_info structure has not been previously
103037 ** allocated and initialized, then allocate and initialize it now.
103039 pIdxInfo = *ppIdxInfo;
103040 if( pIdxInfo==0 ){
103041 *ppIdxInfo = pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pOrderBy);
103043 if( pIdxInfo==0 ){
103044 return;
103047 /* At this point, the sqlite3_index_info structure that pIdxInfo points
103048 ** to will have been initialized, either during the current invocation or
103049 ** during some prior invocation. Now we just have to customize the
103050 ** details of pIdxInfo for the current invocation and pass it to
103051 ** xBestIndex.
103054 /* The module name must be defined. Also, by this point there must
103055 ** be a pointer to an sqlite3_vtab structure. Otherwise
103056 ** sqlite3ViewGetColumnNames() would have picked up the error.
103058 assert( pTab->azModuleArg && pTab->azModuleArg[0] );
103059 assert( sqlite3GetVTable(pParse->db, pTab) );
103061 /* Set the aConstraint[].usable fields and initialize all
103062 ** output variables to zero.
103064 ** aConstraint[].usable is true for constraints where the right-hand
103065 ** side contains only references to tables to the left of the current
103066 ** table. In other words, if the constraint is of the form:
103068 ** column = expr
103070 ** and we are evaluating a join, then the constraint on column is
103071 ** only valid if all tables referenced in expr occur to the left
103072 ** of the table containing column.
103074 ** The aConstraints[] array contains entries for all constraints
103075 ** on the current table. That way we only have to compute it once
103076 ** even though we might try to pick the best index multiple times.
103077 ** For each attempt at picking an index, the order of tables in the
103078 ** join might be different so we have to recompute the usable flag
103079 ** each time.
103081 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
103082 pUsage = pIdxInfo->aConstraintUsage;
103083 for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
103084 j = pIdxCons->iTermOffset;
103085 pTerm = &pWC->a[j];
103086 pIdxCons->usable = (pTerm->prereqRight&notReady) ? 0 : 1;
103088 memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
103089 if( pIdxInfo->needToFreeIdxStr ){
103090 sqlite3_free(pIdxInfo->idxStr);
103092 pIdxInfo->idxStr = 0;
103093 pIdxInfo->idxNum = 0;
103094 pIdxInfo->needToFreeIdxStr = 0;
103095 pIdxInfo->orderByConsumed = 0;
103096 /* ((double)2) In case of SQLITE_OMIT_FLOATING_POINT... */
103097 pIdxInfo->estimatedCost = SQLITE_BIG_DBL / ((double)2);
103098 nOrderBy = pIdxInfo->nOrderBy;
103099 if( !pOrderBy ){
103100 pIdxInfo->nOrderBy = 0;
103103 if( vtabBestIndex(pParse, pTab, pIdxInfo) ){
103104 return;
103107 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
103108 for(i=0; i<pIdxInfo->nConstraint; i++){
103109 if( pUsage[i].argvIndex>0 ){
103110 pCost->used |= pWC->a[pIdxCons[i].iTermOffset].prereqRight;
103114 /* If there is an ORDER BY clause, and the selected virtual table index
103115 ** does not satisfy it, increase the cost of the scan accordingly. This
103116 ** matches the processing for non-virtual tables in bestBtreeIndex().
103118 rCost = pIdxInfo->estimatedCost;
103119 if( pOrderBy && pIdxInfo->orderByConsumed==0 ){
103120 rCost += estLog(rCost)*rCost;
103123 /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
103124 ** inital value of lowestCost in this loop. If it is, then the
103125 ** (cost<lowestCost) test below will never be true.
103127 ** Use "(double)2" instead of "2.0" in case OMIT_FLOATING_POINT
103128 ** is defined.
103130 if( (SQLITE_BIG_DBL/((double)2))<rCost ){
103131 pCost->rCost = (SQLITE_BIG_DBL/((double)2));
103132 }else{
103133 pCost->rCost = rCost;
103135 pCost->plan.u.pVtabIdx = pIdxInfo;
103136 if( pIdxInfo->orderByConsumed ){
103137 pCost->plan.wsFlags |= WHERE_ORDERBY;
103139 pCost->plan.nEq = 0;
103140 pIdxInfo->nOrderBy = nOrderBy;
103142 /* Try to find a more efficient access pattern by using multiple indexes
103143 ** to optimize an OR expression within the WHERE clause.
103145 bestOrClauseIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost);
103147 #endif /* SQLITE_OMIT_VIRTUALTABLE */
103149 #ifdef SQLITE_ENABLE_STAT3
103151 ** Estimate the location of a particular key among all keys in an
103152 ** index. Store the results in aStat as follows:
103154 ** aStat[0] Est. number of rows less than pVal
103155 ** aStat[1] Est. number of rows equal to pVal
103157 ** Return SQLITE_OK on success.
103159 static int whereKeyStats(
103160 Parse *pParse, /* Database connection */
103161 Index *pIdx, /* Index to consider domain of */
103162 sqlite3_value *pVal, /* Value to consider */
103163 int roundUp, /* Round up if true. Round down if false */
103164 tRowcnt *aStat /* OUT: stats written here */
103166 tRowcnt n;
103167 IndexSample *aSample;
103168 int i, eType;
103169 int isEq = 0;
103170 i64 v;
103171 double r, rS;
103173 assert( roundUp==0 || roundUp==1 );
103174 assert( pIdx->nSample>0 );
103175 if( pVal==0 ) return SQLITE_ERROR;
103176 n = pIdx->aiRowEst[0];
103177 aSample = pIdx->aSample;
103178 eType = sqlite3_value_type(pVal);
103180 if( eType==SQLITE_INTEGER ){
103181 v = sqlite3_value_int64(pVal);
103182 r = (i64)v;
103183 for(i=0; i<pIdx->nSample; i++){
103184 if( aSample[i].eType==SQLITE_NULL ) continue;
103185 if( aSample[i].eType>=SQLITE_TEXT ) break;
103186 if( aSample[i].eType==SQLITE_INTEGER ){
103187 if( aSample[i].u.i>=v ){
103188 isEq = aSample[i].u.i==v;
103189 break;
103191 }else{
103192 assert( aSample[i].eType==SQLITE_FLOAT );
103193 if( aSample[i].u.r>=r ){
103194 isEq = aSample[i].u.r==r;
103195 break;
103199 }else if( eType==SQLITE_FLOAT ){
103200 r = sqlite3_value_double(pVal);
103201 for(i=0; i<pIdx->nSample; i++){
103202 if( aSample[i].eType==SQLITE_NULL ) continue;
103203 if( aSample[i].eType>=SQLITE_TEXT ) break;
103204 if( aSample[i].eType==SQLITE_FLOAT ){
103205 rS = aSample[i].u.r;
103206 }else{
103207 rS = aSample[i].u.i;
103209 if( rS>=r ){
103210 isEq = rS==r;
103211 break;
103214 }else if( eType==SQLITE_NULL ){
103215 i = 0;
103216 if( aSample[0].eType==SQLITE_NULL ) isEq = 1;
103217 }else{
103218 assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
103219 for(i=0; i<pIdx->nSample; i++){
103220 if( aSample[i].eType==SQLITE_TEXT || aSample[i].eType==SQLITE_BLOB ){
103221 break;
103224 if( i<pIdx->nSample ){
103225 sqlite3 *db = pParse->db;
103226 CollSeq *pColl;
103227 const u8 *z;
103228 if( eType==SQLITE_BLOB ){
103229 z = (const u8 *)sqlite3_value_blob(pVal);
103230 pColl = db->pDfltColl;
103231 assert( pColl->enc==SQLITE_UTF8 );
103232 }else{
103233 pColl = sqlite3GetCollSeq(db, SQLITE_UTF8, 0, *pIdx->azColl);
103234 if( pColl==0 ){
103235 sqlite3ErrorMsg(pParse, "no such collation sequence: %s",
103236 *pIdx->azColl);
103237 return SQLITE_ERROR;
103239 z = (const u8 *)sqlite3ValueText(pVal, pColl->enc);
103240 if( !z ){
103241 return SQLITE_NOMEM;
103243 assert( z && pColl && pColl->xCmp );
103245 n = sqlite3ValueBytes(pVal, pColl->enc);
103247 for(; i<pIdx->nSample; i++){
103248 int c;
103249 int eSampletype = aSample[i].eType;
103250 if( eSampletype<eType ) continue;
103251 if( eSampletype!=eType ) break;
103252 #ifndef SQLITE_OMIT_UTF16
103253 if( pColl->enc!=SQLITE_UTF8 ){
103254 int nSample;
103255 char *zSample = sqlite3Utf8to16(
103256 db, pColl->enc, aSample[i].u.z, aSample[i].nByte, &nSample
103258 if( !zSample ){
103259 assert( db->mallocFailed );
103260 return SQLITE_NOMEM;
103262 c = pColl->xCmp(pColl->pUser, nSample, zSample, n, z);
103263 sqlite3DbFree(db, zSample);
103264 }else
103265 #endif
103267 c = pColl->xCmp(pColl->pUser, aSample[i].nByte, aSample[i].u.z, n, z);
103269 if( c>=0 ){
103270 if( c==0 ) isEq = 1;
103271 break;
103277 /* At this point, aSample[i] is the first sample that is greater than
103278 ** or equal to pVal. Or if i==pIdx->nSample, then all samples are less
103279 ** than pVal. If aSample[i]==pVal, then isEq==1.
103281 if( isEq ){
103282 assert( i<pIdx->nSample );
103283 aStat[0] = aSample[i].nLt;
103284 aStat[1] = aSample[i].nEq;
103285 }else{
103286 tRowcnt iLower, iUpper, iGap;
103287 if( i==0 ){
103288 iLower = 0;
103289 iUpper = aSample[0].nLt;
103290 }else{
103291 iUpper = i>=pIdx->nSample ? n : aSample[i].nLt;
103292 iLower = aSample[i-1].nEq + aSample[i-1].nLt;
103294 aStat[1] = pIdx->avgEq;
103295 if( iLower>=iUpper ){
103296 iGap = 0;
103297 }else{
103298 iGap = iUpper - iLower;
103300 if( roundUp ){
103301 iGap = (iGap*2)/3;
103302 }else{
103303 iGap = iGap/3;
103305 aStat[0] = iLower + iGap;
103307 return SQLITE_OK;
103309 #endif /* SQLITE_ENABLE_STAT3 */
103312 ** If expression pExpr represents a literal value, set *pp to point to
103313 ** an sqlite3_value structure containing the same value, with affinity
103314 ** aff applied to it, before returning. It is the responsibility of the
103315 ** caller to eventually release this structure by passing it to
103316 ** sqlite3ValueFree().
103318 ** If the current parse is a recompile (sqlite3Reprepare()) and pExpr
103319 ** is an SQL variable that currently has a non-NULL value bound to it,
103320 ** create an sqlite3_value structure containing this value, again with
103321 ** affinity aff applied to it, instead.
103323 ** If neither of the above apply, set *pp to NULL.
103325 ** If an error occurs, return an error code. Otherwise, SQLITE_OK.
103327 #ifdef SQLITE_ENABLE_STAT3
103328 static int valueFromExpr(
103329 Parse *pParse,
103330 Expr *pExpr,
103331 u8 aff,
103332 sqlite3_value **pp
103334 if( pExpr->op==TK_VARIABLE
103335 || (pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
103337 int iVar = pExpr->iColumn;
103338 sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
103339 *pp = sqlite3VdbeGetValue(pParse->pReprepare, iVar, aff);
103340 return SQLITE_OK;
103342 return sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, aff, pp);
103344 #endif
103347 ** This function is used to estimate the number of rows that will be visited
103348 ** by scanning an index for a range of values. The range may have an upper
103349 ** bound, a lower bound, or both. The WHERE clause terms that set the upper
103350 ** and lower bounds are represented by pLower and pUpper respectively. For
103351 ** example, assuming that index p is on t1(a):
103353 ** ... FROM t1 WHERE a > ? AND a < ? ...
103354 ** |_____| |_____|
103355 ** | |
103356 ** pLower pUpper
103358 ** If either of the upper or lower bound is not present, then NULL is passed in
103359 ** place of the corresponding WhereTerm.
103361 ** The nEq parameter is passed the index of the index column subject to the
103362 ** range constraint. Or, equivalently, the number of equality constraints
103363 ** optimized by the proposed index scan. For example, assuming index p is
103364 ** on t1(a, b), and the SQL query is:
103366 ** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
103368 ** then nEq should be passed the value 1 (as the range restricted column,
103369 ** b, is the second left-most column of the index). Or, if the query is:
103371 ** ... FROM t1 WHERE a > ? AND a < ? ...
103373 ** then nEq should be passed 0.
103375 ** The returned value is an integer divisor to reduce the estimated
103376 ** search space. A return value of 1 means that range constraints are
103377 ** no help at all. A return value of 2 means range constraints are
103378 ** expected to reduce the search space by half. And so forth...
103380 ** In the absence of sqlite_stat3 ANALYZE data, each range inequality
103381 ** reduces the search space by a factor of 4. Hence a single constraint (x>?)
103382 ** results in a return of 4 and a range constraint (x>? AND x<?) results
103383 ** in a return of 16.
103385 static int whereRangeScanEst(
103386 Parse *pParse, /* Parsing & code generating context */
103387 Index *p, /* The index containing the range-compared column; "x" */
103388 int nEq, /* index into p->aCol[] of the range-compared column */
103389 WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
103390 WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
103391 double *pRangeDiv /* OUT: Reduce search space by this divisor */
103393 int rc = SQLITE_OK;
103395 #ifdef SQLITE_ENABLE_STAT3
103397 if( nEq==0 && p->nSample ){
103398 sqlite3_value *pRangeVal;
103399 tRowcnt iLower = 0;
103400 tRowcnt iUpper = p->aiRowEst[0];
103401 tRowcnt a[2];
103402 u8 aff = p->pTable->aCol[p->aiColumn[0]].affinity;
103404 if( pLower ){
103405 Expr *pExpr = pLower->pExpr->pRight;
103406 rc = valueFromExpr(pParse, pExpr, aff, &pRangeVal);
103407 assert( pLower->eOperator==WO_GT || pLower->eOperator==WO_GE );
103408 if( rc==SQLITE_OK
103409 && whereKeyStats(pParse, p, pRangeVal, 0, a)==SQLITE_OK
103411 iLower = a[0];
103412 if( pLower->eOperator==WO_GT ) iLower += a[1];
103414 sqlite3ValueFree(pRangeVal);
103416 if( rc==SQLITE_OK && pUpper ){
103417 Expr *pExpr = pUpper->pExpr->pRight;
103418 rc = valueFromExpr(pParse, pExpr, aff, &pRangeVal);
103419 assert( pUpper->eOperator==WO_LT || pUpper->eOperator==WO_LE );
103420 if( rc==SQLITE_OK
103421 && whereKeyStats(pParse, p, pRangeVal, 1, a)==SQLITE_OK
103423 iUpper = a[0];
103424 if( pUpper->eOperator==WO_LE ) iUpper += a[1];
103426 sqlite3ValueFree(pRangeVal);
103428 if( rc==SQLITE_OK ){
103429 if( iUpper<=iLower ){
103430 *pRangeDiv = (double)p->aiRowEst[0];
103431 }else{
103432 *pRangeDiv = (double)p->aiRowEst[0]/(double)(iUpper - iLower);
103434 WHERETRACE(("range scan regions: %u..%u div=%g\n",
103435 (u32)iLower, (u32)iUpper, *pRangeDiv));
103436 return SQLITE_OK;
103439 #else
103440 UNUSED_PARAMETER(pParse);
103441 UNUSED_PARAMETER(p);
103442 UNUSED_PARAMETER(nEq);
103443 #endif
103444 assert( pLower || pUpper );
103445 *pRangeDiv = (double)1;
103446 if( pLower && (pLower->wtFlags & TERM_VNULL)==0 ) *pRangeDiv *= (double)4;
103447 if( pUpper ) *pRangeDiv *= (double)4;
103448 return rc;
103451 #ifdef SQLITE_ENABLE_STAT3
103453 ** Estimate the number of rows that will be returned based on
103454 ** an equality constraint x=VALUE and where that VALUE occurs in
103455 ** the histogram data. This only works when x is the left-most
103456 ** column of an index and sqlite_stat3 histogram data is available
103457 ** for that index. When pExpr==NULL that means the constraint is
103458 ** "x IS NULL" instead of "x=VALUE".
103460 ** Write the estimated row count into *pnRow and return SQLITE_OK.
103461 ** If unable to make an estimate, leave *pnRow unchanged and return
103462 ** non-zero.
103464 ** This routine can fail if it is unable to load a collating sequence
103465 ** required for string comparison, or if unable to allocate memory
103466 ** for a UTF conversion required for comparison. The error is stored
103467 ** in the pParse structure.
103469 static int whereEqualScanEst(
103470 Parse *pParse, /* Parsing & code generating context */
103471 Index *p, /* The index whose left-most column is pTerm */
103472 Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
103473 double *pnRow /* Write the revised row estimate here */
103475 sqlite3_value *pRhs = 0; /* VALUE on right-hand side of pTerm */
103476 u8 aff; /* Column affinity */
103477 int rc; /* Subfunction return code */
103478 tRowcnt a[2]; /* Statistics */
103480 assert( p->aSample!=0 );
103481 assert( p->nSample>0 );
103482 aff = p->pTable->aCol[p->aiColumn[0]].affinity;
103483 if( pExpr ){
103484 rc = valueFromExpr(pParse, pExpr, aff, &pRhs);
103485 if( rc ) goto whereEqualScanEst_cancel;
103486 }else{
103487 pRhs = sqlite3ValueNew(pParse->db);
103489 if( pRhs==0 ) return SQLITE_NOTFOUND;
103490 rc = whereKeyStats(pParse, p, pRhs, 0, a);
103491 if( rc==SQLITE_OK ){
103492 WHERETRACE(("equality scan regions: %d\n", (int)a[1]));
103493 *pnRow = a[1];
103495 whereEqualScanEst_cancel:
103496 sqlite3ValueFree(pRhs);
103497 return rc;
103499 #endif /* defined(SQLITE_ENABLE_STAT3) */
103501 #ifdef SQLITE_ENABLE_STAT3
103503 ** Estimate the number of rows that will be returned based on
103504 ** an IN constraint where the right-hand side of the IN operator
103505 ** is a list of values. Example:
103507 ** WHERE x IN (1,2,3,4)
103509 ** Write the estimated row count into *pnRow and return SQLITE_OK.
103510 ** If unable to make an estimate, leave *pnRow unchanged and return
103511 ** non-zero.
103513 ** This routine can fail if it is unable to load a collating sequence
103514 ** required for string comparison, or if unable to allocate memory
103515 ** for a UTF conversion required for comparison. The error is stored
103516 ** in the pParse structure.
103518 static int whereInScanEst(
103519 Parse *pParse, /* Parsing & code generating context */
103520 Index *p, /* The index whose left-most column is pTerm */
103521 ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
103522 double *pnRow /* Write the revised row estimate here */
103524 int rc = SQLITE_OK; /* Subfunction return code */
103525 double nEst; /* Number of rows for a single term */
103526 double nRowEst = (double)0; /* New estimate of the number of rows */
103527 int i; /* Loop counter */
103529 assert( p->aSample!=0 );
103530 for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
103531 nEst = p->aiRowEst[0];
103532 rc = whereEqualScanEst(pParse, p, pList->a[i].pExpr, &nEst);
103533 nRowEst += nEst;
103535 if( rc==SQLITE_OK ){
103536 if( nRowEst > p->aiRowEst[0] ) nRowEst = p->aiRowEst[0];
103537 *pnRow = nRowEst;
103538 WHERETRACE(("IN row estimate: est=%g\n", nRowEst));
103540 return rc;
103542 #endif /* defined(SQLITE_ENABLE_STAT3) */
103546 ** Find the best query plan for accessing a particular table. Write the
103547 ** best query plan and its cost into the WhereCost object supplied as the
103548 ** last parameter.
103550 ** The lowest cost plan wins. The cost is an estimate of the amount of
103551 ** CPU and disk I/O needed to process the requested result.
103552 ** Factors that influence cost include:
103554 ** * The estimated number of rows that will be retrieved. (The
103555 ** fewer the better.)
103557 ** * Whether or not sorting must occur.
103559 ** * Whether or not there must be separate lookups in the
103560 ** index and in the main table.
103562 ** If there was an INDEXED BY clause (pSrc->pIndex) attached to the table in
103563 ** the SQL statement, then this function only considers plans using the
103564 ** named index. If no such plan is found, then the returned cost is
103565 ** SQLITE_BIG_DBL. If a plan is found that uses the named index,
103566 ** then the cost is calculated in the usual way.
103568 ** If a NOT INDEXED clause (pSrc->notIndexed!=0) was attached to the table
103569 ** in the SELECT statement, then no indexes are considered. However, the
103570 ** selected plan may still take advantage of the built-in rowid primary key
103571 ** index.
103573 static void bestBtreeIndex(
103574 Parse *pParse, /* The parsing context */
103575 WhereClause *pWC, /* The WHERE clause */
103576 struct SrcList_item *pSrc, /* The FROM clause term to search */
103577 Bitmask notReady, /* Mask of cursors not available for indexing */
103578 Bitmask notValid, /* Cursors not available for any purpose */
103579 ExprList *pOrderBy, /* The ORDER BY clause */
103580 ExprList *pDistinct, /* The select-list if query is DISTINCT */
103581 WhereCost *pCost /* Lowest cost query plan */
103583 int iCur = pSrc->iCursor; /* The cursor of the table to be accessed */
103584 Index *pProbe; /* An index we are evaluating */
103585 Index *pIdx; /* Copy of pProbe, or zero for IPK index */
103586 int eqTermMask; /* Current mask of valid equality operators */
103587 int idxEqTermMask; /* Index mask of valid equality operators */
103588 Index sPk; /* A fake index object for the primary key */
103589 tRowcnt aiRowEstPk[2]; /* The aiRowEst[] value for the sPk index */
103590 int aiColumnPk = -1; /* The aColumn[] value for the sPk index */
103591 int wsFlagMask; /* Allowed flags in pCost->plan.wsFlag */
103593 /* Initialize the cost to a worst-case value */
103594 memset(pCost, 0, sizeof(*pCost));
103595 pCost->rCost = SQLITE_BIG_DBL;
103597 /* If the pSrc table is the right table of a LEFT JOIN then we may not
103598 ** use an index to satisfy IS NULL constraints on that table. This is
103599 ** because columns might end up being NULL if the table does not match -
103600 ** a circumstance which the index cannot help us discover. Ticket #2177.
103602 if( pSrc->jointype & JT_LEFT ){
103603 idxEqTermMask = WO_EQ|WO_IN;
103604 }else{
103605 idxEqTermMask = WO_EQ|WO_IN|WO_ISNULL;
103608 if( pSrc->pIndex ){
103609 /* An INDEXED BY clause specifies a particular index to use */
103610 pIdx = pProbe = pSrc->pIndex;
103611 wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
103612 eqTermMask = idxEqTermMask;
103613 }else{
103614 /* There is no INDEXED BY clause. Create a fake Index object in local
103615 ** variable sPk to represent the rowid primary key index. Make this
103616 ** fake index the first in a chain of Index objects with all of the real
103617 ** indices to follow */
103618 Index *pFirst; /* First of real indices on the table */
103619 memset(&sPk, 0, sizeof(Index));
103620 sPk.nColumn = 1;
103621 sPk.aiColumn = &aiColumnPk;
103622 sPk.aiRowEst = aiRowEstPk;
103623 sPk.onError = OE_Replace;
103624 sPk.pTable = pSrc->pTab;
103625 aiRowEstPk[0] = pSrc->pTab->nRowEst;
103626 aiRowEstPk[1] = 1;
103627 pFirst = pSrc->pTab->pIndex;
103628 if( pSrc->notIndexed==0 ){
103629 /* The real indices of the table are only considered if the
103630 ** NOT INDEXED qualifier is omitted from the FROM clause */
103631 sPk.pNext = pFirst;
103633 pProbe = &sPk;
103634 wsFlagMask = ~(
103635 WHERE_COLUMN_IN|WHERE_COLUMN_EQ|WHERE_COLUMN_NULL|WHERE_COLUMN_RANGE
103637 eqTermMask = WO_EQ|WO_IN;
103638 pIdx = 0;
103641 /* Loop over all indices looking for the best one to use
103643 for(; pProbe; pIdx=pProbe=pProbe->pNext){
103644 const tRowcnt * const aiRowEst = pProbe->aiRowEst;
103645 double cost; /* Cost of using pProbe */
103646 double nRow; /* Estimated number of rows in result set */
103647 double log10N = (double)1; /* base-10 logarithm of nRow (inexact) */
103648 int rev; /* True to scan in reverse order */
103649 int wsFlags = 0;
103650 Bitmask used = 0;
103652 /* The following variables are populated based on the properties of
103653 ** index being evaluated. They are then used to determine the expected
103654 ** cost and number of rows returned.
103656 ** nEq:
103657 ** Number of equality terms that can be implemented using the index.
103658 ** In other words, the number of initial fields in the index that
103659 ** are used in == or IN or NOT NULL constraints of the WHERE clause.
103661 ** nInMul:
103662 ** The "in-multiplier". This is an estimate of how many seek operations
103663 ** SQLite must perform on the index in question. For example, if the
103664 ** WHERE clause is:
103666 ** WHERE a IN (1, 2, 3) AND b IN (4, 5, 6)
103668 ** SQLite must perform 9 lookups on an index on (a, b), so nInMul is
103669 ** set to 9. Given the same schema and either of the following WHERE
103670 ** clauses:
103672 ** WHERE a = 1
103673 ** WHERE a >= 2
103675 ** nInMul is set to 1.
103677 ** If there exists a WHERE term of the form "x IN (SELECT ...)", then
103678 ** the sub-select is assumed to return 25 rows for the purposes of
103679 ** determining nInMul.
103681 ** bInEst:
103682 ** Set to true if there was at least one "x IN (SELECT ...)" term used
103683 ** in determining the value of nInMul. Note that the RHS of the
103684 ** IN operator must be a SELECT, not a value list, for this variable
103685 ** to be true.
103687 ** rangeDiv:
103688 ** An estimate of a divisor by which to reduce the search space due
103689 ** to inequality constraints. In the absence of sqlite_stat3 ANALYZE
103690 ** data, a single inequality reduces the search space to 1/4rd its
103691 ** original size (rangeDiv==4). Two inequalities reduce the search
103692 ** space to 1/16th of its original size (rangeDiv==16).
103694 ** bSort:
103695 ** Boolean. True if there is an ORDER BY clause that will require an
103696 ** external sort (i.e. scanning the index being evaluated will not
103697 ** correctly order records).
103699 ** bLookup:
103700 ** Boolean. True if a table lookup is required for each index entry
103701 ** visited. In other words, true if this is not a covering index.
103702 ** This is always false for the rowid primary key index of a table.
103703 ** For other indexes, it is true unless all the columns of the table
103704 ** used by the SELECT statement are present in the index (such an
103705 ** index is sometimes described as a covering index).
103706 ** For example, given the index on (a, b), the second of the following
103707 ** two queries requires table b-tree lookups in order to find the value
103708 ** of column c, but the first does not because columns a and b are
103709 ** both available in the index.
103711 ** SELECT a, b FROM tbl WHERE a = 1;
103712 ** SELECT a, b, c FROM tbl WHERE a = 1;
103714 int nEq; /* Number of == or IN terms matching index */
103715 int bInEst = 0; /* True if "x IN (SELECT...)" seen */
103716 int nInMul = 1; /* Number of distinct equalities to lookup */
103717 double rangeDiv = (double)1; /* Estimated reduction in search space */
103718 int nBound = 0; /* Number of range constraints seen */
103719 int bSort = !!pOrderBy; /* True if external sort required */
103720 int bDist = !!pDistinct; /* True if index cannot help with DISTINCT */
103721 int bLookup = 0; /* True if not a covering index */
103722 WhereTerm *pTerm; /* A single term of the WHERE clause */
103723 #ifdef SQLITE_ENABLE_STAT3
103724 WhereTerm *pFirstTerm = 0; /* First term matching the index */
103725 #endif
103727 /* Determine the values of nEq and nInMul */
103728 for(nEq=0; nEq<pProbe->nColumn; nEq++){
103729 int j = pProbe->aiColumn[nEq];
103730 pTerm = findTerm(pWC, iCur, j, notReady, eqTermMask, pIdx);
103731 if( pTerm==0 ) break;
103732 wsFlags |= (WHERE_COLUMN_EQ|WHERE_ROWID_EQ);
103733 testcase( pTerm->pWC!=pWC );
103734 if( pTerm->eOperator & WO_IN ){
103735 Expr *pExpr = pTerm->pExpr;
103736 wsFlags |= WHERE_COLUMN_IN;
103737 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
103738 /* "x IN (SELECT ...)": Assume the SELECT returns 25 rows */
103739 nInMul *= 25;
103740 bInEst = 1;
103741 }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
103742 /* "x IN (value, value, ...)" */
103743 nInMul *= pExpr->x.pList->nExpr;
103745 }else if( pTerm->eOperator & WO_ISNULL ){
103746 wsFlags |= WHERE_COLUMN_NULL;
103748 #ifdef SQLITE_ENABLE_STAT3
103749 if( nEq==0 && pProbe->aSample ) pFirstTerm = pTerm;
103750 #endif
103751 used |= pTerm->prereqRight;
103754 /* Determine the value of rangeDiv */
103755 if( nEq<pProbe->nColumn && pProbe->bUnordered==0 ){
103756 int j = pProbe->aiColumn[nEq];
103757 if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pIdx) ){
103758 WhereTerm *pTop = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pIdx);
103759 WhereTerm *pBtm = findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pIdx);
103760 whereRangeScanEst(pParse, pProbe, nEq, pBtm, pTop, &rangeDiv);
103761 if( pTop ){
103762 nBound = 1;
103763 wsFlags |= WHERE_TOP_LIMIT;
103764 used |= pTop->prereqRight;
103765 testcase( pTop->pWC!=pWC );
103767 if( pBtm ){
103768 nBound++;
103769 wsFlags |= WHERE_BTM_LIMIT;
103770 used |= pBtm->prereqRight;
103771 testcase( pBtm->pWC!=pWC );
103773 wsFlags |= (WHERE_COLUMN_RANGE|WHERE_ROWID_RANGE);
103775 }else if( pProbe->onError!=OE_None ){
103776 testcase( wsFlags & WHERE_COLUMN_IN );
103777 testcase( wsFlags & WHERE_COLUMN_NULL );
103778 if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0 ){
103779 wsFlags |= WHERE_UNIQUE;
103783 /* If there is an ORDER BY clause and the index being considered will
103784 ** naturally scan rows in the required order, set the appropriate flags
103785 ** in wsFlags. Otherwise, if there is an ORDER BY clause but the index
103786 ** will scan rows in a different order, set the bSort variable. */
103787 if( isSortingIndex(
103788 pParse, pWC->pMaskSet, pProbe, iCur, pOrderBy, nEq, wsFlags, &rev)
103790 bSort = 0;
103791 wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_ORDERBY;
103792 wsFlags |= (rev ? WHERE_REVERSE : 0);
103795 /* If there is a DISTINCT qualifier and this index will scan rows in
103796 ** order of the DISTINCT expressions, clear bDist and set the appropriate
103797 ** flags in wsFlags. */
103798 if( isDistinctIndex(pParse, pWC, pProbe, iCur, pDistinct, nEq) ){
103799 bDist = 0;
103800 wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_DISTINCT;
103803 /* If currently calculating the cost of using an index (not the IPK
103804 ** index), determine if all required column data may be obtained without
103805 ** using the main table (i.e. if the index is a covering
103806 ** index for this query). If it is, set the WHERE_IDX_ONLY flag in
103807 ** wsFlags. Otherwise, set the bLookup variable to true. */
103808 if( pIdx && wsFlags ){
103809 Bitmask m = pSrc->colUsed;
103810 int j;
103811 for(j=0; j<pIdx->nColumn; j++){
103812 int x = pIdx->aiColumn[j];
103813 if( x<BMS-1 ){
103814 m &= ~(((Bitmask)1)<<x);
103817 if( m==0 ){
103818 wsFlags |= WHERE_IDX_ONLY;
103819 }else{
103820 bLookup = 1;
103825 ** Estimate the number of rows of output. For an "x IN (SELECT...)"
103826 ** constraint, do not let the estimate exceed half the rows in the table.
103828 nRow = (double)(aiRowEst[nEq] * nInMul);
103829 if( bInEst && nRow*2>aiRowEst[0] ){
103830 nRow = aiRowEst[0]/2;
103831 nInMul = (int)(nRow / aiRowEst[nEq]);
103834 #ifdef SQLITE_ENABLE_STAT3
103835 /* If the constraint is of the form x=VALUE or x IN (E1,E2,...)
103836 ** and we do not think that values of x are unique and if histogram
103837 ** data is available for column x, then it might be possible
103838 ** to get a better estimate on the number of rows based on
103839 ** VALUE and how common that value is according to the histogram.
103841 if( nRow>(double)1 && nEq==1 && pFirstTerm!=0 && aiRowEst[1]>1 ){
103842 assert( (pFirstTerm->eOperator & (WO_EQ|WO_ISNULL|WO_IN))!=0 );
103843 if( pFirstTerm->eOperator & (WO_EQ|WO_ISNULL) ){
103844 testcase( pFirstTerm->eOperator==WO_EQ );
103845 testcase( pFirstTerm->eOperator==WO_ISNULL );
103846 whereEqualScanEst(pParse, pProbe, pFirstTerm->pExpr->pRight, &nRow);
103847 }else if( bInEst==0 ){
103848 assert( pFirstTerm->eOperator==WO_IN );
103849 whereInScanEst(pParse, pProbe, pFirstTerm->pExpr->x.pList, &nRow);
103852 #endif /* SQLITE_ENABLE_STAT3 */
103854 /* Adjust the number of output rows and downward to reflect rows
103855 ** that are excluded by range constraints.
103857 nRow = nRow/rangeDiv;
103858 if( nRow<1 ) nRow = 1;
103860 /* Experiments run on real SQLite databases show that the time needed
103861 ** to do a binary search to locate a row in a table or index is roughly
103862 ** log10(N) times the time to move from one row to the next row within
103863 ** a table or index. The actual times can vary, with the size of
103864 ** records being an important factor. Both moves and searches are
103865 ** slower with larger records, presumably because fewer records fit
103866 ** on one page and hence more pages have to be fetched.
103868 ** The ANALYZE command and the sqlite_stat1 and sqlite_stat3 tables do
103869 ** not give us data on the relative sizes of table and index records.
103870 ** So this computation assumes table records are about twice as big
103871 ** as index records
103873 if( (wsFlags & WHERE_NOT_FULLSCAN)==0 ){
103874 /* The cost of a full table scan is a number of move operations equal
103875 ** to the number of rows in the table.
103877 ** We add an additional 4x penalty to full table scans. This causes
103878 ** the cost function to err on the side of choosing an index over
103879 ** choosing a full scan. This 4x full-scan penalty is an arguable
103880 ** decision and one which we expect to revisit in the future. But
103881 ** it seems to be working well enough at the moment.
103883 cost = aiRowEst[0]*4;
103884 }else{
103885 log10N = estLog(aiRowEst[0]);
103886 cost = nRow;
103887 if( pIdx ){
103888 if( bLookup ){
103889 /* For an index lookup followed by a table lookup:
103890 ** nInMul index searches to find the start of each index range
103891 ** + nRow steps through the index
103892 ** + nRow table searches to lookup the table entry using the rowid
103894 cost += (nInMul + nRow)*log10N;
103895 }else{
103896 /* For a covering index:
103897 ** nInMul index searches to find the initial entry
103898 ** + nRow steps through the index
103900 cost += nInMul*log10N;
103902 }else{
103903 /* For a rowid primary key lookup:
103904 ** nInMult table searches to find the initial entry for each range
103905 ** + nRow steps through the table
103907 cost += nInMul*log10N;
103911 /* Add in the estimated cost of sorting the result. Actual experimental
103912 ** measurements of sorting performance in SQLite show that sorting time
103913 ** adds C*N*log10(N) to the cost, where N is the number of rows to be
103914 ** sorted and C is a factor between 1.95 and 4.3. We will split the
103915 ** difference and select C of 3.0.
103917 if( bSort ){
103918 cost += nRow*estLog(nRow)*3;
103920 if( bDist ){
103921 cost += nRow*estLog(nRow)*3;
103924 /**** Cost of using this index has now been computed ****/
103926 /* If there are additional constraints on this table that cannot
103927 ** be used with the current index, but which might lower the number
103928 ** of output rows, adjust the nRow value accordingly. This only
103929 ** matters if the current index is the least costly, so do not bother
103930 ** with this step if we already know this index will not be chosen.
103931 ** Also, never reduce the output row count below 2 using this step.
103933 ** It is critical that the notValid mask be used here instead of
103934 ** the notReady mask. When computing an "optimal" index, the notReady
103935 ** mask will only have one bit set - the bit for the current table.
103936 ** The notValid mask, on the other hand, always has all bits set for
103937 ** tables that are not in outer loops. If notReady is used here instead
103938 ** of notValid, then a optimal index that depends on inner joins loops
103939 ** might be selected even when there exists an optimal index that has
103940 ** no such dependency.
103942 if( nRow>2 && cost<=pCost->rCost ){
103943 int k; /* Loop counter */
103944 int nSkipEq = nEq; /* Number of == constraints to skip */
103945 int nSkipRange = nBound; /* Number of < constraints to skip */
103946 Bitmask thisTab; /* Bitmap for pSrc */
103948 thisTab = getMask(pWC->pMaskSet, iCur);
103949 for(pTerm=pWC->a, k=pWC->nTerm; nRow>2 && k; k--, pTerm++){
103950 if( pTerm->wtFlags & TERM_VIRTUAL ) continue;
103951 if( (pTerm->prereqAll & notValid)!=thisTab ) continue;
103952 if( pTerm->eOperator & (WO_EQ|WO_IN|WO_ISNULL) ){
103953 if( nSkipEq ){
103954 /* Ignore the first nEq equality matches since the index
103955 ** has already accounted for these */
103956 nSkipEq--;
103957 }else{
103958 /* Assume each additional equality match reduces the result
103959 ** set size by a factor of 10 */
103960 nRow /= 10;
103962 }else if( pTerm->eOperator & (WO_LT|WO_LE|WO_GT|WO_GE) ){
103963 if( nSkipRange ){
103964 /* Ignore the first nSkipRange range constraints since the index
103965 ** has already accounted for these */
103966 nSkipRange--;
103967 }else{
103968 /* Assume each additional range constraint reduces the result
103969 ** set size by a factor of 3. Indexed range constraints reduce
103970 ** the search space by a larger factor: 4. We make indexed range
103971 ** more selective intentionally because of the subjective
103972 ** observation that indexed range constraints really are more
103973 ** selective in practice, on average. */
103974 nRow /= 3;
103976 }else if( pTerm->eOperator!=WO_NOOP ){
103977 /* Any other expression lowers the output row count by half */
103978 nRow /= 2;
103981 if( nRow<2 ) nRow = 2;
103985 WHERETRACE((
103986 "%s(%s): nEq=%d nInMul=%d rangeDiv=%d bSort=%d bLookup=%d wsFlags=0x%x\n"
103987 " notReady=0x%llx log10N=%.1f nRow=%.1f cost=%.1f used=0x%llx\n",
103988 pSrc->pTab->zName, (pIdx ? pIdx->zName : "ipk"),
103989 nEq, nInMul, (int)rangeDiv, bSort, bLookup, wsFlags,
103990 notReady, log10N, nRow, cost, used
103993 /* If this index is the best we have seen so far, then record this
103994 ** index and its cost in the pCost structure.
103996 if( (!pIdx || wsFlags)
103997 && (cost<pCost->rCost || (cost<=pCost->rCost && nRow<pCost->plan.nRow))
103999 pCost->rCost = cost;
104000 pCost->used = used;
104001 pCost->plan.nRow = nRow;
104002 pCost->plan.wsFlags = (wsFlags&wsFlagMask);
104003 pCost->plan.nEq = nEq;
104004 pCost->plan.u.pIdx = pIdx;
104007 /* If there was an INDEXED BY clause, then only that one index is
104008 ** considered. */
104009 if( pSrc->pIndex ) break;
104011 /* Reset masks for the next index in the loop */
104012 wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
104013 eqTermMask = idxEqTermMask;
104016 /* If there is no ORDER BY clause and the SQLITE_ReverseOrder flag
104017 ** is set, then reverse the order that the index will be scanned
104018 ** in. This is used for application testing, to help find cases
104019 ** where application behaviour depends on the (undefined) order that
104020 ** SQLite outputs rows in in the absence of an ORDER BY clause. */
104021 if( !pOrderBy && pParse->db->flags & SQLITE_ReverseOrder ){
104022 pCost->plan.wsFlags |= WHERE_REVERSE;
104025 assert( pOrderBy || (pCost->plan.wsFlags&WHERE_ORDERBY)==0 );
104026 assert( pCost->plan.u.pIdx==0 || (pCost->plan.wsFlags&WHERE_ROWID_EQ)==0 );
104027 assert( pSrc->pIndex==0
104028 || pCost->plan.u.pIdx==0
104029 || pCost->plan.u.pIdx==pSrc->pIndex
104032 WHERETRACE(("best index is: %s\n",
104033 ((pCost->plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ? "none" :
104034 pCost->plan.u.pIdx ? pCost->plan.u.pIdx->zName : "ipk")
104037 bestOrClauseIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost);
104038 bestAutomaticIndex(pParse, pWC, pSrc, notReady, pCost);
104039 pCost->plan.wsFlags |= eqTermMask;
104043 ** Find the query plan for accessing table pSrc->pTab. Write the
104044 ** best query plan and its cost into the WhereCost object supplied
104045 ** as the last parameter. This function may calculate the cost of
104046 ** both real and virtual table scans.
104048 static void bestIndex(
104049 Parse *pParse, /* The parsing context */
104050 WhereClause *pWC, /* The WHERE clause */
104051 struct SrcList_item *pSrc, /* The FROM clause term to search */
104052 Bitmask notReady, /* Mask of cursors not available for indexing */
104053 Bitmask notValid, /* Cursors not available for any purpose */
104054 ExprList *pOrderBy, /* The ORDER BY clause */
104055 WhereCost *pCost /* Lowest cost query plan */
104057 #ifndef SQLITE_OMIT_VIRTUALTABLE
104058 if( IsVirtual(pSrc->pTab) ){
104059 sqlite3_index_info *p = 0;
104060 bestVirtualIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost,&p);
104061 if( p->needToFreeIdxStr ){
104062 sqlite3_free(p->idxStr);
104064 sqlite3DbFree(pParse->db, p);
104065 }else
104066 #endif
104068 bestBtreeIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, 0, pCost);
104073 ** Disable a term in the WHERE clause. Except, do not disable the term
104074 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
104075 ** or USING clause of that join.
104077 ** Consider the term t2.z='ok' in the following queries:
104079 ** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
104080 ** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
104081 ** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
104083 ** The t2.z='ok' is disabled in the in (2) because it originates
104084 ** in the ON clause. The term is disabled in (3) because it is not part
104085 ** of a LEFT OUTER JOIN. In (1), the term is not disabled.
104087 ** IMPLEMENTATION-OF: R-24597-58655 No tests are done for terms that are
104088 ** completely satisfied by indices.
104090 ** Disabling a term causes that term to not be tested in the inner loop
104091 ** of the join. Disabling is an optimization. When terms are satisfied
104092 ** by indices, we disable them to prevent redundant tests in the inner
104093 ** loop. We would get the correct results if nothing were ever disabled,
104094 ** but joins might run a little slower. The trick is to disable as much
104095 ** as we can without disabling too much. If we disabled in (1), we'd get
104096 ** the wrong answer. See ticket #813.
104098 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
104099 if( pTerm
104100 && (pTerm->wtFlags & TERM_CODED)==0
104101 && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
104103 pTerm->wtFlags |= TERM_CODED;
104104 if( pTerm->iParent>=0 ){
104105 WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
104106 if( (--pOther->nChild)==0 ){
104107 disableTerm(pLevel, pOther);
104114 ** Code an OP_Affinity opcode to apply the column affinity string zAff
104115 ** to the n registers starting at base.
104117 ** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
104118 ** beginning and end of zAff are ignored. If all entries in zAff are
104119 ** SQLITE_AFF_NONE, then no code gets generated.
104121 ** This routine makes its own copy of zAff so that the caller is free
104122 ** to modify zAff after this routine returns.
104124 static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
104125 Vdbe *v = pParse->pVdbe;
104126 if( zAff==0 ){
104127 assert( pParse->db->mallocFailed );
104128 return;
104130 assert( v!=0 );
104132 /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
104133 ** and end of the affinity string.
104135 while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
104137 base++;
104138 zAff++;
104140 while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
104144 /* Code the OP_Affinity opcode if there is anything left to do. */
104145 if( n>0 ){
104146 sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
104147 sqlite3VdbeChangeP4(v, -1, zAff, n);
104148 sqlite3ExprCacheAffinityChange(pParse, base, n);
104154 ** Generate code for a single equality term of the WHERE clause. An equality
104155 ** term can be either X=expr or X IN (...). pTerm is the term to be
104156 ** coded.
104158 ** The current value for the constraint is left in register iReg.
104160 ** For a constraint of the form X=expr, the expression is evaluated and its
104161 ** result is left on the stack. For constraints of the form X IN (...)
104162 ** this routine sets up a loop that will iterate over all values of X.
104164 static int codeEqualityTerm(
104165 Parse *pParse, /* The parsing context */
104166 WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
104167 WhereLevel *pLevel, /* When level of the FROM clause we are working on */
104168 int iTarget /* Attempt to leave results in this register */
104170 Expr *pX = pTerm->pExpr;
104171 Vdbe *v = pParse->pVdbe;
104172 int iReg; /* Register holding results */
104174 assert( iTarget>0 );
104175 if( pX->op==TK_EQ ){
104176 iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
104177 }else if( pX->op==TK_ISNULL ){
104178 iReg = iTarget;
104179 sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
104180 #ifndef SQLITE_OMIT_SUBQUERY
104181 }else{
104182 int eType;
104183 int iTab;
104184 struct InLoop *pIn;
104186 assert( pX->op==TK_IN );
104187 iReg = iTarget;
104188 eType = sqlite3FindInIndex(pParse, pX, 0);
104189 iTab = pX->iTable;
104190 sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
104191 assert( pLevel->plan.wsFlags & WHERE_IN_ABLE );
104192 if( pLevel->u.in.nIn==0 ){
104193 pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
104195 pLevel->u.in.nIn++;
104196 pLevel->u.in.aInLoop =
104197 sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
104198 sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
104199 pIn = pLevel->u.in.aInLoop;
104200 if( pIn ){
104201 pIn += pLevel->u.in.nIn - 1;
104202 pIn->iCur = iTab;
104203 if( eType==IN_INDEX_ROWID ){
104204 pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
104205 }else{
104206 pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
104208 sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
104209 }else{
104210 pLevel->u.in.nIn = 0;
104212 #endif
104214 disableTerm(pLevel, pTerm);
104215 return iReg;
104219 ** Generate code that will evaluate all == and IN constraints for an
104220 ** index.
104222 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
104223 ** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
104224 ** The index has as many as three equality constraints, but in this
104225 ** example, the third "c" value is an inequality. So only two
104226 ** constraints are coded. This routine will generate code to evaluate
104227 ** a==5 and b IN (1,2,3). The current values for a and b will be stored
104228 ** in consecutive registers and the index of the first register is returned.
104230 ** In the example above nEq==2. But this subroutine works for any value
104231 ** of nEq including 0. If nEq==0, this routine is nearly a no-op.
104232 ** The only thing it does is allocate the pLevel->iMem memory cell and
104233 ** compute the affinity string.
104235 ** This routine always allocates at least one memory cell and returns
104236 ** the index of that memory cell. The code that
104237 ** calls this routine will use that memory cell to store the termination
104238 ** key value of the loop. If one or more IN operators appear, then
104239 ** this routine allocates an additional nEq memory cells for internal
104240 ** use.
104242 ** Before returning, *pzAff is set to point to a buffer containing a
104243 ** copy of the column affinity string of the index allocated using
104244 ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
104245 ** with equality constraints that use NONE affinity are set to
104246 ** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
104248 ** CREATE TABLE t1(a TEXT PRIMARY KEY, b);
104249 ** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
104251 ** In the example above, the index on t1(a) has TEXT affinity. But since
104252 ** the right hand side of the equality constraint (t2.b) has NONE affinity,
104253 ** no conversion should be attempted before using a t2.b value as part of
104254 ** a key to search the index. Hence the first byte in the returned affinity
104255 ** string in this example would be set to SQLITE_AFF_NONE.
104257 static int codeAllEqualityTerms(
104258 Parse *pParse, /* Parsing context */
104259 WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
104260 WhereClause *pWC, /* The WHERE clause */
104261 Bitmask notReady, /* Which parts of FROM have not yet been coded */
104262 int nExtraReg, /* Number of extra registers to allocate */
104263 char **pzAff /* OUT: Set to point to affinity string */
104265 int nEq = pLevel->plan.nEq; /* The number of == or IN constraints to code */
104266 Vdbe *v = pParse->pVdbe; /* The vm under construction */
104267 Index *pIdx; /* The index being used for this loop */
104268 int iCur = pLevel->iTabCur; /* The cursor of the table */
104269 WhereTerm *pTerm; /* A single constraint term */
104270 int j; /* Loop counter */
104271 int regBase; /* Base register */
104272 int nReg; /* Number of registers to allocate */
104273 char *zAff; /* Affinity string to return */
104275 /* This module is only called on query plans that use an index. */
104276 assert( pLevel->plan.wsFlags & WHERE_INDEXED );
104277 pIdx = pLevel->plan.u.pIdx;
104279 /* Figure out how many memory cells we will need then allocate them.
104281 regBase = pParse->nMem + 1;
104282 nReg = pLevel->plan.nEq + nExtraReg;
104283 pParse->nMem += nReg;
104285 zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
104286 if( !zAff ){
104287 pParse->db->mallocFailed = 1;
104290 /* Evaluate the equality constraints
104292 assert( pIdx->nColumn>=nEq );
104293 for(j=0; j<nEq; j++){
104294 int r1;
104295 int k = pIdx->aiColumn[j];
104296 pTerm = findTerm(pWC, iCur, k, notReady, pLevel->plan.wsFlags, pIdx);
104297 if( NEVER(pTerm==0) ) break;
104298 /* The following true for indices with redundant columns.
104299 ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
104300 testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
104301 testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
104302 r1 = codeEqualityTerm(pParse, pTerm, pLevel, regBase+j);
104303 if( r1!=regBase+j ){
104304 if( nReg==1 ){
104305 sqlite3ReleaseTempReg(pParse, regBase);
104306 regBase = r1;
104307 }else{
104308 sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
104311 testcase( pTerm->eOperator & WO_ISNULL );
104312 testcase( pTerm->eOperator & WO_IN );
104313 if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
104314 Expr *pRight = pTerm->pExpr->pRight;
104315 sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
104316 if( zAff ){
104317 if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
104318 zAff[j] = SQLITE_AFF_NONE;
104320 if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
104321 zAff[j] = SQLITE_AFF_NONE;
104326 *pzAff = zAff;
104327 return regBase;
104330 #ifndef SQLITE_OMIT_EXPLAIN
104332 ** This routine is a helper for explainIndexRange() below
104334 ** pStr holds the text of an expression that we are building up one term
104335 ** at a time. This routine adds a new term to the end of the expression.
104336 ** Terms are separated by AND so add the "AND" text for second and subsequent
104337 ** terms only.
104339 static void explainAppendTerm(
104340 StrAccum *pStr, /* The text expression being built */
104341 int iTerm, /* Index of this term. First is zero */
104342 const char *zColumn, /* Name of the column */
104343 const char *zOp /* Name of the operator */
104345 if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
104346 sqlite3StrAccumAppend(pStr, zColumn, -1);
104347 sqlite3StrAccumAppend(pStr, zOp, 1);
104348 sqlite3StrAccumAppend(pStr, "?", 1);
104352 ** Argument pLevel describes a strategy for scanning table pTab. This
104353 ** function returns a pointer to a string buffer containing a description
104354 ** of the subset of table rows scanned by the strategy in the form of an
104355 ** SQL expression. Or, if all rows are scanned, NULL is returned.
104357 ** For example, if the query:
104359 ** SELECT * FROM t1 WHERE a=1 AND b>2;
104361 ** is run and there is an index on (a, b), then this function returns a
104362 ** string similar to:
104364 ** "a=? AND b>?"
104366 ** The returned pointer points to memory obtained from sqlite3DbMalloc().
104367 ** It is the responsibility of the caller to free the buffer when it is
104368 ** no longer required.
104370 static char *explainIndexRange(sqlite3 *db, WhereLevel *pLevel, Table *pTab){
104371 WherePlan *pPlan = &pLevel->plan;
104372 Index *pIndex = pPlan->u.pIdx;
104373 int nEq = pPlan->nEq;
104374 int i, j;
104375 Column *aCol = pTab->aCol;
104376 int *aiColumn = pIndex->aiColumn;
104377 StrAccum txt;
104379 if( nEq==0 && (pPlan->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){
104380 return 0;
104382 sqlite3StrAccumInit(&txt, 0, 0, SQLITE_MAX_LENGTH);
104383 txt.db = db;
104384 sqlite3StrAccumAppend(&txt, " (", 2);
104385 for(i=0; i<nEq; i++){
104386 explainAppendTerm(&txt, i, aCol[aiColumn[i]].zName, "=");
104389 j = i;
104390 if( pPlan->wsFlags&WHERE_BTM_LIMIT ){
104391 explainAppendTerm(&txt, i++, aCol[aiColumn[j]].zName, ">");
104393 if( pPlan->wsFlags&WHERE_TOP_LIMIT ){
104394 explainAppendTerm(&txt, i, aCol[aiColumn[j]].zName, "<");
104396 sqlite3StrAccumAppend(&txt, ")", 1);
104397 return sqlite3StrAccumFinish(&txt);
104401 ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
104402 ** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single
104403 ** record is added to the output to describe the table scan strategy in
104404 ** pLevel.
104406 static void explainOneScan(
104407 Parse *pParse, /* Parse context */
104408 SrcList *pTabList, /* Table list this loop refers to */
104409 WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
104410 int iLevel, /* Value for "level" column of output */
104411 int iFrom, /* Value for "from" column of output */
104412 u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
104414 if( pParse->explain==2 ){
104415 u32 flags = pLevel->plan.wsFlags;
104416 struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
104417 Vdbe *v = pParse->pVdbe; /* VM being constructed */
104418 sqlite3 *db = pParse->db; /* Database handle */
104419 char *zMsg; /* Text to add to EQP output */
104420 sqlite3_int64 nRow; /* Expected number of rows visited by scan */
104421 int iId = pParse->iSelectId; /* Select id (left-most output column) */
104422 int isSearch; /* True for a SEARCH. False for SCAN. */
104424 if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
104426 isSearch = (pLevel->plan.nEq>0)
104427 || (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
104428 || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
104430 zMsg = sqlite3MPrintf(db, "%s", isSearch?"SEARCH":"SCAN");
104431 if( pItem->pSelect ){
104432 zMsg = sqlite3MAppendf(db, zMsg, "%s SUBQUERY %d", zMsg,pItem->iSelectId);
104433 }else{
104434 zMsg = sqlite3MAppendf(db, zMsg, "%s TABLE %s", zMsg, pItem->zName);
104437 if( pItem->zAlias ){
104438 zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
104440 if( (flags & WHERE_INDEXED)!=0 ){
104441 char *zWhere = explainIndexRange(db, pLevel, pItem->pTab);
104442 zMsg = sqlite3MAppendf(db, zMsg, "%s USING %s%sINDEX%s%s%s", zMsg,
104443 ((flags & WHERE_TEMP_INDEX)?"AUTOMATIC ":""),
104444 ((flags & WHERE_IDX_ONLY)?"COVERING ":""),
104445 ((flags & WHERE_TEMP_INDEX)?"":" "),
104446 ((flags & WHERE_TEMP_INDEX)?"": pLevel->plan.u.pIdx->zName),
104447 zWhere
104449 sqlite3DbFree(db, zWhere);
104450 }else if( flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
104451 zMsg = sqlite3MAppendf(db, zMsg, "%s USING INTEGER PRIMARY KEY", zMsg);
104453 if( flags&WHERE_ROWID_EQ ){
104454 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid=?)", zMsg);
104455 }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
104456 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>? AND rowid<?)", zMsg);
104457 }else if( flags&WHERE_BTM_LIMIT ){
104458 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>?)", zMsg);
104459 }else if( flags&WHERE_TOP_LIMIT ){
104460 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid<?)", zMsg);
104463 #ifndef SQLITE_OMIT_VIRTUALTABLE
104464 else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
104465 sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
104466 zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
104467 pVtabIdx->idxNum, pVtabIdx->idxStr);
104469 #endif
104470 if( wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX) ){
104471 testcase( wctrlFlags & WHERE_ORDERBY_MIN );
104472 nRow = 1;
104473 }else{
104474 nRow = (sqlite3_int64)pLevel->plan.nRow;
104476 zMsg = sqlite3MAppendf(db, zMsg, "%s (~%lld rows)", zMsg, nRow);
104477 sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
104480 #else
104481 # define explainOneScan(u,v,w,x,y,z)
104482 #endif /* SQLITE_OMIT_EXPLAIN */
104486 ** Generate code for the start of the iLevel-th loop in the WHERE clause
104487 ** implementation described by pWInfo.
104489 static Bitmask codeOneLoopStart(
104490 WhereInfo *pWInfo, /* Complete information about the WHERE clause */
104491 int iLevel, /* Which level of pWInfo->a[] should be coded */
104492 u16 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */
104493 Bitmask notReady, /* Which tables are currently available */
104494 Expr *pWhere /* Complete WHERE clause */
104496 int j, k; /* Loop counters */
104497 int iCur; /* The VDBE cursor for the table */
104498 int addrNxt; /* Where to jump to continue with the next IN case */
104499 int omitTable; /* True if we use the index only */
104500 int bRev; /* True if we need to scan in reverse order */
104501 WhereLevel *pLevel; /* The where level to be coded */
104502 WhereClause *pWC; /* Decomposition of the entire WHERE clause */
104503 WhereTerm *pTerm; /* A WHERE clause term */
104504 Parse *pParse; /* Parsing context */
104505 Vdbe *v; /* The prepared stmt under constructions */
104506 struct SrcList_item *pTabItem; /* FROM clause term being coded */
104507 int addrBrk; /* Jump here to break out of the loop */
104508 int addrCont; /* Jump here to continue with next cycle */
104509 int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
104510 int iReleaseReg = 0; /* Temp register to free before returning */
104512 pParse = pWInfo->pParse;
104513 v = pParse->pVdbe;
104514 pWC = pWInfo->pWC;
104515 pLevel = &pWInfo->a[iLevel];
104516 pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
104517 iCur = pTabItem->iCursor;
104518 bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
104519 omitTable = (pLevel->plan.wsFlags & WHERE_IDX_ONLY)!=0
104520 && (wctrlFlags & WHERE_FORCE_TABLE)==0;
104522 /* Create labels for the "break" and "continue" instructions
104523 ** for the current loop. Jump to addrBrk to break out of a loop.
104524 ** Jump to cont to go immediately to the next iteration of the
104525 ** loop.
104527 ** When there is an IN operator, we also have a "addrNxt" label that
104528 ** means to continue with the next IN value combination. When
104529 ** there are no IN operators in the constraints, the "addrNxt" label
104530 ** is the same as "addrBrk".
104532 addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
104533 addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
104535 /* If this is the right table of a LEFT OUTER JOIN, allocate and
104536 ** initialize a memory cell that records if this table matches any
104537 ** row of the left table of the join.
104539 if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
104540 pLevel->iLeftJoin = ++pParse->nMem;
104541 sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
104542 VdbeComment((v, "init LEFT JOIN no-match flag"));
104545 #ifndef SQLITE_OMIT_VIRTUALTABLE
104546 if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
104547 /* Case 0: The table is a virtual-table. Use the VFilter and VNext
104548 ** to access the data.
104550 int iReg; /* P3 Value for OP_VFilter */
104551 sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
104552 int nConstraint = pVtabIdx->nConstraint;
104553 struct sqlite3_index_constraint_usage *aUsage =
104554 pVtabIdx->aConstraintUsage;
104555 const struct sqlite3_index_constraint *aConstraint =
104556 pVtabIdx->aConstraint;
104558 sqlite3ExprCachePush(pParse);
104559 iReg = sqlite3GetTempRange(pParse, nConstraint+2);
104560 for(j=1; j<=nConstraint; j++){
104561 for(k=0; k<nConstraint; k++){
104562 if( aUsage[k].argvIndex==j ){
104563 int iTerm = aConstraint[k].iTermOffset;
104564 sqlite3ExprCode(pParse, pWC->a[iTerm].pExpr->pRight, iReg+j+1);
104565 break;
104568 if( k==nConstraint ) break;
104570 sqlite3VdbeAddOp2(v, OP_Integer, pVtabIdx->idxNum, iReg);
104571 sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
104572 sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrBrk, iReg, pVtabIdx->idxStr,
104573 pVtabIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
104574 pVtabIdx->needToFreeIdxStr = 0;
104575 for(j=0; j<nConstraint; j++){
104576 if( aUsage[j].omit ){
104577 int iTerm = aConstraint[j].iTermOffset;
104578 disableTerm(pLevel, &pWC->a[iTerm]);
104581 pLevel->op = OP_VNext;
104582 pLevel->p1 = iCur;
104583 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
104584 sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
104585 sqlite3ExprCachePop(pParse, 1);
104586 }else
104587 #endif /* SQLITE_OMIT_VIRTUALTABLE */
104589 if( pLevel->plan.wsFlags & WHERE_ROWID_EQ ){
104590 /* Case 1: We can directly reference a single row using an
104591 ** equality comparison against the ROWID field. Or
104592 ** we reference multiple rows using a "rowid IN (...)"
104593 ** construct.
104595 iReleaseReg = sqlite3GetTempReg(pParse);
104596 pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
104597 assert( pTerm!=0 );
104598 assert( pTerm->pExpr!=0 );
104599 assert( pTerm->leftCursor==iCur );
104600 assert( omitTable==0 );
104601 testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
104602 iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, iReleaseReg);
104603 addrNxt = pLevel->addrNxt;
104604 sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
104605 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
104606 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
104607 VdbeComment((v, "pk"));
104608 pLevel->op = OP_Noop;
104609 }else if( pLevel->plan.wsFlags & WHERE_ROWID_RANGE ){
104610 /* Case 2: We have an inequality comparison against the ROWID field.
104612 int testOp = OP_Noop;
104613 int start;
104614 int memEndValue = 0;
104615 WhereTerm *pStart, *pEnd;
104617 assert( omitTable==0 );
104618 pStart = findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0);
104619 pEnd = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0);
104620 if( bRev ){
104621 pTerm = pStart;
104622 pStart = pEnd;
104623 pEnd = pTerm;
104625 if( pStart ){
104626 Expr *pX; /* The expression that defines the start bound */
104627 int r1, rTemp; /* Registers for holding the start boundary */
104629 /* The following constant maps TK_xx codes into corresponding
104630 ** seek opcodes. It depends on a particular ordering of TK_xx
104632 const u8 aMoveOp[] = {
104633 /* TK_GT */ OP_SeekGt,
104634 /* TK_LE */ OP_SeekLe,
104635 /* TK_LT */ OP_SeekLt,
104636 /* TK_GE */ OP_SeekGe
104638 assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */
104639 assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */
104640 assert( TK_GE==TK_GT+3 ); /* ... is correcct. */
104642 testcase( pStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
104643 pX = pStart->pExpr;
104644 assert( pX!=0 );
104645 assert( pStart->leftCursor==iCur );
104646 r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
104647 sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
104648 VdbeComment((v, "pk"));
104649 sqlite3ExprCacheAffinityChange(pParse, r1, 1);
104650 sqlite3ReleaseTempReg(pParse, rTemp);
104651 disableTerm(pLevel, pStart);
104652 }else{
104653 sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
104655 if( pEnd ){
104656 Expr *pX;
104657 pX = pEnd->pExpr;
104658 assert( pX!=0 );
104659 assert( pEnd->leftCursor==iCur );
104660 testcase( pEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
104661 memEndValue = ++pParse->nMem;
104662 sqlite3ExprCode(pParse, pX->pRight, memEndValue);
104663 if( pX->op==TK_LT || pX->op==TK_GT ){
104664 testOp = bRev ? OP_Le : OP_Ge;
104665 }else{
104666 testOp = bRev ? OP_Lt : OP_Gt;
104668 disableTerm(pLevel, pEnd);
104670 start = sqlite3VdbeCurrentAddr(v);
104671 pLevel->op = bRev ? OP_Prev : OP_Next;
104672 pLevel->p1 = iCur;
104673 pLevel->p2 = start;
104674 if( pStart==0 && pEnd==0 ){
104675 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
104676 }else{
104677 assert( pLevel->p5==0 );
104679 if( testOp!=OP_Noop ){
104680 iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
104681 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
104682 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
104683 sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
104684 sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
104686 }else if( pLevel->plan.wsFlags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
104687 /* Case 3: A scan using an index.
104689 ** The WHERE clause may contain zero or more equality
104690 ** terms ("==" or "IN" operators) that refer to the N
104691 ** left-most columns of the index. It may also contain
104692 ** inequality constraints (>, <, >= or <=) on the indexed
104693 ** column that immediately follows the N equalities. Only
104694 ** the right-most column can be an inequality - the rest must
104695 ** use the "==" and "IN" operators. For example, if the
104696 ** index is on (x,y,z), then the following clauses are all
104697 ** optimized:
104699 ** x=5
104700 ** x=5 AND y=10
104701 ** x=5 AND y<10
104702 ** x=5 AND y>5 AND y<10
104703 ** x=5 AND y=5 AND z<=10
104705 ** The z<10 term of the following cannot be used, only
104706 ** the x=5 term:
104708 ** x=5 AND z<10
104710 ** N may be zero if there are inequality constraints.
104711 ** If there are no inequality constraints, then N is at
104712 ** least one.
104714 ** This case is also used when there are no WHERE clause
104715 ** constraints but an index is selected anyway, in order
104716 ** to force the output order to conform to an ORDER BY.
104718 static const u8 aStartOp[] = {
104721 OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
104722 OP_Last, /* 3: (!start_constraints && startEq && bRev) */
104723 OP_SeekGt, /* 4: (start_constraints && !startEq && !bRev) */
104724 OP_SeekLt, /* 5: (start_constraints && !startEq && bRev) */
104725 OP_SeekGe, /* 6: (start_constraints && startEq && !bRev) */
104726 OP_SeekLe /* 7: (start_constraints && startEq && bRev) */
104728 static const u8 aEndOp[] = {
104729 OP_Noop, /* 0: (!end_constraints) */
104730 OP_IdxGE, /* 1: (end_constraints && !bRev) */
104731 OP_IdxLT /* 2: (end_constraints && bRev) */
104733 int nEq = pLevel->plan.nEq; /* Number of == or IN terms */
104734 int isMinQuery = 0; /* If this is an optimized SELECT min(x).. */
104735 int regBase; /* Base register holding constraint values */
104736 int r1; /* Temp register */
104737 WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
104738 WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
104739 int startEq; /* True if range start uses ==, >= or <= */
104740 int endEq; /* True if range end uses ==, >= or <= */
104741 int start_constraints; /* Start of range is constrained */
104742 int nConstraint; /* Number of constraint terms */
104743 Index *pIdx; /* The index we will be using */
104744 int iIdxCur; /* The VDBE cursor for the index */
104745 int nExtraReg = 0; /* Number of extra registers needed */
104746 int op; /* Instruction opcode */
104747 char *zStartAff; /* Affinity for start of range constraint */
104748 char *zEndAff; /* Affinity for end of range constraint */
104750 pIdx = pLevel->plan.u.pIdx;
104751 iIdxCur = pLevel->iIdxCur;
104752 k = pIdx->aiColumn[nEq]; /* Column for inequality constraints */
104754 /* If this loop satisfies a sort order (pOrderBy) request that
104755 ** was passed to this function to implement a "SELECT min(x) ..."
104756 ** query, then the caller will only allow the loop to run for
104757 ** a single iteration. This means that the first row returned
104758 ** should not have a NULL value stored in 'x'. If column 'x' is
104759 ** the first one after the nEq equality constraints in the index,
104760 ** this requires some special handling.
104762 if( (wctrlFlags&WHERE_ORDERBY_MIN)!=0
104763 && (pLevel->plan.wsFlags&WHERE_ORDERBY)
104764 && (pIdx->nColumn>nEq)
104766 /* assert( pOrderBy->nExpr==1 ); */
104767 /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
104768 isMinQuery = 1;
104769 nExtraReg = 1;
104772 /* Find any inequality constraint terms for the start and end
104773 ** of the range.
104775 if( pLevel->plan.wsFlags & WHERE_TOP_LIMIT ){
104776 pRangeEnd = findTerm(pWC, iCur, k, notReady, (WO_LT|WO_LE), pIdx);
104777 nExtraReg = 1;
104779 if( pLevel->plan.wsFlags & WHERE_BTM_LIMIT ){
104780 pRangeStart = findTerm(pWC, iCur, k, notReady, (WO_GT|WO_GE), pIdx);
104781 nExtraReg = 1;
104784 /* Generate code to evaluate all constraint terms using == or IN
104785 ** and store the values of those terms in an array of registers
104786 ** starting at regBase.
104788 regBase = codeAllEqualityTerms(
104789 pParse, pLevel, pWC, notReady, nExtraReg, &zStartAff
104791 zEndAff = sqlite3DbStrDup(pParse->db, zStartAff);
104792 addrNxt = pLevel->addrNxt;
104794 /* If we are doing a reverse order scan on an ascending index, or
104795 ** a forward order scan on a descending index, interchange the
104796 ** start and end terms (pRangeStart and pRangeEnd).
104798 if( nEq<pIdx->nColumn && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC) ){
104799 SWAP(WhereTerm *, pRangeEnd, pRangeStart);
104802 testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
104803 testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
104804 testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
104805 testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
104806 startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
104807 endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
104808 start_constraints = pRangeStart || nEq>0;
104810 /* Seek the index cursor to the start of the range. */
104811 nConstraint = nEq;
104812 if( pRangeStart ){
104813 Expr *pRight = pRangeStart->pExpr->pRight;
104814 sqlite3ExprCode(pParse, pRight, regBase+nEq);
104815 if( (pRangeStart->wtFlags & TERM_VNULL)==0 ){
104816 sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
104818 if( zStartAff ){
104819 if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
104820 /* Since the comparison is to be performed with no conversions
104821 ** applied to the operands, set the affinity to apply to pRight to
104822 ** SQLITE_AFF_NONE. */
104823 zStartAff[nEq] = SQLITE_AFF_NONE;
104825 if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
104826 zStartAff[nEq] = SQLITE_AFF_NONE;
104829 nConstraint++;
104830 testcase( pRangeStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
104831 }else if( isMinQuery ){
104832 sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
104833 nConstraint++;
104834 startEq = 0;
104835 start_constraints = 1;
104837 codeApplyAffinity(pParse, regBase, nConstraint, zStartAff);
104838 op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
104839 assert( op!=0 );
104840 testcase( op==OP_Rewind );
104841 testcase( op==OP_Last );
104842 testcase( op==OP_SeekGt );
104843 testcase( op==OP_SeekGe );
104844 testcase( op==OP_SeekLe );
104845 testcase( op==OP_SeekLt );
104846 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
104848 /* Load the value for the inequality constraint at the end of the
104849 ** range (if any).
104851 nConstraint = nEq;
104852 if( pRangeEnd ){
104853 Expr *pRight = pRangeEnd->pExpr->pRight;
104854 sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
104855 sqlite3ExprCode(pParse, pRight, regBase+nEq);
104856 if( (pRangeEnd->wtFlags & TERM_VNULL)==0 ){
104857 sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
104859 if( zEndAff ){
104860 if( sqlite3CompareAffinity(pRight, zEndAff[nEq])==SQLITE_AFF_NONE){
104861 /* Since the comparison is to be performed with no conversions
104862 ** applied to the operands, set the affinity to apply to pRight to
104863 ** SQLITE_AFF_NONE. */
104864 zEndAff[nEq] = SQLITE_AFF_NONE;
104866 if( sqlite3ExprNeedsNoAffinityChange(pRight, zEndAff[nEq]) ){
104867 zEndAff[nEq] = SQLITE_AFF_NONE;
104870 codeApplyAffinity(pParse, regBase, nEq+1, zEndAff);
104871 nConstraint++;
104872 testcase( pRangeEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
104874 sqlite3DbFree(pParse->db, zStartAff);
104875 sqlite3DbFree(pParse->db, zEndAff);
104877 /* Top of the loop body */
104878 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
104880 /* Check if the index cursor is past the end of the range. */
104881 op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
104882 testcase( op==OP_Noop );
104883 testcase( op==OP_IdxGE );
104884 testcase( op==OP_IdxLT );
104885 if( op!=OP_Noop ){
104886 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
104887 sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
104890 /* If there are inequality constraints, check that the value
104891 ** of the table column that the inequality contrains is not NULL.
104892 ** If it is, jump to the next iteration of the loop.
104894 r1 = sqlite3GetTempReg(pParse);
104895 testcase( pLevel->plan.wsFlags & WHERE_BTM_LIMIT );
104896 testcase( pLevel->plan.wsFlags & WHERE_TOP_LIMIT );
104897 if( (pLevel->plan.wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 ){
104898 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
104899 sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
104901 sqlite3ReleaseTempReg(pParse, r1);
104903 /* Seek the table cursor, if required */
104904 disableTerm(pLevel, pRangeStart);
104905 disableTerm(pLevel, pRangeEnd);
104906 if( !omitTable ){
104907 iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
104908 sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
104909 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
104910 sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg); /* Deferred seek */
104913 /* Record the instruction used to terminate the loop. Disable
104914 ** WHERE clause terms made redundant by the index range scan.
104916 if( pLevel->plan.wsFlags & WHERE_UNIQUE ){
104917 pLevel->op = OP_Noop;
104918 }else if( bRev ){
104919 pLevel->op = OP_Prev;
104920 }else{
104921 pLevel->op = OP_Next;
104923 pLevel->p1 = iIdxCur;
104924 }else
104926 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
104927 if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
104928 /* Case 4: Two or more separately indexed terms connected by OR
104930 ** Example:
104932 ** CREATE TABLE t1(a,b,c,d);
104933 ** CREATE INDEX i1 ON t1(a);
104934 ** CREATE INDEX i2 ON t1(b);
104935 ** CREATE INDEX i3 ON t1(c);
104937 ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
104939 ** In the example, there are three indexed terms connected by OR.
104940 ** The top of the loop looks like this:
104942 ** Null 1 # Zero the rowset in reg 1
104944 ** Then, for each indexed term, the following. The arguments to
104945 ** RowSetTest are such that the rowid of the current row is inserted
104946 ** into the RowSet. If it is already present, control skips the
104947 ** Gosub opcode and jumps straight to the code generated by WhereEnd().
104949 ** sqlite3WhereBegin(<term>)
104950 ** RowSetTest # Insert rowid into rowset
104951 ** Gosub 2 A
104952 ** sqlite3WhereEnd()
104954 ** Following the above, code to terminate the loop. Label A, the target
104955 ** of the Gosub above, jumps to the instruction right after the Goto.
104957 ** Null 1 # Zero the rowset in reg 1
104958 ** Goto B # The loop is finished.
104960 ** A: <loop body> # Return data, whatever.
104962 ** Return 2 # Jump back to the Gosub
104964 ** B: <after the loop>
104967 WhereClause *pOrWc; /* The OR-clause broken out into subterms */
104968 SrcList *pOrTab; /* Shortened table list or OR-clause generation */
104970 int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
104971 int regRowset = 0; /* Register for RowSet object */
104972 int regRowid = 0; /* Register holding rowid */
104973 int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */
104974 int iRetInit; /* Address of regReturn init */
104975 int untestedTerms = 0; /* Some terms not completely tested */
104976 int ii; /* Loop counter */
104977 Expr *pAndExpr = 0; /* An ".. AND (...)" expression */
104979 pTerm = pLevel->plan.u.pTerm;
104980 assert( pTerm!=0 );
104981 assert( pTerm->eOperator==WO_OR );
104982 assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
104983 pOrWc = &pTerm->u.pOrInfo->wc;
104984 pLevel->op = OP_Return;
104985 pLevel->p1 = regReturn;
104987 /* Set up a new SrcList ni pOrTab containing the table being scanned
104988 ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
104989 ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
104991 if( pWInfo->nLevel>1 ){
104992 int nNotReady; /* The number of notReady tables */
104993 struct SrcList_item *origSrc; /* Original list of tables */
104994 nNotReady = pWInfo->nLevel - iLevel - 1;
104995 pOrTab = sqlite3StackAllocRaw(pParse->db,
104996 sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
104997 if( pOrTab==0 ) return notReady;
104998 pOrTab->nAlloc = (i16)(nNotReady + 1);
104999 pOrTab->nSrc = pOrTab->nAlloc;
105000 memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
105001 origSrc = pWInfo->pTabList->a;
105002 for(k=1; k<=nNotReady; k++){
105003 memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
105005 }else{
105006 pOrTab = pWInfo->pTabList;
105009 /* Initialize the rowset register to contain NULL. An SQL NULL is
105010 ** equivalent to an empty rowset.
105012 ** Also initialize regReturn to contain the address of the instruction
105013 ** immediately following the OP_Return at the bottom of the loop. This
105014 ** is required in a few obscure LEFT JOIN cases where control jumps
105015 ** over the top of the loop into the body of it. In this case the
105016 ** correct response for the end-of-loop code (the OP_Return) is to
105017 ** fall through to the next instruction, just as an OP_Next does if
105018 ** called on an uninitialized cursor.
105020 if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
105021 regRowset = ++pParse->nMem;
105022 regRowid = ++pParse->nMem;
105023 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
105025 iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
105027 /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y
105028 ** Then for every term xN, evaluate as the subexpression: xN AND z
105029 ** That way, terms in y that are factored into the disjunction will
105030 ** be picked up by the recursive calls to sqlite3WhereBegin() below.
105032 if( pWC->nTerm>1 ){
105033 pAndExpr = sqlite3ExprAlloc(pParse->db, TK_AND, 0, 0);
105034 pAndExpr->pRight = pWhere;
105037 for(ii=0; ii<pOrWc->nTerm; ii++){
105038 WhereTerm *pOrTerm = &pOrWc->a[ii];
105039 if( pOrTerm->leftCursor==iCur || pOrTerm->eOperator==WO_AND ){
105040 WhereInfo *pSubWInfo; /* Info for single OR-term scan */
105041 Expr *pOrExpr = pOrTerm->pExpr;
105042 if( pAndExpr ){
105043 pAndExpr->pLeft = pOrExpr;
105044 pOrExpr = pAndExpr;
105046 /* Loop through table entries that match term pOrTerm. */
105047 pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
105048 WHERE_OMIT_OPEN_CLOSE | WHERE_AND_ONLY |
105049 WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY);
105050 if( pSubWInfo ){
105051 explainOneScan(
105052 pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
105054 if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
105055 int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
105056 int r;
105057 r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur,
105058 regRowid);
105059 sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
105060 sqlite3VdbeCurrentAddr(v)+2, r, iSet);
105062 sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
105064 /* The pSubWInfo->untestedTerms flag means that this OR term
105065 ** contained one or more AND term from a notReady table. The
105066 ** terms from the notReady table could not be tested and will
105067 ** need to be tested later.
105069 if( pSubWInfo->untestedTerms ) untestedTerms = 1;
105071 /* Finish the loop through table entries that match term pOrTerm. */
105072 sqlite3WhereEnd(pSubWInfo);
105076 sqlite3DbFree(pParse->db, pAndExpr);
105077 sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
105078 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
105079 sqlite3VdbeResolveLabel(v, iLoopBody);
105081 if( pWInfo->nLevel>1 ) sqlite3StackFree(pParse->db, pOrTab);
105082 if( !untestedTerms ) disableTerm(pLevel, pTerm);
105083 }else
105084 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
105087 /* Case 5: There is no usable index. We must do a complete
105088 ** scan of the entire table.
105090 static const u8 aStep[] = { OP_Next, OP_Prev };
105091 static const u8 aStart[] = { OP_Rewind, OP_Last };
105092 assert( bRev==0 || bRev==1 );
105093 assert( omitTable==0 );
105094 pLevel->op = aStep[bRev];
105095 pLevel->p1 = iCur;
105096 pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
105097 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
105099 notReady &= ~getMask(pWC->pMaskSet, iCur);
105101 /* Insert code to test every subexpression that can be completely
105102 ** computed using the current set of tables.
105104 ** IMPLEMENTATION-OF: R-49525-50935 Terms that cannot be satisfied through
105105 ** the use of indices become tests that are evaluated against each row of
105106 ** the relevant input tables.
105108 for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
105109 Expr *pE;
105110 testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* IMP: R-30575-11662 */
105111 testcase( pTerm->wtFlags & TERM_CODED );
105112 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
105113 if( (pTerm->prereqAll & notReady)!=0 ){
105114 testcase( pWInfo->untestedTerms==0
105115 && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
105116 pWInfo->untestedTerms = 1;
105117 continue;
105119 pE = pTerm->pExpr;
105120 assert( pE!=0 );
105121 if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
105122 continue;
105124 sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
105125 pTerm->wtFlags |= TERM_CODED;
105128 /* For a LEFT OUTER JOIN, generate code that will record the fact that
105129 ** at least one row of the right table has matched the left table.
105131 if( pLevel->iLeftJoin ){
105132 pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
105133 sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
105134 VdbeComment((v, "record LEFT JOIN hit"));
105135 sqlite3ExprCacheClear(pParse);
105136 for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
105137 testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* IMP: R-30575-11662 */
105138 testcase( pTerm->wtFlags & TERM_CODED );
105139 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
105140 if( (pTerm->prereqAll & notReady)!=0 ){
105141 assert( pWInfo->untestedTerms );
105142 continue;
105144 assert( pTerm->pExpr );
105145 sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
105146 pTerm->wtFlags |= TERM_CODED;
105149 sqlite3ReleaseTempReg(pParse, iReleaseReg);
105151 return notReady;
105154 #if defined(SQLITE_TEST)
105156 ** The following variable holds a text description of query plan generated
105157 ** by the most recent call to sqlite3WhereBegin(). Each call to WhereBegin
105158 ** overwrites the previous. This information is used for testing and
105159 ** analysis only.
105161 SQLITE_API char sqlite3_query_plan[BMS*2*40]; /* Text of the join */
105162 static int nQPlan = 0; /* Next free slow in _query_plan[] */
105164 #endif /* SQLITE_TEST */
105168 ** Free a WhereInfo structure
105170 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
105171 if( ALWAYS(pWInfo) ){
105172 int i;
105173 for(i=0; i<pWInfo->nLevel; i++){
105174 sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
105175 if( pInfo ){
105176 /* assert( pInfo->needToFreeIdxStr==0 || db->mallocFailed ); */
105177 if( pInfo->needToFreeIdxStr ){
105178 sqlite3_free(pInfo->idxStr);
105180 sqlite3DbFree(db, pInfo);
105182 if( pWInfo->a[i].plan.wsFlags & WHERE_TEMP_INDEX ){
105183 Index *pIdx = pWInfo->a[i].plan.u.pIdx;
105184 if( pIdx ){
105185 sqlite3DbFree(db, pIdx->zColAff);
105186 sqlite3DbFree(db, pIdx);
105190 whereClauseClear(pWInfo->pWC);
105191 sqlite3DbFree(db, pWInfo);
105197 ** Generate the beginning of the loop used for WHERE clause processing.
105198 ** The return value is a pointer to an opaque structure that contains
105199 ** information needed to terminate the loop. Later, the calling routine
105200 ** should invoke sqlite3WhereEnd() with the return value of this function
105201 ** in order to complete the WHERE clause processing.
105203 ** If an error occurs, this routine returns NULL.
105205 ** The basic idea is to do a nested loop, one loop for each table in
105206 ** the FROM clause of a select. (INSERT and UPDATE statements are the
105207 ** same as a SELECT with only a single table in the FROM clause.) For
105208 ** example, if the SQL is this:
105210 ** SELECT * FROM t1, t2, t3 WHERE ...;
105212 ** Then the code generated is conceptually like the following:
105214 ** foreach row1 in t1 do \ Code generated
105215 ** foreach row2 in t2 do |-- by sqlite3WhereBegin()
105216 ** foreach row3 in t3 do /
105217 ** ...
105218 ** end \ Code generated
105219 ** end |-- by sqlite3WhereEnd()
105220 ** end /
105222 ** Note that the loops might not be nested in the order in which they
105223 ** appear in the FROM clause if a different order is better able to make
105224 ** use of indices. Note also that when the IN operator appears in
105225 ** the WHERE clause, it might result in additional nested loops for
105226 ** scanning through all values on the right-hand side of the IN.
105228 ** There are Btree cursors associated with each table. t1 uses cursor
105229 ** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
105230 ** And so forth. This routine generates code to open those VDBE cursors
105231 ** and sqlite3WhereEnd() generates the code to close them.
105233 ** The code that sqlite3WhereBegin() generates leaves the cursors named
105234 ** in pTabList pointing at their appropriate entries. The [...] code
105235 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
105236 ** data from the various tables of the loop.
105238 ** If the WHERE clause is empty, the foreach loops must each scan their
105239 ** entire tables. Thus a three-way join is an O(N^3) operation. But if
105240 ** the tables have indices and there are terms in the WHERE clause that
105241 ** refer to those indices, a complete table scan can be avoided and the
105242 ** code will run much faster. Most of the work of this routine is checking
105243 ** to see if there are indices that can be used to speed up the loop.
105245 ** Terms of the WHERE clause are also used to limit which rows actually
105246 ** make it to the "..." in the middle of the loop. After each "foreach",
105247 ** terms of the WHERE clause that use only terms in that loop and outer
105248 ** loops are evaluated and if false a jump is made around all subsequent
105249 ** inner loops (or around the "..." if the test occurs within the inner-
105250 ** most loop)
105252 ** OUTER JOINS
105254 ** An outer join of tables t1 and t2 is conceptally coded as follows:
105256 ** foreach row1 in t1 do
105257 ** flag = 0
105258 ** foreach row2 in t2 do
105259 ** start:
105260 ** ...
105261 ** flag = 1
105262 ** end
105263 ** if flag==0 then
105264 ** move the row2 cursor to a null row
105265 ** goto start
105266 ** fi
105267 ** end
105269 ** ORDER BY CLAUSE PROCESSING
105271 ** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
105272 ** if there is one. If there is no ORDER BY clause or if this routine
105273 ** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
105275 ** If an index can be used so that the natural output order of the table
105276 ** scan is correct for the ORDER BY clause, then that index is used and
105277 ** *ppOrderBy is set to NULL. This is an optimization that prevents an
105278 ** unnecessary sort of the result set if an index appropriate for the
105279 ** ORDER BY clause already exists.
105281 ** If the where clause loops cannot be arranged to provide the correct
105282 ** output order, then the *ppOrderBy is unchanged.
105284 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
105285 Parse *pParse, /* The parser context */
105286 SrcList *pTabList, /* A list of all tables to be scanned */
105287 Expr *pWhere, /* The WHERE clause */
105288 ExprList **ppOrderBy, /* An ORDER BY clause, or NULL */
105289 ExprList *pDistinct, /* The select-list for DISTINCT queries - or NULL */
105290 u16 wctrlFlags /* One of the WHERE_* flags defined in sqliteInt.h */
105292 int i; /* Loop counter */
105293 int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
105294 int nTabList; /* Number of elements in pTabList */
105295 WhereInfo *pWInfo; /* Will become the return value of this function */
105296 Vdbe *v = pParse->pVdbe; /* The virtual database engine */
105297 Bitmask notReady; /* Cursors that are not yet positioned */
105298 WhereMaskSet *pMaskSet; /* The expression mask set */
105299 WhereClause *pWC; /* Decomposition of the WHERE clause */
105300 struct SrcList_item *pTabItem; /* A single entry from pTabList */
105301 WhereLevel *pLevel; /* A single level in the pWInfo list */
105302 int iFrom; /* First unused FROM clause element */
105303 int andFlags; /* AND-ed combination of all pWC->a[].wtFlags */
105304 sqlite3 *db; /* Database connection */
105306 /* The number of tables in the FROM clause is limited by the number of
105307 ** bits in a Bitmask
105309 testcase( pTabList->nSrc==BMS );
105310 if( pTabList->nSrc>BMS ){
105311 sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
105312 return 0;
105315 /* This function normally generates a nested loop for all tables in
105316 ** pTabList. But if the WHERE_ONETABLE_ONLY flag is set, then we should
105317 ** only generate code for the first table in pTabList and assume that
105318 ** any cursors associated with subsequent tables are uninitialized.
105320 nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
105322 /* Allocate and initialize the WhereInfo structure that will become the
105323 ** return value. A single allocation is used to store the WhereInfo
105324 ** struct, the contents of WhereInfo.a[], the WhereClause structure
105325 ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
105326 ** field (type Bitmask) it must be aligned on an 8-byte boundary on
105327 ** some architectures. Hence the ROUND8() below.
105329 db = pParse->db;
105330 nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
105331 pWInfo = sqlite3DbMallocZero(db,
105332 nByteWInfo +
105333 sizeof(WhereClause) +
105334 sizeof(WhereMaskSet)
105336 if( db->mallocFailed ){
105337 sqlite3DbFree(db, pWInfo);
105338 pWInfo = 0;
105339 goto whereBeginError;
105341 pWInfo->nLevel = nTabList;
105342 pWInfo->pParse = pParse;
105343 pWInfo->pTabList = pTabList;
105344 pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
105345 pWInfo->pWC = pWC = (WhereClause *)&((u8 *)pWInfo)[nByteWInfo];
105346 pWInfo->wctrlFlags = wctrlFlags;
105347 pWInfo->savedNQueryLoop = pParse->nQueryLoop;
105348 pMaskSet = (WhereMaskSet*)&pWC[1];
105350 /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
105351 ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
105352 if( db->flags & SQLITE_DistinctOpt ) pDistinct = 0;
105354 /* Split the WHERE clause into separate subexpressions where each
105355 ** subexpression is separated by an AND operator.
105357 initMaskSet(pMaskSet);
105358 whereClauseInit(pWC, pParse, pMaskSet, wctrlFlags);
105359 sqlite3ExprCodeConstants(pParse, pWhere);
105360 whereSplit(pWC, pWhere, TK_AND); /* IMP: R-15842-53296 */
105362 /* Special case: a WHERE clause that is constant. Evaluate the
105363 ** expression and either jump over all of the code or fall thru.
105365 if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
105366 sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
105367 pWhere = 0;
105370 /* Assign a bit from the bitmask to every term in the FROM clause.
105372 ** When assigning bitmask values to FROM clause cursors, it must be
105373 ** the case that if X is the bitmask for the N-th FROM clause term then
105374 ** the bitmask for all FROM clause terms to the left of the N-th term
105375 ** is (X-1). An expression from the ON clause of a LEFT JOIN can use
105376 ** its Expr.iRightJoinTable value to find the bitmask of the right table
105377 ** of the join. Subtracting one from the right table bitmask gives a
105378 ** bitmask for all tables to the left of the join. Knowing the bitmask
105379 ** for all tables to the left of a left join is important. Ticket #3015.
105381 ** Configure the WhereClause.vmask variable so that bits that correspond
105382 ** to virtual table cursors are set. This is used to selectively disable
105383 ** the OR-to-IN transformation in exprAnalyzeOrTerm(). It is not helpful
105384 ** with virtual tables.
105386 ** Note that bitmasks are created for all pTabList->nSrc tables in
105387 ** pTabList, not just the first nTabList tables. nTabList is normally
105388 ** equal to pTabList->nSrc but might be shortened to 1 if the
105389 ** WHERE_ONETABLE_ONLY flag is set.
105391 assert( pWC->vmask==0 && pMaskSet->n==0 );
105392 for(i=0; i<pTabList->nSrc; i++){
105393 createMask(pMaskSet, pTabList->a[i].iCursor);
105394 #ifndef SQLITE_OMIT_VIRTUALTABLE
105395 if( ALWAYS(pTabList->a[i].pTab) && IsVirtual(pTabList->a[i].pTab) ){
105396 pWC->vmask |= ((Bitmask)1 << i);
105398 #endif
105400 #ifndef NDEBUG
105402 Bitmask toTheLeft = 0;
105403 for(i=0; i<pTabList->nSrc; i++){
105404 Bitmask m = getMask(pMaskSet, pTabList->a[i].iCursor);
105405 assert( (m-1)==toTheLeft );
105406 toTheLeft |= m;
105409 #endif
105411 /* Analyze all of the subexpressions. Note that exprAnalyze() might
105412 ** add new virtual terms onto the end of the WHERE clause. We do not
105413 ** want to analyze these virtual terms, so start analyzing at the end
105414 ** and work forward so that the added virtual terms are never processed.
105416 exprAnalyzeAll(pTabList, pWC);
105417 if( db->mallocFailed ){
105418 goto whereBeginError;
105421 /* Check if the DISTINCT qualifier, if there is one, is redundant.
105422 ** If it is, then set pDistinct to NULL and WhereInfo.eDistinct to
105423 ** WHERE_DISTINCT_UNIQUE to tell the caller to ignore the DISTINCT.
105425 if( pDistinct && isDistinctRedundant(pParse, pTabList, pWC, pDistinct) ){
105426 pDistinct = 0;
105427 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
105430 /* Chose the best index to use for each table in the FROM clause.
105432 ** This loop fills in the following fields:
105434 ** pWInfo->a[].pIdx The index to use for this level of the loop.
105435 ** pWInfo->a[].wsFlags WHERE_xxx flags associated with pIdx
105436 ** pWInfo->a[].nEq The number of == and IN constraints
105437 ** pWInfo->a[].iFrom Which term of the FROM clause is being coded
105438 ** pWInfo->a[].iTabCur The VDBE cursor for the database table
105439 ** pWInfo->a[].iIdxCur The VDBE cursor for the index
105440 ** pWInfo->a[].pTerm When wsFlags==WO_OR, the OR-clause term
105442 ** This loop also figures out the nesting order of tables in the FROM
105443 ** clause.
105445 notReady = ~(Bitmask)0;
105446 andFlags = ~0;
105447 WHERETRACE(("*** Optimizer Start ***\n"));
105448 for(i=iFrom=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
105449 WhereCost bestPlan; /* Most efficient plan seen so far */
105450 Index *pIdx; /* Index for FROM table at pTabItem */
105451 int j; /* For looping over FROM tables */
105452 int bestJ = -1; /* The value of j */
105453 Bitmask m; /* Bitmask value for j or bestJ */
105454 int isOptimal; /* Iterator for optimal/non-optimal search */
105455 int nUnconstrained; /* Number tables without INDEXED BY */
105456 Bitmask notIndexed; /* Mask of tables that cannot use an index */
105458 memset(&bestPlan, 0, sizeof(bestPlan));
105459 bestPlan.rCost = SQLITE_BIG_DBL;
105460 WHERETRACE(("*** Begin search for loop %d ***\n", i));
105462 /* Loop through the remaining entries in the FROM clause to find the
105463 ** next nested loop. The loop tests all FROM clause entries
105464 ** either once or twice.
105466 ** The first test is always performed if there are two or more entries
105467 ** remaining and never performed if there is only one FROM clause entry
105468 ** to choose from. The first test looks for an "optimal" scan. In
105469 ** this context an optimal scan is one that uses the same strategy
105470 ** for the given FROM clause entry as would be selected if the entry
105471 ** were used as the innermost nested loop. In other words, a table
105472 ** is chosen such that the cost of running that table cannot be reduced
105473 ** by waiting for other tables to run first. This "optimal" test works
105474 ** by first assuming that the FROM clause is on the inner loop and finding
105475 ** its query plan, then checking to see if that query plan uses any
105476 ** other FROM clause terms that are notReady. If no notReady terms are
105477 ** used then the "optimal" query plan works.
105479 ** Note that the WhereCost.nRow parameter for an optimal scan might
105480 ** not be as small as it would be if the table really were the innermost
105481 ** join. The nRow value can be reduced by WHERE clause constraints
105482 ** that do not use indices. But this nRow reduction only happens if the
105483 ** table really is the innermost join.
105485 ** The second loop iteration is only performed if no optimal scan
105486 ** strategies were found by the first iteration. This second iteration
105487 ** is used to search for the lowest cost scan overall.
105489 ** Previous versions of SQLite performed only the second iteration -
105490 ** the next outermost loop was always that with the lowest overall
105491 ** cost. However, this meant that SQLite could select the wrong plan
105492 ** for scripts such as the following:
105494 ** CREATE TABLE t1(a, b);
105495 ** CREATE TABLE t2(c, d);
105496 ** SELECT * FROM t2, t1 WHERE t2.rowid = t1.a;
105498 ** The best strategy is to iterate through table t1 first. However it
105499 ** is not possible to determine this with a simple greedy algorithm.
105500 ** Since the cost of a linear scan through table t2 is the same
105501 ** as the cost of a linear scan through table t1, a simple greedy
105502 ** algorithm may choose to use t2 for the outer loop, which is a much
105503 ** costlier approach.
105505 nUnconstrained = 0;
105506 notIndexed = 0;
105507 for(isOptimal=(iFrom<nTabList-1); isOptimal>=0 && bestJ<0; isOptimal--){
105508 Bitmask mask; /* Mask of tables not yet ready */
105509 for(j=iFrom, pTabItem=&pTabList->a[j]; j<nTabList; j++, pTabItem++){
105510 int doNotReorder; /* True if this table should not be reordered */
105511 WhereCost sCost; /* Cost information from best[Virtual]Index() */
105512 ExprList *pOrderBy; /* ORDER BY clause for index to optimize */
105513 ExprList *pDist; /* DISTINCT clause for index to optimize */
105515 doNotReorder = (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0;
105516 if( j!=iFrom && doNotReorder ) break;
105517 m = getMask(pMaskSet, pTabItem->iCursor);
105518 if( (m & notReady)==0 ){
105519 if( j==iFrom ) iFrom++;
105520 continue;
105522 mask = (isOptimal ? m : notReady);
105523 pOrderBy = ((i==0 && ppOrderBy )?*ppOrderBy:0);
105524 pDist = (i==0 ? pDistinct : 0);
105525 if( pTabItem->pIndex==0 ) nUnconstrained++;
105527 WHERETRACE(("=== trying table %d with isOptimal=%d ===\n",
105528 j, isOptimal));
105529 assert( pTabItem->pTab );
105530 #ifndef SQLITE_OMIT_VIRTUALTABLE
105531 if( IsVirtual(pTabItem->pTab) ){
105532 sqlite3_index_info **pp = &pWInfo->a[j].pIdxInfo;
105533 bestVirtualIndex(pParse, pWC, pTabItem, mask, notReady, pOrderBy,
105534 &sCost, pp);
105535 }else
105536 #endif
105538 bestBtreeIndex(pParse, pWC, pTabItem, mask, notReady, pOrderBy,
105539 pDist, &sCost);
105541 assert( isOptimal || (sCost.used&notReady)==0 );
105543 /* If an INDEXED BY clause is present, then the plan must use that
105544 ** index if it uses any index at all */
105545 assert( pTabItem->pIndex==0
105546 || (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0
105547 || sCost.plan.u.pIdx==pTabItem->pIndex );
105549 if( isOptimal && (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ){
105550 notIndexed |= m;
105553 /* Conditions under which this table becomes the best so far:
105555 ** (1) The table must not depend on other tables that have not
105556 ** yet run.
105558 ** (2) A full-table-scan plan cannot supercede indexed plan unless
105559 ** the full-table-scan is an "optimal" plan as defined above.
105561 ** (3) All tables have an INDEXED BY clause or this table lacks an
105562 ** INDEXED BY clause or this table uses the specific
105563 ** index specified by its INDEXED BY clause. This rule ensures
105564 ** that a best-so-far is always selected even if an impossible
105565 ** combination of INDEXED BY clauses are given. The error
105566 ** will be detected and relayed back to the application later.
105567 ** The NEVER() comes about because rule (2) above prevents
105568 ** An indexable full-table-scan from reaching rule (3).
105570 ** (4) The plan cost must be lower than prior plans or else the
105571 ** cost must be the same and the number of rows must be lower.
105573 if( (sCost.used&notReady)==0 /* (1) */
105574 && (bestJ<0 || (notIndexed&m)!=0 /* (2) */
105575 || (bestPlan.plan.wsFlags & WHERE_NOT_FULLSCAN)==0
105576 || (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0)
105577 && (nUnconstrained==0 || pTabItem->pIndex==0 /* (3) */
105578 || NEVER((sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0))
105579 && (bestJ<0 || sCost.rCost<bestPlan.rCost /* (4) */
105580 || (sCost.rCost<=bestPlan.rCost
105581 && sCost.plan.nRow<bestPlan.plan.nRow))
105583 WHERETRACE(("=== table %d is best so far"
105584 " with cost=%g and nRow=%g\n",
105585 j, sCost.rCost, sCost.plan.nRow));
105586 bestPlan = sCost;
105587 bestJ = j;
105589 if( doNotReorder ) break;
105592 assert( bestJ>=0 );
105593 assert( notReady & getMask(pMaskSet, pTabList->a[bestJ].iCursor) );
105594 WHERETRACE(("*** Optimizer selects table %d for loop %d"
105595 " with cost=%g and nRow=%g\n",
105596 bestJ, pLevel-pWInfo->a, bestPlan.rCost, bestPlan.plan.nRow));
105597 /* The ALWAYS() that follows was added to hush up clang scan-build */
105598 if( (bestPlan.plan.wsFlags & WHERE_ORDERBY)!=0 && ALWAYS(ppOrderBy) ){
105599 *ppOrderBy = 0;
105601 if( (bestPlan.plan.wsFlags & WHERE_DISTINCT)!=0 ){
105602 assert( pWInfo->eDistinct==0 );
105603 pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
105605 andFlags &= bestPlan.plan.wsFlags;
105606 pLevel->plan = bestPlan.plan;
105607 testcase( bestPlan.plan.wsFlags & WHERE_INDEXED );
105608 testcase( bestPlan.plan.wsFlags & WHERE_TEMP_INDEX );
105609 if( bestPlan.plan.wsFlags & (WHERE_INDEXED|WHERE_TEMP_INDEX) ){
105610 pLevel->iIdxCur = pParse->nTab++;
105611 }else{
105612 pLevel->iIdxCur = -1;
105614 notReady &= ~getMask(pMaskSet, pTabList->a[bestJ].iCursor);
105615 pLevel->iFrom = (u8)bestJ;
105616 if( bestPlan.plan.nRow>=(double)1 ){
105617 pParse->nQueryLoop *= bestPlan.plan.nRow;
105620 /* Check that if the table scanned by this loop iteration had an
105621 ** INDEXED BY clause attached to it, that the named index is being
105622 ** used for the scan. If not, then query compilation has failed.
105623 ** Return an error.
105625 pIdx = pTabList->a[bestJ].pIndex;
105626 if( pIdx ){
105627 if( (bestPlan.plan.wsFlags & WHERE_INDEXED)==0 ){
105628 sqlite3ErrorMsg(pParse, "cannot use index: %s", pIdx->zName);
105629 goto whereBeginError;
105630 }else{
105631 /* If an INDEXED BY clause is used, the bestIndex() function is
105632 ** guaranteed to find the index specified in the INDEXED BY clause
105633 ** if it find an index at all. */
105634 assert( bestPlan.plan.u.pIdx==pIdx );
105638 WHERETRACE(("*** Optimizer Finished ***\n"));
105639 if( pParse->nErr || db->mallocFailed ){
105640 goto whereBeginError;
105643 /* If the total query only selects a single row, then the ORDER BY
105644 ** clause is irrelevant.
105646 if( (andFlags & WHERE_UNIQUE)!=0 && ppOrderBy ){
105647 *ppOrderBy = 0;
105650 /* If the caller is an UPDATE or DELETE statement that is requesting
105651 ** to use a one-pass algorithm, determine if this is appropriate.
105652 ** The one-pass algorithm only works if the WHERE clause constraints
105653 ** the statement to update a single row.
105655 assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
105656 if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){
105657 pWInfo->okOnePass = 1;
105658 pWInfo->a[0].plan.wsFlags &= ~WHERE_IDX_ONLY;
105661 /* Open all tables in the pTabList and any indices selected for
105662 ** searching those tables.
105664 sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
105665 notReady = ~(Bitmask)0;
105666 pWInfo->nRowOut = (double)1;
105667 for(i=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
105668 Table *pTab; /* Table to open */
105669 int iDb; /* Index of database containing table/index */
105671 pTabItem = &pTabList->a[pLevel->iFrom];
105672 pTab = pTabItem->pTab;
105673 pLevel->iTabCur = pTabItem->iCursor;
105674 pWInfo->nRowOut *= pLevel->plan.nRow;
105675 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
105676 if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
105677 /* Do nothing */
105678 }else
105679 #ifndef SQLITE_OMIT_VIRTUALTABLE
105680 if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
105681 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
105682 int iCur = pTabItem->iCursor;
105683 sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
105684 }else
105685 #endif
105686 if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
105687 && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
105688 int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
105689 sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
105690 testcase( pTab->nCol==BMS-1 );
105691 testcase( pTab->nCol==BMS );
105692 if( !pWInfo->okOnePass && pTab->nCol<BMS ){
105693 Bitmask b = pTabItem->colUsed;
105694 int n = 0;
105695 for(; b; b=b>>1, n++){}
105696 sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
105697 SQLITE_INT_TO_PTR(n), P4_INT32);
105698 assert( n<=pTab->nCol );
105700 }else{
105701 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
105703 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
105704 if( (pLevel->plan.wsFlags & WHERE_TEMP_INDEX)!=0 ){
105705 constructAutomaticIndex(pParse, pWC, pTabItem, notReady, pLevel);
105706 }else
105707 #endif
105708 if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
105709 Index *pIx = pLevel->plan.u.pIdx;
105710 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
105711 int iIdxCur = pLevel->iIdxCur;
105712 assert( pIx->pSchema==pTab->pSchema );
105713 assert( iIdxCur>=0 );
105714 sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIx->tnum, iDb,
105715 (char*)pKey, P4_KEYINFO_HANDOFF);
105716 VdbeComment((v, "%s", pIx->zName));
105718 sqlite3CodeVerifySchema(pParse, iDb);
105719 notReady &= ~getMask(pWC->pMaskSet, pTabItem->iCursor);
105721 pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
105722 if( db->mallocFailed ) goto whereBeginError;
105724 /* Generate the code to do the search. Each iteration of the for
105725 ** loop below generates code for a single nested loop of the VM
105726 ** program.
105728 notReady = ~(Bitmask)0;
105729 for(i=0; i<nTabList; i++){
105730 pLevel = &pWInfo->a[i];
105731 explainOneScan(pParse, pTabList, pLevel, i, pLevel->iFrom, wctrlFlags);
105732 notReady = codeOneLoopStart(pWInfo, i, wctrlFlags, notReady, pWhere);
105733 pWInfo->iContinue = pLevel->addrCont;
105736 #ifdef SQLITE_TEST /* For testing and debugging use only */
105737 /* Record in the query plan information about the current table
105738 ** and the index used to access it (if any). If the table itself
105739 ** is not used, its name is just '{}'. If no index is used
105740 ** the index is listed as "{}". If the primary key is used the
105741 ** index name is '*'.
105743 for(i=0; i<nTabList; i++){
105744 char *z;
105745 int n;
105746 pLevel = &pWInfo->a[i];
105747 pTabItem = &pTabList->a[pLevel->iFrom];
105748 z = pTabItem->zAlias;
105749 if( z==0 ) z = pTabItem->pTab->zName;
105750 n = sqlite3Strlen30(z);
105751 if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
105752 if( pLevel->plan.wsFlags & WHERE_IDX_ONLY ){
105753 memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
105754 nQPlan += 2;
105755 }else{
105756 memcpy(&sqlite3_query_plan[nQPlan], z, n);
105757 nQPlan += n;
105759 sqlite3_query_plan[nQPlan++] = ' ';
105761 testcase( pLevel->plan.wsFlags & WHERE_ROWID_EQ );
105762 testcase( pLevel->plan.wsFlags & WHERE_ROWID_RANGE );
105763 if( pLevel->plan.wsFlags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
105764 memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
105765 nQPlan += 2;
105766 }else if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
105767 n = sqlite3Strlen30(pLevel->plan.u.pIdx->zName);
105768 if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
105769 memcpy(&sqlite3_query_plan[nQPlan], pLevel->plan.u.pIdx->zName, n);
105770 nQPlan += n;
105771 sqlite3_query_plan[nQPlan++] = ' ';
105773 }else{
105774 memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
105775 nQPlan += 3;
105778 while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
105779 sqlite3_query_plan[--nQPlan] = 0;
105781 sqlite3_query_plan[nQPlan] = 0;
105782 nQPlan = 0;
105783 #endif /* SQLITE_TEST // Testing and debugging use only */
105785 /* Record the continuation address in the WhereInfo structure. Then
105786 ** clean up and return.
105788 return pWInfo;
105790 /* Jump here if malloc fails */
105791 whereBeginError:
105792 if( pWInfo ){
105793 pParse->nQueryLoop = pWInfo->savedNQueryLoop;
105794 whereInfoFree(db, pWInfo);
105796 return 0;
105800 ** Generate the end of the WHERE loop. See comments on
105801 ** sqlite3WhereBegin() for additional information.
105803 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
105804 Parse *pParse = pWInfo->pParse;
105805 Vdbe *v = pParse->pVdbe;
105806 int i;
105807 WhereLevel *pLevel;
105808 SrcList *pTabList = pWInfo->pTabList;
105809 sqlite3 *db = pParse->db;
105811 /* Generate loop termination code.
105813 sqlite3ExprCacheClear(pParse);
105814 for(i=pWInfo->nLevel-1; i>=0; i--){
105815 pLevel = &pWInfo->a[i];
105816 sqlite3VdbeResolveLabel(v, pLevel->addrCont);
105817 if( pLevel->op!=OP_Noop ){
105818 sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
105819 sqlite3VdbeChangeP5(v, pLevel->p5);
105821 if( pLevel->plan.wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
105822 struct InLoop *pIn;
105823 int j;
105824 sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
105825 for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
105826 sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
105827 sqlite3VdbeAddOp2(v, OP_Next, pIn->iCur, pIn->addrInTop);
105828 sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
105830 sqlite3DbFree(db, pLevel->u.in.aInLoop);
105832 sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
105833 if( pLevel->iLeftJoin ){
105834 int addr;
105835 addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
105836 assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
105837 || (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 );
105838 if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){
105839 sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
105841 if( pLevel->iIdxCur>=0 ){
105842 sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
105844 if( pLevel->op==OP_Return ){
105845 sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
105846 }else{
105847 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
105849 sqlite3VdbeJumpHere(v, addr);
105853 /* The "break" point is here, just past the end of the outer loop.
105854 ** Set it.
105856 sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
105858 /* Close all of the cursors that were opened by sqlite3WhereBegin.
105860 assert( pWInfo->nLevel==1 || pWInfo->nLevel==pTabList->nSrc );
105861 for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
105862 struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
105863 Table *pTab = pTabItem->pTab;
105864 assert( pTab!=0 );
105865 if( (pTab->tabFlags & TF_Ephemeral)==0
105866 && pTab->pSelect==0
105867 && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
105869 int ws = pLevel->plan.wsFlags;
105870 if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
105871 sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
105873 if( (ws & WHERE_INDEXED)!=0 && (ws & WHERE_TEMP_INDEX)==0 ){
105874 sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
105878 /* If this scan uses an index, make code substitutions to read data
105879 ** from the index in preference to the table. Sometimes, this means
105880 ** the table need never be read from. This is a performance boost,
105881 ** as the vdbe level waits until the table is read before actually
105882 ** seeking the table cursor to the record corresponding to the current
105883 ** position in the index.
105885 ** Calls to the code generator in between sqlite3WhereBegin and
105886 ** sqlite3WhereEnd will have created code that references the table
105887 ** directly. This loop scans all that code looking for opcodes
105888 ** that reference the table and converts them into opcodes that
105889 ** reference the index.
105891 if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 && !db->mallocFailed){
105892 int k, j, last;
105893 VdbeOp *pOp;
105894 Index *pIdx = pLevel->plan.u.pIdx;
105896 assert( pIdx!=0 );
105897 pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
105898 last = sqlite3VdbeCurrentAddr(v);
105899 for(k=pWInfo->iTop; k<last; k++, pOp++){
105900 if( pOp->p1!=pLevel->iTabCur ) continue;
105901 if( pOp->opcode==OP_Column ){
105902 for(j=0; j<pIdx->nColumn; j++){
105903 if( pOp->p2==pIdx->aiColumn[j] ){
105904 pOp->p2 = j;
105905 pOp->p1 = pLevel->iIdxCur;
105906 break;
105909 assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
105910 || j<pIdx->nColumn );
105911 }else if( pOp->opcode==OP_Rowid ){
105912 pOp->p1 = pLevel->iIdxCur;
105913 pOp->opcode = OP_IdxRowid;
105919 /* Final cleanup
105921 pParse->nQueryLoop = pWInfo->savedNQueryLoop;
105922 whereInfoFree(db, pWInfo);
105923 return;
105926 /************** End of where.c ***********************************************/
105927 /************** Begin file parse.c *******************************************/
105928 /* Driver template for the LEMON parser generator.
105929 ** The author disclaims copyright to this source code.
105931 ** This version of "lempar.c" is modified, slightly, for use by SQLite.
105932 ** The only modifications are the addition of a couple of NEVER()
105933 ** macros to disable tests that are needed in the case of a general
105934 ** LALR(1) grammar but which are always false in the
105935 ** specific grammar used by SQLite.
105937 /* First off, code is included that follows the "include" declaration
105938 ** in the input grammar file. */
105939 /* #include <stdio.h> */
105943 ** Disable all error recovery processing in the parser push-down
105944 ** automaton.
105946 #define YYNOERRORRECOVERY 1
105949 ** Make yytestcase() the same as testcase()
105951 #define yytestcase(X) testcase(X)
105954 ** An instance of this structure holds information about the
105955 ** LIMIT clause of a SELECT statement.
105957 struct LimitVal {
105958 Expr *pLimit; /* The LIMIT expression. NULL if there is no limit */
105959 Expr *pOffset; /* The OFFSET expression. NULL if there is none */
105963 ** An instance of this structure is used to store the LIKE,
105964 ** GLOB, NOT LIKE, and NOT GLOB operators.
105966 struct LikeOp {
105967 Token eOperator; /* "like" or "glob" or "regexp" */
105968 int not; /* True if the NOT keyword is present */
105972 ** An instance of the following structure describes the event of a
105973 ** TRIGGER. "a" is the event type, one of TK_UPDATE, TK_INSERT,
105974 ** TK_DELETE, or TK_INSTEAD. If the event is of the form
105976 ** UPDATE ON (a,b,c)
105978 ** Then the "b" IdList records the list "a,b,c".
105980 struct TrigEvent { int a; IdList * b; };
105983 ** An instance of this structure holds the ATTACH key and the key type.
105985 struct AttachKey { int type; Token key; };
105988 /* This is a utility routine used to set the ExprSpan.zStart and
105989 ** ExprSpan.zEnd values of pOut so that the span covers the complete
105990 ** range of text beginning with pStart and going to the end of pEnd.
105992 static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
105993 pOut->zStart = pStart->z;
105994 pOut->zEnd = &pEnd->z[pEnd->n];
105997 /* Construct a new Expr object from a single identifier. Use the
105998 ** new Expr to populate pOut. Set the span of pOut to be the identifier
105999 ** that created the expression.
106001 static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
106002 pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
106003 pOut->zStart = pValue->z;
106004 pOut->zEnd = &pValue->z[pValue->n];
106007 /* This routine constructs a binary expression node out of two ExprSpan
106008 ** objects and uses the result to populate a new ExprSpan object.
106010 static void spanBinaryExpr(
106011 ExprSpan *pOut, /* Write the result here */
106012 Parse *pParse, /* The parsing context. Errors accumulate here */
106013 int op, /* The binary operation */
106014 ExprSpan *pLeft, /* The left operand */
106015 ExprSpan *pRight /* The right operand */
106017 pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
106018 pOut->zStart = pLeft->zStart;
106019 pOut->zEnd = pRight->zEnd;
106022 /* Construct an expression node for a unary postfix operator
106024 static void spanUnaryPostfix(
106025 ExprSpan *pOut, /* Write the new expression node here */
106026 Parse *pParse, /* Parsing context to record errors */
106027 int op, /* The operator */
106028 ExprSpan *pOperand, /* The operand */
106029 Token *pPostOp /* The operand token for setting the span */
106031 pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
106032 pOut->zStart = pOperand->zStart;
106033 pOut->zEnd = &pPostOp->z[pPostOp->n];
106036 /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
106037 ** unary TK_ISNULL or TK_NOTNULL expression. */
106038 static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
106039 sqlite3 *db = pParse->db;
106040 if( db->mallocFailed==0 && pY->op==TK_NULL ){
106041 pA->op = (u8)op;
106042 sqlite3ExprDelete(db, pA->pRight);
106043 pA->pRight = 0;
106047 /* Construct an expression node for a unary prefix operator
106049 static void spanUnaryPrefix(
106050 ExprSpan *pOut, /* Write the new expression node here */
106051 Parse *pParse, /* Parsing context to record errors */
106052 int op, /* The operator */
106053 ExprSpan *pOperand, /* The operand */
106054 Token *pPreOp /* The operand token for setting the span */
106056 pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
106057 pOut->zStart = pPreOp->z;
106058 pOut->zEnd = pOperand->zEnd;
106060 /* Next is all token values, in a form suitable for use by makeheaders.
106061 ** This section will be null unless lemon is run with the -m switch.
106064 ** These constants (all generated automatically by the parser generator)
106065 ** specify the various kinds of tokens (terminals) that the parser
106066 ** understands.
106068 ** Each symbol here is a terminal symbol in the grammar.
106070 /* Make sure the INTERFACE macro is defined.
106072 #ifndef INTERFACE
106073 # define INTERFACE 1
106074 #endif
106075 /* The next thing included is series of defines which control
106076 ** various aspects of the generated parser.
106077 ** YYCODETYPE is the data type used for storing terminal
106078 ** and nonterminal numbers. "unsigned char" is
106079 ** used if there are fewer than 250 terminals
106080 ** and nonterminals. "int" is used otherwise.
106081 ** YYNOCODE is a number of type YYCODETYPE which corresponds
106082 ** to no legal terminal or nonterminal number. This
106083 ** number is used to fill in empty slots of the hash
106084 ** table.
106085 ** YYFALLBACK If defined, this indicates that one or more tokens
106086 ** have fall-back values which should be used if the
106087 ** original value of the token will not parse.
106088 ** YYACTIONTYPE is the data type used for storing terminal
106089 ** and nonterminal numbers. "unsigned char" is
106090 ** used if there are fewer than 250 rules and
106091 ** states combined. "int" is used otherwise.
106092 ** sqlite3ParserTOKENTYPE is the data type used for minor tokens given
106093 ** directly to the parser from the tokenizer.
106094 ** YYMINORTYPE is the data type used for all minor tokens.
106095 ** This is typically a union of many types, one of
106096 ** which is sqlite3ParserTOKENTYPE. The entry in the union
106097 ** for base tokens is called "yy0".
106098 ** YYSTACKDEPTH is the maximum depth of the parser's stack. If
106099 ** zero the stack is dynamically sized using realloc()
106100 ** sqlite3ParserARG_SDECL A static variable declaration for the %extra_argument
106101 ** sqlite3ParserARG_PDECL A parameter declaration for the %extra_argument
106102 ** sqlite3ParserARG_STORE Code to store %extra_argument into yypParser
106103 ** sqlite3ParserARG_FETCH Code to extract %extra_argument from yypParser
106104 ** YYNSTATE the combined number of states.
106105 ** YYNRULE the number of rules in the grammar
106106 ** YYERRORSYMBOL is the code number of the error symbol. If not
106107 ** defined, then do no error processing.
106109 #define YYCODETYPE unsigned char
106110 #define YYNOCODE 253
106111 #define YYACTIONTYPE unsigned short int
106112 #define YYWILDCARD 67
106113 #define sqlite3ParserTOKENTYPE Token
106114 typedef union {
106115 int yyinit;
106116 sqlite3ParserTOKENTYPE yy0;
106117 int yy4;
106118 struct TrigEvent yy90;
106119 ExprSpan yy118;
106120 TriggerStep* yy203;
106121 u8 yy210;
106122 struct {int value; int mask;} yy215;
106123 SrcList* yy259;
106124 struct LimitVal yy292;
106125 Expr* yy314;
106126 ExprList* yy322;
106127 struct LikeOp yy342;
106128 IdList* yy384;
106129 Select* yy387;
106130 } YYMINORTYPE;
106131 #ifndef YYSTACKDEPTH
106132 #define YYSTACKDEPTH 100
106133 #endif
106134 #define sqlite3ParserARG_SDECL Parse *pParse;
106135 #define sqlite3ParserARG_PDECL ,Parse *pParse
106136 #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
106137 #define sqlite3ParserARG_STORE yypParser->pParse = pParse
106138 #define YYNSTATE 630
106139 #define YYNRULE 329
106140 #define YYFALLBACK 1
106141 #define YY_NO_ACTION (YYNSTATE+YYNRULE+2)
106142 #define YY_ACCEPT_ACTION (YYNSTATE+YYNRULE+1)
106143 #define YY_ERROR_ACTION (YYNSTATE+YYNRULE)
106145 /* The yyzerominor constant is used to initialize instances of
106146 ** YYMINORTYPE objects to zero. */
106147 static const YYMINORTYPE yyzerominor = { 0 };
106149 /* Define the yytestcase() macro to be a no-op if is not already defined
106150 ** otherwise.
106152 ** Applications can choose to define yytestcase() in the %include section
106153 ** to a macro that can assist in verifying code coverage. For production
106154 ** code the yytestcase() macro should be turned off. But it is useful
106155 ** for testing.
106157 #ifndef yytestcase
106158 # define yytestcase(X)
106159 #endif
106162 /* Next are the tables used to determine what action to take based on the
106163 ** current state and lookahead token. These tables are used to implement
106164 ** functions that take a state number and lookahead value and return an
106165 ** action integer.
106167 ** Suppose the action integer is N. Then the action is determined as
106168 ** follows
106170 ** 0 <= N < YYNSTATE Shift N. That is, push the lookahead
106171 ** token onto the stack and goto state N.
106173 ** YYNSTATE <= N < YYNSTATE+YYNRULE Reduce by rule N-YYNSTATE.
106175 ** N == YYNSTATE+YYNRULE A syntax error has occurred.
106177 ** N == YYNSTATE+YYNRULE+1 The parser accepts its input.
106179 ** N == YYNSTATE+YYNRULE+2 No such action. Denotes unused
106180 ** slots in the yy_action[] table.
106182 ** The action table is constructed as a single large table named yy_action[].
106183 ** Given state S and lookahead X, the action is computed as
106185 ** yy_action[ yy_shift_ofst[S] + X ]
106187 ** If the index value yy_shift_ofst[S]+X is out of range or if the value
106188 ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
106189 ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
106190 ** and that yy_default[S] should be used instead.
106192 ** The formula above is for computing the action when the lookahead is
106193 ** a terminal symbol. If the lookahead is a non-terminal (as occurs after
106194 ** a reduce action) then the yy_reduce_ofst[] array is used in place of
106195 ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
106196 ** YY_SHIFT_USE_DFLT.
106198 ** The following are the tables generated in this section:
106200 ** yy_action[] A single table containing all actions.
106201 ** yy_lookahead[] A table containing the lookahead for each entry in
106202 ** yy_action. Used to detect hash collisions.
106203 ** yy_shift_ofst[] For each state, the offset into yy_action for
106204 ** shifting terminals.
106205 ** yy_reduce_ofst[] For each state, the offset into yy_action for
106206 ** shifting non-terminals after a reduce.
106207 ** yy_default[] Default action for each state.
106209 #define YY_ACTTAB_COUNT (1557)
106210 static const YYACTIONTYPE yy_action[] = {
106211 /* 0 */ 313, 960, 186, 419, 2, 172, 627, 597, 55, 55,
106212 /* 10 */ 55, 55, 48, 53, 53, 53, 53, 52, 52, 51,
106213 /* 20 */ 51, 51, 50, 238, 302, 283, 623, 622, 516, 515,
106214 /* 30 */ 590, 584, 55, 55, 55, 55, 282, 53, 53, 53,
106215 /* 40 */ 53, 52, 52, 51, 51, 51, 50, 238, 6, 56,
106216 /* 50 */ 57, 47, 582, 581, 583, 583, 54, 54, 55, 55,
106217 /* 60 */ 55, 55, 608, 53, 53, 53, 53, 52, 52, 51,
106218 /* 70 */ 51, 51, 50, 238, 313, 597, 409, 330, 579, 579,
106219 /* 80 */ 32, 53, 53, 53, 53, 52, 52, 51, 51, 51,
106220 /* 90 */ 50, 238, 330, 217, 620, 619, 166, 411, 624, 382,
106221 /* 100 */ 379, 378, 7, 491, 590, 584, 200, 199, 198, 58,
106222 /* 110 */ 377, 300, 414, 621, 481, 66, 623, 622, 621, 580,
106223 /* 120 */ 254, 601, 94, 56, 57, 47, 582, 581, 583, 583,
106224 /* 130 */ 54, 54, 55, 55, 55, 55, 671, 53, 53, 53,
106225 /* 140 */ 53, 52, 52, 51, 51, 51, 50, 238, 313, 532,
106226 /* 150 */ 226, 506, 507, 133, 177, 139, 284, 385, 279, 384,
106227 /* 160 */ 169, 197, 342, 398, 251, 226, 253, 275, 388, 167,
106228 /* 170 */ 139, 284, 385, 279, 384, 169, 570, 236, 590, 584,
106229 /* 180 */ 672, 240, 275, 157, 620, 619, 554, 437, 51, 51,
106230 /* 190 */ 51, 50, 238, 343, 439, 553, 438, 56, 57, 47,
106231 /* 200 */ 582, 581, 583, 583, 54, 54, 55, 55, 55, 55,
106232 /* 210 */ 465, 53, 53, 53, 53, 52, 52, 51, 51, 51,
106233 /* 220 */ 50, 238, 313, 390, 52, 52, 51, 51, 51, 50,
106234 /* 230 */ 238, 391, 166, 491, 566, 382, 379, 378, 409, 440,
106235 /* 240 */ 579, 579, 252, 440, 607, 66, 377, 513, 621, 49,
106236 /* 250 */ 46, 147, 590, 584, 621, 16, 466, 189, 621, 441,
106237 /* 260 */ 442, 673, 526, 441, 340, 577, 595, 64, 194, 482,
106238 /* 270 */ 434, 56, 57, 47, 582, 581, 583, 583, 54, 54,
106239 /* 280 */ 55, 55, 55, 55, 30, 53, 53, 53, 53, 52,
106240 /* 290 */ 52, 51, 51, 51, 50, 238, 313, 593, 593, 593,
106241 /* 300 */ 387, 578, 606, 493, 259, 351, 258, 411, 1, 623,
106242 /* 310 */ 622, 496, 623, 622, 65, 240, 623, 622, 597, 443,
106243 /* 320 */ 237, 239, 414, 341, 237, 602, 590, 584, 18, 603,
106244 /* 330 */ 166, 601, 87, 382, 379, 378, 67, 623, 622, 38,
106245 /* 340 */ 623, 622, 176, 270, 377, 56, 57, 47, 582, 581,
106246 /* 350 */ 583, 583, 54, 54, 55, 55, 55, 55, 175, 53,
106247 /* 360 */ 53, 53, 53, 52, 52, 51, 51, 51, 50, 238,
106248 /* 370 */ 313, 396, 233, 411, 531, 565, 317, 620, 619, 44,
106249 /* 380 */ 620, 619, 240, 206, 620, 619, 597, 266, 414, 268,
106250 /* 390 */ 409, 597, 579, 579, 352, 184, 505, 601, 73, 533,
106251 /* 400 */ 590, 584, 466, 548, 190, 620, 619, 576, 620, 619,
106252 /* 410 */ 547, 383, 551, 35, 332, 575, 574, 600, 504, 56,
106253 /* 420 */ 57, 47, 582, 581, 583, 583, 54, 54, 55, 55,
106254 /* 430 */ 55, 55, 567, 53, 53, 53, 53, 52, 52, 51,
106255 /* 440 */ 51, 51, 50, 238, 313, 411, 561, 561, 528, 364,
106256 /* 450 */ 259, 351, 258, 183, 361, 549, 524, 374, 411, 597,
106257 /* 460 */ 414, 240, 560, 560, 409, 604, 579, 579, 328, 601,
106258 /* 470 */ 93, 623, 622, 414, 590, 584, 237, 564, 559, 559,
106259 /* 480 */ 520, 402, 601, 87, 409, 210, 579, 579, 168, 421,
106260 /* 490 */ 950, 519, 950, 56, 57, 47, 582, 581, 583, 583,
106261 /* 500 */ 54, 54, 55, 55, 55, 55, 192, 53, 53, 53,
106262 /* 510 */ 53, 52, 52, 51, 51, 51, 50, 238, 313, 600,
106263 /* 520 */ 293, 563, 511, 234, 357, 146, 475, 475, 367, 411,
106264 /* 530 */ 562, 411, 358, 542, 425, 171, 411, 215, 144, 620,
106265 /* 540 */ 619, 544, 318, 353, 414, 203, 414, 275, 590, 584,
106266 /* 550 */ 549, 414, 174, 601, 94, 601, 79, 558, 471, 61,
106267 /* 560 */ 601, 79, 421, 949, 350, 949, 34, 56, 57, 47,
106268 /* 570 */ 582, 581, 583, 583, 54, 54, 55, 55, 55, 55,
106269 /* 580 */ 535, 53, 53, 53, 53, 52, 52, 51, 51, 51,
106270 /* 590 */ 50, 238, 313, 307, 424, 394, 272, 49, 46, 147,
106271 /* 600 */ 349, 322, 4, 411, 491, 312, 321, 425, 568, 492,
106272 /* 610 */ 216, 264, 407, 575, 574, 429, 66, 549, 414, 621,
106273 /* 620 */ 540, 602, 590, 584, 13, 603, 621, 601, 72, 12,
106274 /* 630 */ 618, 617, 616, 202, 210, 621, 546, 469, 422, 319,
106275 /* 640 */ 148, 56, 57, 47, 582, 581, 583, 583, 54, 54,
106276 /* 650 */ 55, 55, 55, 55, 338, 53, 53, 53, 53, 52,
106277 /* 660 */ 52, 51, 51, 51, 50, 238, 313, 600, 600, 411,
106278 /* 670 */ 39, 21, 37, 170, 237, 875, 411, 572, 572, 201,
106279 /* 680 */ 144, 473, 538, 331, 414, 474, 143, 146, 630, 628,
106280 /* 690 */ 334, 414, 353, 601, 68, 168, 590, 584, 132, 365,
106281 /* 700 */ 601, 96, 307, 423, 530, 336, 49, 46, 147, 568,
106282 /* 710 */ 406, 216, 549, 360, 529, 56, 57, 47, 582, 581,
106283 /* 720 */ 583, 583, 54, 54, 55, 55, 55, 55, 411, 53,
106284 /* 730 */ 53, 53, 53, 52, 52, 51, 51, 51, 50, 238,
106285 /* 740 */ 313, 411, 605, 414, 484, 510, 172, 422, 597, 318,
106286 /* 750 */ 496, 485, 601, 99, 411, 142, 414, 411, 231, 411,
106287 /* 760 */ 540, 411, 359, 629, 2, 601, 97, 426, 308, 414,
106288 /* 770 */ 590, 584, 414, 20, 414, 621, 414, 621, 601, 106,
106289 /* 780 */ 503, 601, 105, 601, 108, 601, 109, 204, 28, 56,
106290 /* 790 */ 57, 47, 582, 581, 583, 583, 54, 54, 55, 55,
106291 /* 800 */ 55, 55, 411, 53, 53, 53, 53, 52, 52, 51,
106292 /* 810 */ 51, 51, 50, 238, 313, 411, 597, 414, 411, 276,
106293 /* 820 */ 214, 600, 411, 366, 213, 381, 601, 134, 274, 500,
106294 /* 830 */ 414, 167, 130, 414, 621, 411, 354, 414, 376, 601,
106295 /* 840 */ 135, 129, 601, 100, 590, 584, 601, 104, 522, 521,
106296 /* 850 */ 414, 621, 224, 273, 600, 167, 327, 282, 600, 601,
106297 /* 860 */ 103, 468, 521, 56, 57, 47, 582, 581, 583, 583,
106298 /* 870 */ 54, 54, 55, 55, 55, 55, 411, 53, 53, 53,
106299 /* 880 */ 53, 52, 52, 51, 51, 51, 50, 238, 313, 411,
106300 /* 890 */ 27, 414, 411, 375, 276, 167, 359, 544, 50, 238,
106301 /* 900 */ 601, 95, 128, 223, 414, 411, 165, 414, 411, 621,
106302 /* 910 */ 411, 621, 612, 601, 102, 372, 601, 76, 590, 584,
106303 /* 920 */ 414, 570, 236, 414, 470, 414, 167, 621, 188, 601,
106304 /* 930 */ 98, 225, 601, 138, 601, 137, 232, 56, 45, 47,
106305 /* 940 */ 582, 581, 583, 583, 54, 54, 55, 55, 55, 55,
106306 /* 950 */ 411, 53, 53, 53, 53, 52, 52, 51, 51, 51,
106307 /* 960 */ 50, 238, 313, 276, 276, 414, 411, 276, 544, 459,
106308 /* 970 */ 359, 171, 209, 479, 601, 136, 628, 334, 621, 621,
106309 /* 980 */ 125, 414, 621, 368, 411, 621, 257, 540, 589, 588,
106310 /* 990 */ 601, 75, 590, 584, 458, 446, 23, 23, 124, 414,
106311 /* 1000 */ 326, 325, 621, 427, 324, 309, 600, 288, 601, 92,
106312 /* 1010 */ 586, 585, 57, 47, 582, 581, 583, 583, 54, 54,
106313 /* 1020 */ 55, 55, 55, 55, 411, 53, 53, 53, 53, 52,
106314 /* 1030 */ 52, 51, 51, 51, 50, 238, 313, 587, 411, 414,
106315 /* 1040 */ 411, 207, 611, 476, 171, 472, 160, 123, 601, 91,
106316 /* 1050 */ 323, 261, 15, 414, 464, 414, 411, 621, 411, 354,
106317 /* 1060 */ 222, 411, 601, 74, 601, 90, 590, 584, 159, 264,
106318 /* 1070 */ 158, 414, 461, 414, 621, 600, 414, 121, 120, 25,
106319 /* 1080 */ 601, 89, 601, 101, 621, 601, 88, 47, 582, 581,
106320 /* 1090 */ 583, 583, 54, 54, 55, 55, 55, 55, 544, 53,
106321 /* 1100 */ 53, 53, 53, 52, 52, 51, 51, 51, 50, 238,
106322 /* 1110 */ 43, 405, 263, 3, 610, 264, 140, 415, 622, 24,
106323 /* 1120 */ 410, 11, 456, 594, 118, 155, 219, 452, 408, 621,
106324 /* 1130 */ 621, 621, 156, 43, 405, 621, 3, 286, 621, 113,
106325 /* 1140 */ 415, 622, 111, 445, 411, 400, 557, 403, 545, 10,
106326 /* 1150 */ 411, 408, 264, 110, 205, 436, 541, 566, 453, 414,
106327 /* 1160 */ 621, 621, 63, 621, 435, 414, 411, 621, 601, 94,
106328 /* 1170 */ 403, 621, 411, 337, 601, 86, 150, 40, 41, 534,
106329 /* 1180 */ 566, 414, 242, 264, 42, 413, 412, 414, 600, 595,
106330 /* 1190 */ 601, 85, 191, 333, 107, 451, 601, 84, 621, 539,
106331 /* 1200 */ 40, 41, 420, 230, 411, 149, 316, 42, 413, 412,
106332 /* 1210 */ 398, 127, 595, 315, 621, 399, 278, 625, 181, 414,
106333 /* 1220 */ 593, 593, 593, 592, 591, 14, 450, 411, 601, 71,
106334 /* 1230 */ 240, 621, 43, 405, 264, 3, 615, 180, 264, 415,
106335 /* 1240 */ 622, 614, 414, 593, 593, 593, 592, 591, 14, 621,
106336 /* 1250 */ 408, 601, 70, 621, 417, 33, 405, 613, 3, 411,
106337 /* 1260 */ 264, 411, 415, 622, 418, 626, 178, 509, 8, 403,
106338 /* 1270 */ 241, 416, 126, 408, 414, 621, 414, 449, 208, 566,
106339 /* 1280 */ 240, 221, 621, 601, 83, 601, 82, 599, 297, 277,
106340 /* 1290 */ 296, 30, 403, 31, 395, 264, 295, 397, 489, 40,
106341 /* 1300 */ 41, 411, 566, 220, 621, 294, 42, 413, 412, 271,
106342 /* 1310 */ 621, 595, 600, 621, 59, 60, 414, 269, 267, 623,
106343 /* 1320 */ 622, 36, 40, 41, 621, 601, 81, 598, 235, 42,
106344 /* 1330 */ 413, 412, 621, 621, 595, 265, 344, 411, 248, 556,
106345 /* 1340 */ 173, 185, 593, 593, 593, 592, 591, 14, 218, 29,
106346 /* 1350 */ 621, 543, 414, 305, 304, 303, 179, 301, 411, 566,
106347 /* 1360 */ 454, 601, 80, 289, 335, 593, 593, 593, 592, 591,
106348 /* 1370 */ 14, 411, 287, 414, 151, 392, 246, 260, 411, 196,
106349 /* 1380 */ 195, 523, 601, 69, 411, 245, 414, 526, 537, 285,
106350 /* 1390 */ 389, 595, 621, 414, 536, 601, 17, 362, 153, 414,
106351 /* 1400 */ 466, 463, 601, 78, 154, 414, 462, 152, 601, 77,
106352 /* 1410 */ 355, 255, 621, 455, 601, 9, 621, 386, 444, 517,
106353 /* 1420 */ 247, 621, 593, 593, 593, 621, 621, 244, 621, 243,
106354 /* 1430 */ 430, 518, 292, 621, 329, 621, 145, 393, 280, 513,
106355 /* 1440 */ 291, 131, 621, 514, 621, 621, 311, 621, 259, 346,
106356 /* 1450 */ 249, 621, 621, 229, 314, 621, 228, 512, 227, 240,
106357 /* 1460 */ 494, 488, 310, 164, 487, 486, 373, 480, 163, 262,
106358 /* 1470 */ 369, 371, 162, 26, 212, 478, 477, 161, 141, 363,
106359 /* 1480 */ 467, 122, 339, 187, 119, 348, 347, 117, 116, 115,
106360 /* 1490 */ 114, 112, 182, 457, 320, 22, 433, 432, 448, 19,
106361 /* 1500 */ 609, 431, 428, 62, 193, 596, 573, 298, 555, 552,
106362 /* 1510 */ 571, 404, 290, 380, 498, 510, 495, 306, 281, 499,
106363 /* 1520 */ 250, 5, 497, 460, 345, 447, 569, 550, 238, 299,
106364 /* 1530 */ 527, 525, 508, 961, 502, 501, 961, 401, 961, 211,
106365 /* 1540 */ 490, 356, 256, 961, 483, 961, 961, 961, 961, 961,
106366 /* 1550 */ 961, 961, 961, 961, 961, 961, 370,
106368 static const YYCODETYPE yy_lookahead[] = {
106369 /* 0 */ 19, 142, 143, 144, 145, 24, 1, 26, 77, 78,
106370 /* 10 */ 79, 80, 81, 82, 83, 84, 85, 86, 87, 88,
106371 /* 20 */ 89, 90, 91, 92, 15, 98, 26, 27, 7, 8,
106372 /* 30 */ 49, 50, 77, 78, 79, 80, 109, 82, 83, 84,
106373 /* 40 */ 85, 86, 87, 88, 89, 90, 91, 92, 22, 68,
106374 /* 50 */ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78,
106375 /* 60 */ 79, 80, 23, 82, 83, 84, 85, 86, 87, 88,
106376 /* 70 */ 89, 90, 91, 92, 19, 94, 112, 19, 114, 115,
106377 /* 80 */ 25, 82, 83, 84, 85, 86, 87, 88, 89, 90,
106378 /* 90 */ 91, 92, 19, 22, 94, 95, 96, 150, 150, 99,
106379 /* 100 */ 100, 101, 76, 150, 49, 50, 105, 106, 107, 54,
106380 /* 110 */ 110, 158, 165, 165, 161, 162, 26, 27, 165, 113,
106381 /* 120 */ 16, 174, 175, 68, 69, 70, 71, 72, 73, 74,
106382 /* 130 */ 75, 76, 77, 78, 79, 80, 118, 82, 83, 84,
106383 /* 140 */ 85, 86, 87, 88, 89, 90, 91, 92, 19, 23,
106384 /* 150 */ 92, 97, 98, 24, 96, 97, 98, 99, 100, 101,
106385 /* 160 */ 102, 25, 97, 216, 60, 92, 62, 109, 221, 25,
106386 /* 170 */ 97, 98, 99, 100, 101, 102, 86, 87, 49, 50,
106387 /* 180 */ 118, 116, 109, 25, 94, 95, 32, 97, 88, 89,
106388 /* 190 */ 90, 91, 92, 128, 104, 41, 106, 68, 69, 70,
106389 /* 200 */ 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
106390 /* 210 */ 11, 82, 83, 84, 85, 86, 87, 88, 89, 90,
106391 /* 220 */ 91, 92, 19, 19, 86, 87, 88, 89, 90, 91,
106392 /* 230 */ 92, 27, 96, 150, 66, 99, 100, 101, 112, 150,
106393 /* 240 */ 114, 115, 138, 150, 161, 162, 110, 103, 165, 222,
106394 /* 250 */ 223, 224, 49, 50, 165, 22, 57, 24, 165, 170,
106395 /* 260 */ 171, 118, 94, 170, 171, 23, 98, 25, 185, 186,
106396 /* 270 */ 243, 68, 69, 70, 71, 72, 73, 74, 75, 76,
106397 /* 280 */ 77, 78, 79, 80, 126, 82, 83, 84, 85, 86,
106398 /* 290 */ 87, 88, 89, 90, 91, 92, 19, 129, 130, 131,
106399 /* 300 */ 88, 23, 172, 173, 105, 106, 107, 150, 22, 26,
106400 /* 310 */ 27, 181, 26, 27, 22, 116, 26, 27, 26, 230,
106401 /* 320 */ 231, 197, 165, 230, 231, 113, 49, 50, 204, 117,
106402 /* 330 */ 96, 174, 175, 99, 100, 101, 22, 26, 27, 136,
106403 /* 340 */ 26, 27, 118, 16, 110, 68, 69, 70, 71, 72,
106404 /* 350 */ 73, 74, 75, 76, 77, 78, 79, 80, 118, 82,
106405 /* 360 */ 83, 84, 85, 86, 87, 88, 89, 90, 91, 92,
106406 /* 370 */ 19, 214, 215, 150, 23, 23, 155, 94, 95, 22,
106407 /* 380 */ 94, 95, 116, 160, 94, 95, 94, 60, 165, 62,
106408 /* 390 */ 112, 26, 114, 115, 128, 23, 36, 174, 175, 88,
106409 /* 400 */ 49, 50, 57, 120, 22, 94, 95, 23, 94, 95,
106410 /* 410 */ 120, 51, 25, 136, 169, 170, 171, 194, 58, 68,
106411 /* 420 */ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78,
106412 /* 430 */ 79, 80, 23, 82, 83, 84, 85, 86, 87, 88,
106413 /* 440 */ 89, 90, 91, 92, 19, 150, 12, 12, 23, 228,
106414 /* 450 */ 105, 106, 107, 23, 233, 25, 165, 19, 150, 94,
106415 /* 460 */ 165, 116, 28, 28, 112, 174, 114, 115, 108, 174,
106416 /* 470 */ 175, 26, 27, 165, 49, 50, 231, 11, 44, 44,
106417 /* 480 */ 46, 46, 174, 175, 112, 160, 114, 115, 50, 22,
106418 /* 490 */ 23, 57, 25, 68, 69, 70, 71, 72, 73, 74,
106419 /* 500 */ 75, 76, 77, 78, 79, 80, 119, 82, 83, 84,
106420 /* 510 */ 85, 86, 87, 88, 89, 90, 91, 92, 19, 194,
106421 /* 520 */ 225, 23, 23, 215, 19, 95, 105, 106, 107, 150,
106422 /* 530 */ 23, 150, 27, 23, 67, 25, 150, 206, 207, 94,
106423 /* 540 */ 95, 166, 104, 218, 165, 22, 165, 109, 49, 50,
106424 /* 550 */ 120, 165, 25, 174, 175, 174, 175, 23, 21, 234,
106425 /* 560 */ 174, 175, 22, 23, 239, 25, 25, 68, 69, 70,
106426 /* 570 */ 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
106427 /* 580 */ 205, 82, 83, 84, 85, 86, 87, 88, 89, 90,
106428 /* 590 */ 91, 92, 19, 22, 23, 216, 23, 222, 223, 224,
106429 /* 600 */ 63, 220, 35, 150, 150, 163, 220, 67, 166, 167,
106430 /* 610 */ 168, 150, 169, 170, 171, 161, 162, 25, 165, 165,
106431 /* 620 */ 150, 113, 49, 50, 25, 117, 165, 174, 175, 35,
106432 /* 630 */ 7, 8, 9, 160, 160, 165, 120, 100, 67, 247,
106433 /* 640 */ 248, 68, 69, 70, 71, 72, 73, 74, 75, 76,
106434 /* 650 */ 77, 78, 79, 80, 193, 82, 83, 84, 85, 86,
106435 /* 660 */ 87, 88, 89, 90, 91, 92, 19, 194, 194, 150,
106436 /* 670 */ 135, 24, 137, 35, 231, 138, 150, 129, 130, 206,
106437 /* 680 */ 207, 30, 27, 213, 165, 34, 118, 95, 0, 1,
106438 /* 690 */ 2, 165, 218, 174, 175, 50, 49, 50, 22, 48,
106439 /* 700 */ 174, 175, 22, 23, 23, 244, 222, 223, 224, 166,
106440 /* 710 */ 167, 168, 120, 239, 23, 68, 69, 70, 71, 72,
106441 /* 720 */ 73, 74, 75, 76, 77, 78, 79, 80, 150, 82,
106442 /* 730 */ 83, 84, 85, 86, 87, 88, 89, 90, 91, 92,
106443 /* 740 */ 19, 150, 173, 165, 181, 182, 24, 67, 26, 104,
106444 /* 750 */ 181, 188, 174, 175, 150, 39, 165, 150, 52, 150,
106445 /* 760 */ 150, 150, 150, 144, 145, 174, 175, 249, 250, 165,
106446 /* 770 */ 49, 50, 165, 52, 165, 165, 165, 165, 174, 175,
106447 /* 780 */ 29, 174, 175, 174, 175, 174, 175, 160, 22, 68,
106448 /* 790 */ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78,
106449 /* 800 */ 79, 80, 150, 82, 83, 84, 85, 86, 87, 88,
106450 /* 810 */ 89, 90, 91, 92, 19, 150, 94, 165, 150, 150,
106451 /* 820 */ 160, 194, 150, 213, 160, 52, 174, 175, 23, 23,
106452 /* 830 */ 165, 25, 22, 165, 165, 150, 150, 165, 52, 174,
106453 /* 840 */ 175, 22, 174, 175, 49, 50, 174, 175, 190, 191,
106454 /* 850 */ 165, 165, 240, 23, 194, 25, 187, 109, 194, 174,
106455 /* 860 */ 175, 190, 191, 68, 69, 70, 71, 72, 73, 74,
106456 /* 870 */ 75, 76, 77, 78, 79, 80, 150, 82, 83, 84,
106457 /* 880 */ 85, 86, 87, 88, 89, 90, 91, 92, 19, 150,
106458 /* 890 */ 22, 165, 150, 23, 150, 25, 150, 166, 91, 92,
106459 /* 900 */ 174, 175, 22, 217, 165, 150, 102, 165, 150, 165,
106460 /* 910 */ 150, 165, 150, 174, 175, 19, 174, 175, 49, 50,
106461 /* 920 */ 165, 86, 87, 165, 23, 165, 25, 165, 24, 174,
106462 /* 930 */ 175, 187, 174, 175, 174, 175, 205, 68, 69, 70,
106463 /* 940 */ 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
106464 /* 950 */ 150, 82, 83, 84, 85, 86, 87, 88, 89, 90,
106465 /* 960 */ 91, 92, 19, 150, 150, 165, 150, 150, 166, 23,
106466 /* 970 */ 150, 25, 160, 20, 174, 175, 1, 2, 165, 165,
106467 /* 980 */ 104, 165, 165, 43, 150, 165, 240, 150, 49, 50,
106468 /* 990 */ 174, 175, 49, 50, 23, 23, 25, 25, 53, 165,
106469 /* 1000 */ 187, 187, 165, 23, 187, 25, 194, 205, 174, 175,
106470 /* 1010 */ 71, 72, 69, 70, 71, 72, 73, 74, 75, 76,
106471 /* 1020 */ 77, 78, 79, 80, 150, 82, 83, 84, 85, 86,
106472 /* 1030 */ 87, 88, 89, 90, 91, 92, 19, 98, 150, 165,
106473 /* 1040 */ 150, 160, 150, 59, 25, 53, 104, 22, 174, 175,
106474 /* 1050 */ 213, 138, 5, 165, 1, 165, 150, 165, 150, 150,
106475 /* 1060 */ 240, 150, 174, 175, 174, 175, 49, 50, 118, 150,
106476 /* 1070 */ 35, 165, 27, 165, 165, 194, 165, 108, 127, 76,
106477 /* 1080 */ 174, 175, 174, 175, 165, 174, 175, 70, 71, 72,
106478 /* 1090 */ 73, 74, 75, 76, 77, 78, 79, 80, 166, 82,
106479 /* 1100 */ 83, 84, 85, 86, 87, 88, 89, 90, 91, 92,
106480 /* 1110 */ 19, 20, 193, 22, 150, 150, 150, 26, 27, 76,
106481 /* 1120 */ 150, 22, 1, 150, 119, 121, 217, 20, 37, 165,
106482 /* 1130 */ 165, 165, 16, 19, 20, 165, 22, 205, 165, 119,
106483 /* 1140 */ 26, 27, 108, 128, 150, 150, 150, 56, 150, 22,
106484 /* 1150 */ 150, 37, 150, 127, 160, 23, 150, 66, 193, 165,
106485 /* 1160 */ 165, 165, 16, 165, 23, 165, 150, 165, 174, 175,
106486 /* 1170 */ 56, 165, 150, 65, 174, 175, 15, 86, 87, 88,
106487 /* 1180 */ 66, 165, 140, 150, 93, 94, 95, 165, 194, 98,
106488 /* 1190 */ 174, 175, 22, 3, 164, 193, 174, 175, 165, 150,
106489 /* 1200 */ 86, 87, 4, 180, 150, 248, 251, 93, 94, 95,
106490 /* 1210 */ 216, 180, 98, 251, 165, 221, 150, 149, 6, 165,
106491 /* 1220 */ 129, 130, 131, 132, 133, 134, 193, 150, 174, 175,
106492 /* 1230 */ 116, 165, 19, 20, 150, 22, 149, 151, 150, 26,
106493 /* 1240 */ 27, 149, 165, 129, 130, 131, 132, 133, 134, 165,
106494 /* 1250 */ 37, 174, 175, 165, 149, 19, 20, 13, 22, 150,
106495 /* 1260 */ 150, 150, 26, 27, 146, 147, 151, 150, 25, 56,
106496 /* 1270 */ 152, 159, 154, 37, 165, 165, 165, 193, 160, 66,
106497 /* 1280 */ 116, 193, 165, 174, 175, 174, 175, 194, 199, 150,
106498 /* 1290 */ 200, 126, 56, 124, 123, 150, 201, 122, 150, 86,
106499 /* 1300 */ 87, 150, 66, 193, 165, 202, 93, 94, 95, 150,
106500 /* 1310 */ 165, 98, 194, 165, 125, 22, 165, 150, 150, 26,
106501 /* 1320 */ 27, 135, 86, 87, 165, 174, 175, 203, 226, 93,
106502 /* 1330 */ 94, 95, 165, 165, 98, 150, 218, 150, 193, 157,
106503 /* 1340 */ 118, 157, 129, 130, 131, 132, 133, 134, 5, 104,
106504 /* 1350 */ 165, 211, 165, 10, 11, 12, 13, 14, 150, 66,
106505 /* 1360 */ 17, 174, 175, 210, 246, 129, 130, 131, 132, 133,
106506 /* 1370 */ 134, 150, 210, 165, 31, 121, 33, 150, 150, 86,
106507 /* 1380 */ 87, 176, 174, 175, 150, 42, 165, 94, 211, 210,
106508 /* 1390 */ 150, 98, 165, 165, 211, 174, 175, 150, 55, 165,
106509 /* 1400 */ 57, 150, 174, 175, 61, 165, 150, 64, 174, 175,
106510 /* 1410 */ 150, 150, 165, 150, 174, 175, 165, 104, 150, 184,
106511 /* 1420 */ 150, 165, 129, 130, 131, 165, 165, 150, 165, 150,
106512 /* 1430 */ 150, 176, 150, 165, 47, 165, 150, 150, 176, 103,
106513 /* 1440 */ 150, 22, 165, 178, 165, 165, 179, 165, 105, 106,
106514 /* 1450 */ 107, 165, 165, 229, 111, 165, 92, 176, 229, 116,
106515 /* 1460 */ 184, 176, 179, 156, 176, 176, 18, 157, 156, 237,
106516 /* 1470 */ 45, 157, 156, 135, 157, 157, 238, 156, 68, 157,
106517 /* 1480 */ 189, 189, 139, 219, 22, 157, 18, 192, 192, 192,
106518 /* 1490 */ 192, 189, 219, 199, 157, 242, 40, 157, 199, 242,
106519 /* 1500 */ 153, 157, 38, 245, 196, 166, 232, 198, 177, 177,
106520 /* 1510 */ 232, 227, 209, 178, 166, 182, 166, 148, 177, 177,
106521 /* 1520 */ 209, 196, 177, 199, 209, 199, 166, 208, 92, 195,
106522 /* 1530 */ 174, 174, 183, 252, 183, 183, 252, 191, 252, 235,
106523 /* 1540 */ 186, 241, 241, 252, 186, 252, 252, 252, 252, 252,
106524 /* 1550 */ 252, 252, 252, 252, 252, 252, 236,
106526 #define YY_SHIFT_USE_DFLT (-74)
106527 #define YY_SHIFT_COUNT (418)
106528 #define YY_SHIFT_MIN (-73)
106529 #define YY_SHIFT_MAX (1468)
106530 static const short yy_shift_ofst[] = {
106531 /* 0 */ 975, 1114, 1343, 1114, 1213, 1213, 90, 90, 0, -19,
106532 /* 10 */ 1213, 1213, 1213, 1213, 1213, 345, 445, 721, 1091, 1213,
106533 /* 20 */ 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
106534 /* 30 */ 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
106535 /* 40 */ 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1236, 1213, 1213,
106536 /* 50 */ 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
106537 /* 60 */ 1213, 199, 445, 445, 835, 835, 365, 1164, 55, 647,
106538 /* 70 */ 573, 499, 425, 351, 277, 203, 129, 795, 795, 795,
106539 /* 80 */ 795, 795, 795, 795, 795, 795, 795, 795, 795, 795,
106540 /* 90 */ 795, 795, 795, 795, 795, 869, 795, 943, 1017, 1017,
106541 /* 100 */ -69, -45, -45, -45, -45, -45, -1, 58, 138, 100,
106542 /* 110 */ 445, 445, 445, 445, 445, 445, 445, 445, 445, 445,
106543 /* 120 */ 445, 445, 445, 445, 445, 445, 537, 438, 445, 445,
106544 /* 130 */ 445, 445, 445, 365, 807, 1436, -74, -74, -74, 1293,
106545 /* 140 */ 73, 434, 434, 311, 314, 290, 283, 286, 540, 467,
106546 /* 150 */ 445, 445, 445, 445, 445, 445, 445, 445, 445, 445,
106547 /* 160 */ 445, 445, 445, 445, 445, 445, 445, 445, 445, 445,
106548 /* 170 */ 445, 445, 445, 445, 445, 445, 445, 445, 445, 445,
106549 /* 180 */ 445, 445, 65, 722, 722, 722, 688, 266, 1164, 1164,
106550 /* 190 */ 1164, -74, -74, -74, 136, 168, 168, 234, 360, 360,
106551 /* 200 */ 360, 430, 372, 435, 352, 278, 126, -36, -36, -36,
106552 /* 210 */ -36, 421, 651, -36, -36, 592, 292, 212, 623, 158,
106553 /* 220 */ 204, 204, 505, 158, 505, 144, 365, 154, 365, 154,
106554 /* 230 */ 645, 154, 204, 154, 154, 535, 548, 548, 365, 387,
106555 /* 240 */ 508, 233, 1464, 1222, 1222, 1456, 1456, 1222, 1462, 1410,
106556 /* 250 */ 1165, 1468, 1468, 1468, 1468, 1222, 1165, 1462, 1410, 1410,
106557 /* 260 */ 1222, 1448, 1338, 1425, 1222, 1222, 1448, 1222, 1448, 1222,
106558 /* 270 */ 1448, 1419, 1313, 1313, 1313, 1387, 1364, 1364, 1419, 1313,
106559 /* 280 */ 1336, 1313, 1387, 1313, 1313, 1254, 1245, 1254, 1245, 1254,
106560 /* 290 */ 1245, 1222, 1222, 1186, 1189, 1175, 1169, 1171, 1165, 1164,
106561 /* 300 */ 1243, 1244, 1244, 1212, 1212, 1212, 1212, -74, -74, -74,
106562 /* 310 */ -74, -74, -74, 939, 104, 680, 571, 327, 1, 980,
106563 /* 320 */ 26, 972, 971, 946, 901, 870, 830, 806, 54, 21,
106564 /* 330 */ -73, 510, 242, 1198, 1190, 1170, 1042, 1161, 1108, 1146,
106565 /* 340 */ 1141, 1132, 1015, 1127, 1026, 1034, 1020, 1107, 1004, 1116,
106566 /* 350 */ 1121, 1005, 1099, 951, 1043, 1003, 969, 1045, 1035, 950,
106567 /* 360 */ 1053, 1047, 1025, 942, 913, 992, 1019, 945, 984, 940,
106568 /* 370 */ 876, 904, 953, 896, 748, 804, 880, 786, 868, 819,
106569 /* 380 */ 805, 810, 773, 751, 766, 706, 716, 691, 681, 568,
106570 /* 390 */ 655, 638, 676, 516, 541, 594, 599, 567, 541, 534,
106571 /* 400 */ 507, 527, 498, 523, 466, 382, 409, 384, 357, 6,
106572 /* 410 */ 240, 224, 143, 62, 18, 71, 39, 9, 5,
106574 #define YY_REDUCE_USE_DFLT (-142)
106575 #define YY_REDUCE_COUNT (312)
106576 #define YY_REDUCE_MIN (-141)
106577 #define YY_REDUCE_MAX (1369)
106578 static const short yy_reduce_ofst[] = {
106579 /* 0 */ -141, 994, 1118, 223, 157, -53, 93, 89, 83, 375,
106580 /* 10 */ 386, 381, 379, 308, 295, 325, -47, 27, 1240, 1234,
106581 /* 20 */ 1228, 1221, 1208, 1187, 1151, 1111, 1109, 1077, 1054, 1022,
106582 /* 30 */ 1016, 1000, 911, 908, 906, 890, 888, 874, 834, 816,
106583 /* 40 */ 800, 760, 758, 755, 742, 739, 726, 685, 672, 668,
106584 /* 50 */ 665, 652, 611, 609, 607, 604, 591, 578, 526, 519,
106585 /* 60 */ 453, 474, 454, 461, 443, 245, 442, 473, 484, 484,
106586 /* 70 */ 484, 484, 484, 484, 484, 484, 484, 484, 484, 484,
106587 /* 80 */ 484, 484, 484, 484, 484, 484, 484, 484, 484, 484,
106588 /* 90 */ 484, 484, 484, 484, 484, 484, 484, 484, 484, 484,
106589 /* 100 */ 484, 484, 484, 484, 484, 484, 484, 130, 484, 484,
106590 /* 110 */ 1145, 909, 1110, 1088, 1084, 1033, 1002, 965, 820, 837,
106591 /* 120 */ 746, 686, 612, 817, 610, 919, 221, 563, 814, 813,
106592 /* 130 */ 744, 669, 470, 543, 484, 484, 484, 484, 484, 291,
106593 /* 140 */ 569, 671, 658, 970, 1290, 1287, 1286, 1282, 518, 518,
106594 /* 150 */ 1280, 1279, 1277, 1270, 1268, 1263, 1261, 1260, 1256, 1251,
106595 /* 160 */ 1247, 1227, 1185, 1168, 1167, 1159, 1148, 1139, 1117, 1066,
106596 /* 170 */ 1049, 1006, 998, 996, 995, 973, 970, 966, 964, 892,
106597 /* 180 */ 762, -52, 881, 932, 802, 731, 619, 812, 664, 660,
106598 /* 190 */ 627, 392, 331, 124, 1358, 1357, 1356, 1354, 1352, 1351,
106599 /* 200 */ 1349, 1319, 1334, 1346, 1334, 1334, 1334, 1334, 1334, 1334,
106600 /* 210 */ 1334, 1320, 1304, 1334, 1334, 1319, 1360, 1325, 1369, 1326,
106601 /* 220 */ 1315, 1311, 1301, 1324, 1300, 1335, 1350, 1345, 1348, 1342,
106602 /* 230 */ 1333, 1341, 1303, 1332, 1331, 1284, 1278, 1274, 1339, 1309,
106603 /* 240 */ 1308, 1347, 1258, 1344, 1340, 1257, 1253, 1337, 1273, 1302,
106604 /* 250 */ 1299, 1298, 1297, 1296, 1295, 1328, 1294, 1264, 1292, 1291,
106605 /* 260 */ 1322, 1321, 1238, 1232, 1318, 1317, 1316, 1314, 1312, 1310,
106606 /* 270 */ 1307, 1283, 1289, 1288, 1285, 1276, 1229, 1224, 1267, 1281,
106607 /* 280 */ 1265, 1262, 1235, 1255, 1205, 1183, 1179, 1177, 1162, 1140,
106608 /* 290 */ 1153, 1184, 1182, 1102, 1124, 1103, 1095, 1090, 1089, 1093,
106609 /* 300 */ 1112, 1115, 1086, 1105, 1092, 1087, 1068, 962, 955, 957,
106610 /* 310 */ 1031, 1023, 1030,
106612 static const YYACTIONTYPE yy_default[] = {
106613 /* 0 */ 635, 870, 959, 959, 959, 870, 899, 899, 959, 759,
106614 /* 10 */ 959, 959, 959, 959, 868, 959, 959, 933, 959, 959,
106615 /* 20 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 959,
106616 /* 30 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 959,
106617 /* 40 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 959,
106618 /* 50 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 959,
106619 /* 60 */ 959, 959, 959, 959, 899, 899, 674, 763, 794, 959,
106620 /* 70 */ 959, 959, 959, 959, 959, 959, 959, 932, 934, 809,
106621 /* 80 */ 808, 802, 801, 912, 774, 799, 792, 785, 796, 871,
106622 /* 90 */ 864, 865, 863, 867, 872, 959, 795, 831, 848, 830,
106623 /* 100 */ 842, 847, 854, 846, 843, 833, 832, 666, 834, 835,
106624 /* 110 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 959,
106625 /* 120 */ 959, 959, 959, 959, 959, 959, 661, 728, 959, 959,
106626 /* 130 */ 959, 959, 959, 959, 836, 837, 851, 850, 849, 959,
106627 /* 140 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 959,
106628 /* 150 */ 959, 939, 937, 959, 883, 959, 959, 959, 959, 959,
106629 /* 160 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 959,
106630 /* 170 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 959,
106631 /* 180 */ 959, 641, 959, 759, 759, 759, 635, 959, 959, 959,
106632 /* 190 */ 959, 951, 763, 753, 719, 959, 959, 959, 959, 959,
106633 /* 200 */ 959, 959, 959, 959, 959, 959, 959, 804, 742, 922,
106634 /* 210 */ 924, 959, 905, 740, 663, 761, 676, 751, 643, 798,
106635 /* 220 */ 776, 776, 917, 798, 917, 700, 959, 788, 959, 788,
106636 /* 230 */ 697, 788, 776, 788, 788, 866, 959, 959, 959, 760,
106637 /* 240 */ 751, 959, 944, 767, 767, 936, 936, 767, 810, 732,
106638 /* 250 */ 798, 739, 739, 739, 739, 767, 798, 810, 732, 732,
106639 /* 260 */ 767, 658, 911, 909, 767, 767, 658, 767, 658, 767,
106640 /* 270 */ 658, 876, 730, 730, 730, 715, 880, 880, 876, 730,
106641 /* 280 */ 700, 730, 715, 730, 730, 780, 775, 780, 775, 780,
106642 /* 290 */ 775, 767, 767, 959, 793, 781, 791, 789, 798, 959,
106643 /* 300 */ 718, 651, 651, 640, 640, 640, 640, 956, 956, 951,
106644 /* 310 */ 702, 702, 684, 959, 959, 959, 959, 959, 959, 959,
106645 /* 320 */ 885, 959, 959, 959, 959, 959, 959, 959, 959, 959,
106646 /* 330 */ 959, 959, 959, 959, 636, 946, 959, 959, 943, 959,
106647 /* 340 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 959,
106648 /* 350 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 915,
106649 /* 360 */ 959, 959, 959, 959, 959, 959, 908, 907, 959, 959,
106650 /* 370 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 959,
106651 /* 380 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 959,
106652 /* 390 */ 959, 959, 959, 959, 790, 959, 782, 959, 869, 959,
106653 /* 400 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 745,
106654 /* 410 */ 819, 959, 818, 822, 817, 668, 959, 649, 959, 632,
106655 /* 420 */ 637, 955, 958, 957, 954, 953, 952, 947, 945, 942,
106656 /* 430 */ 941, 940, 938, 935, 931, 889, 887, 894, 893, 892,
106657 /* 440 */ 891, 890, 888, 886, 884, 805, 803, 800, 797, 930,
106658 /* 450 */ 882, 741, 738, 737, 657, 948, 914, 923, 921, 811,
106659 /* 460 */ 920, 919, 918, 916, 913, 900, 807, 806, 733, 874,
106660 /* 470 */ 873, 660, 904, 903, 902, 906, 910, 901, 769, 659,
106661 /* 480 */ 656, 665, 722, 721, 729, 727, 726, 725, 724, 723,
106662 /* 490 */ 720, 667, 675, 686, 714, 699, 698, 879, 881, 878,
106663 /* 500 */ 877, 707, 706, 712, 711, 710, 709, 708, 705, 704,
106664 /* 510 */ 703, 696, 695, 701, 694, 717, 716, 713, 693, 736,
106665 /* 520 */ 735, 734, 731, 692, 691, 690, 822, 689, 688, 828,
106666 /* 530 */ 827, 815, 858, 756, 755, 754, 766, 765, 778, 777,
106667 /* 540 */ 813, 812, 779, 764, 758, 757, 773, 772, 771, 770,
106668 /* 550 */ 762, 752, 784, 787, 786, 783, 860, 768, 857, 929,
106669 /* 560 */ 928, 927, 926, 925, 862, 861, 829, 826, 679, 680,
106670 /* 570 */ 898, 896, 897, 895, 682, 681, 678, 677, 859, 747,
106671 /* 580 */ 746, 855, 852, 844, 840, 856, 853, 845, 841, 839,
106672 /* 590 */ 838, 824, 823, 821, 820, 816, 825, 670, 748, 744,
106673 /* 600 */ 743, 814, 750, 749, 687, 685, 683, 664, 662, 655,
106674 /* 610 */ 653, 652, 654, 650, 648, 647, 646, 645, 644, 673,
106675 /* 620 */ 672, 671, 669, 668, 642, 639, 638, 634, 633, 631,
106678 /* The next table maps tokens into fallback tokens. If a construct
106679 ** like the following:
106681 ** %fallback ID X Y Z.
106683 ** appears in the grammar, then ID becomes a fallback token for X, Y,
106684 ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
106685 ** but it does not parse, the type of the token is changed to ID and
106686 ** the parse is retried before an error is thrown.
106688 #ifdef YYFALLBACK
106689 static const YYCODETYPE yyFallback[] = {
106690 0, /* $ => nothing */
106691 0, /* SEMI => nothing */
106692 26, /* EXPLAIN => ID */
106693 26, /* QUERY => ID */
106694 26, /* PLAN => ID */
106695 26, /* BEGIN => ID */
106696 0, /* TRANSACTION => nothing */
106697 26, /* DEFERRED => ID */
106698 26, /* IMMEDIATE => ID */
106699 26, /* EXCLUSIVE => ID */
106700 0, /* COMMIT => nothing */
106701 26, /* END => ID */
106702 26, /* ROLLBACK => ID */
106703 26, /* SAVEPOINT => ID */
106704 26, /* RELEASE => ID */
106705 0, /* TO => nothing */
106706 0, /* TABLE => nothing */
106707 0, /* CREATE => nothing */
106708 26, /* IF => ID */
106709 0, /* NOT => nothing */
106710 0, /* EXISTS => nothing */
106711 26, /* TEMP => ID */
106712 0, /* LP => nothing */
106713 0, /* RP => nothing */
106714 0, /* AS => nothing */
106715 0, /* COMMA => nothing */
106716 0, /* ID => nothing */
106717 0, /* INDEXED => nothing */
106718 26, /* ABORT => ID */
106719 26, /* ACTION => ID */
106720 26, /* AFTER => ID */
106721 26, /* ANALYZE => ID */
106722 26, /* ASC => ID */
106723 26, /* ATTACH => ID */
106724 26, /* BEFORE => ID */
106725 26, /* BY => ID */
106726 26, /* CASCADE => ID */
106727 26, /* CAST => ID */
106728 26, /* COLUMNKW => ID */
106729 26, /* CONFLICT => ID */
106730 26, /* DATABASE => ID */
106731 26, /* DESC => ID */
106732 26, /* DETACH => ID */
106733 26, /* EACH => ID */
106734 26, /* FAIL => ID */
106735 26, /* FOR => ID */
106736 26, /* IGNORE => ID */
106737 26, /* INITIALLY => ID */
106738 26, /* INSTEAD => ID */
106739 26, /* LIKE_KW => ID */
106740 26, /* MATCH => ID */
106741 26, /* NO => ID */
106742 26, /* KEY => ID */
106743 26, /* OF => ID */
106744 26, /* OFFSET => ID */
106745 26, /* PRAGMA => ID */
106746 26, /* RAISE => ID */
106747 26, /* REPLACE => ID */
106748 26, /* RESTRICT => ID */
106749 26, /* ROW => ID */
106750 26, /* TRIGGER => ID */
106751 26, /* VACUUM => ID */
106752 26, /* VIEW => ID */
106753 26, /* VIRTUAL => ID */
106754 26, /* REINDEX => ID */
106755 26, /* RENAME => ID */
106756 26, /* CTIME_KW => ID */
106758 #endif /* YYFALLBACK */
106760 /* The following structure represents a single element of the
106761 ** parser's stack. Information stored includes:
106763 ** + The state number for the parser at this level of the stack.
106765 ** + The value of the token stored at this level of the stack.
106766 ** (In other words, the "major" token.)
106768 ** + The semantic value stored at this level of the stack. This is
106769 ** the information used by the action routines in the grammar.
106770 ** It is sometimes called the "minor" token.
106772 struct yyStackEntry {
106773 YYACTIONTYPE stateno; /* The state-number */
106774 YYCODETYPE major; /* The major token value. This is the code
106775 ** number for the token at this stack level */
106776 YYMINORTYPE minor; /* The user-supplied minor token value. This
106777 ** is the value of the token */
106779 typedef struct yyStackEntry yyStackEntry;
106781 /* The state of the parser is completely contained in an instance of
106782 ** the following structure */
106783 struct yyParser {
106784 int yyidx; /* Index of top element in stack */
106785 #ifdef YYTRACKMAXSTACKDEPTH
106786 int yyidxMax; /* Maximum value of yyidx */
106787 #endif
106788 int yyerrcnt; /* Shifts left before out of the error */
106789 sqlite3ParserARG_SDECL /* A place to hold %extra_argument */
106790 #if YYSTACKDEPTH<=0
106791 int yystksz; /* Current side of the stack */
106792 yyStackEntry *yystack; /* The parser's stack */
106793 #else
106794 yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */
106795 #endif
106797 typedef struct yyParser yyParser;
106799 #ifndef NDEBUG
106800 /* #include <stdio.h> */
106801 static FILE *yyTraceFILE = 0;
106802 static char *yyTracePrompt = 0;
106803 #endif /* NDEBUG */
106805 #ifndef NDEBUG
106807 ** Turn parser tracing on by giving a stream to which to write the trace
106808 ** and a prompt to preface each trace message. Tracing is turned off
106809 ** by making either argument NULL
106811 ** Inputs:
106812 ** <ul>
106813 ** <li> A FILE* to which trace output should be written.
106814 ** If NULL, then tracing is turned off.
106815 ** <li> A prefix string written at the beginning of every
106816 ** line of trace output. If NULL, then tracing is
106817 ** turned off.
106818 ** </ul>
106820 ** Outputs:
106821 ** None.
106823 SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
106824 yyTraceFILE = TraceFILE;
106825 yyTracePrompt = zTracePrompt;
106826 if( yyTraceFILE==0 ) yyTracePrompt = 0;
106827 else if( yyTracePrompt==0 ) yyTraceFILE = 0;
106829 #endif /* NDEBUG */
106831 #ifndef NDEBUG
106832 /* For tracing shifts, the names of all terminals and nonterminals
106833 ** are required. The following table supplies these names */
106834 static const char *const yyTokenName[] = {
106835 "$", "SEMI", "EXPLAIN", "QUERY",
106836 "PLAN", "BEGIN", "TRANSACTION", "DEFERRED",
106837 "IMMEDIATE", "EXCLUSIVE", "COMMIT", "END",
106838 "ROLLBACK", "SAVEPOINT", "RELEASE", "TO",
106839 "TABLE", "CREATE", "IF", "NOT",
106840 "EXISTS", "TEMP", "LP", "RP",
106841 "AS", "COMMA", "ID", "INDEXED",
106842 "ABORT", "ACTION", "AFTER", "ANALYZE",
106843 "ASC", "ATTACH", "BEFORE", "BY",
106844 "CASCADE", "CAST", "COLUMNKW", "CONFLICT",
106845 "DATABASE", "DESC", "DETACH", "EACH",
106846 "FAIL", "FOR", "IGNORE", "INITIALLY",
106847 "INSTEAD", "LIKE_KW", "MATCH", "NO",
106848 "KEY", "OF", "OFFSET", "PRAGMA",
106849 "RAISE", "REPLACE", "RESTRICT", "ROW",
106850 "TRIGGER", "VACUUM", "VIEW", "VIRTUAL",
106851 "REINDEX", "RENAME", "CTIME_KW", "ANY",
106852 "OR", "AND", "IS", "BETWEEN",
106853 "IN", "ISNULL", "NOTNULL", "NE",
106854 "EQ", "GT", "LE", "LT",
106855 "GE", "ESCAPE", "BITAND", "BITOR",
106856 "LSHIFT", "RSHIFT", "PLUS", "MINUS",
106857 "STAR", "SLASH", "REM", "CONCAT",
106858 "COLLATE", "BITNOT", "STRING", "JOIN_KW",
106859 "CONSTRAINT", "DEFAULT", "NULL", "PRIMARY",
106860 "UNIQUE", "CHECK", "REFERENCES", "AUTOINCR",
106861 "ON", "INSERT", "DELETE", "UPDATE",
106862 "SET", "DEFERRABLE", "FOREIGN", "DROP",
106863 "UNION", "ALL", "EXCEPT", "INTERSECT",
106864 "SELECT", "DISTINCT", "DOT", "FROM",
106865 "JOIN", "USING", "ORDER", "GROUP",
106866 "HAVING", "LIMIT", "WHERE", "INTO",
106867 "VALUES", "INTEGER", "FLOAT", "BLOB",
106868 "REGISTER", "VARIABLE", "CASE", "WHEN",
106869 "THEN", "ELSE", "INDEX", "ALTER",
106870 "ADD", "error", "input", "cmdlist",
106871 "ecmd", "explain", "cmdx", "cmd",
106872 "transtype", "trans_opt", "nm", "savepoint_opt",
106873 "create_table", "create_table_args", "createkw", "temp",
106874 "ifnotexists", "dbnm", "columnlist", "conslist_opt",
106875 "select", "column", "columnid", "type",
106876 "carglist", "id", "ids", "typetoken",
106877 "typename", "signed", "plus_num", "minus_num",
106878 "carg", "ccons", "term", "expr",
106879 "onconf", "sortorder", "autoinc", "idxlist_opt",
106880 "refargs", "defer_subclause", "refarg", "refact",
106881 "init_deferred_pred_opt", "conslist", "tcons", "idxlist",
106882 "defer_subclause_opt", "orconf", "resolvetype", "raisetype",
106883 "ifexists", "fullname", "oneselect", "multiselect_op",
106884 "distinct", "selcollist", "from", "where_opt",
106885 "groupby_opt", "having_opt", "orderby_opt", "limit_opt",
106886 "sclp", "as", "seltablist", "stl_prefix",
106887 "joinop", "indexed_opt", "on_opt", "using_opt",
106888 "joinop2", "inscollist", "sortlist", "sortitem",
106889 "nexprlist", "setlist", "insert_cmd", "inscollist_opt",
106890 "itemlist", "exprlist", "likeop", "between_op",
106891 "in_op", "case_operand", "case_exprlist", "case_else",
106892 "uniqueflag", "collate", "nmnum", "plus_opt",
106893 "number", "trigger_decl", "trigger_cmd_list", "trigger_time",
106894 "trigger_event", "foreach_clause", "when_clause", "trigger_cmd",
106895 "trnm", "tridxby", "database_kw_opt", "key_opt",
106896 "add_column_fullname", "kwcolumn_opt", "create_vtab", "vtabarglist",
106897 "vtabarg", "vtabargtoken", "lp", "anylist",
106899 #endif /* NDEBUG */
106901 #ifndef NDEBUG
106902 /* For tracing reduce actions, the names of all rules are required.
106904 static const char *const yyRuleName[] = {
106905 /* 0 */ "input ::= cmdlist",
106906 /* 1 */ "cmdlist ::= cmdlist ecmd",
106907 /* 2 */ "cmdlist ::= ecmd",
106908 /* 3 */ "ecmd ::= SEMI",
106909 /* 4 */ "ecmd ::= explain cmdx SEMI",
106910 /* 5 */ "explain ::=",
106911 /* 6 */ "explain ::= EXPLAIN",
106912 /* 7 */ "explain ::= EXPLAIN QUERY PLAN",
106913 /* 8 */ "cmdx ::= cmd",
106914 /* 9 */ "cmd ::= BEGIN transtype trans_opt",
106915 /* 10 */ "trans_opt ::=",
106916 /* 11 */ "trans_opt ::= TRANSACTION",
106917 /* 12 */ "trans_opt ::= TRANSACTION nm",
106918 /* 13 */ "transtype ::=",
106919 /* 14 */ "transtype ::= DEFERRED",
106920 /* 15 */ "transtype ::= IMMEDIATE",
106921 /* 16 */ "transtype ::= EXCLUSIVE",
106922 /* 17 */ "cmd ::= COMMIT trans_opt",
106923 /* 18 */ "cmd ::= END trans_opt",
106924 /* 19 */ "cmd ::= ROLLBACK trans_opt",
106925 /* 20 */ "savepoint_opt ::= SAVEPOINT",
106926 /* 21 */ "savepoint_opt ::=",
106927 /* 22 */ "cmd ::= SAVEPOINT nm",
106928 /* 23 */ "cmd ::= RELEASE savepoint_opt nm",
106929 /* 24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
106930 /* 25 */ "cmd ::= create_table create_table_args",
106931 /* 26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
106932 /* 27 */ "createkw ::= CREATE",
106933 /* 28 */ "ifnotexists ::=",
106934 /* 29 */ "ifnotexists ::= IF NOT EXISTS",
106935 /* 30 */ "temp ::= TEMP",
106936 /* 31 */ "temp ::=",
106937 /* 32 */ "create_table_args ::= LP columnlist conslist_opt RP",
106938 /* 33 */ "create_table_args ::= AS select",
106939 /* 34 */ "columnlist ::= columnlist COMMA column",
106940 /* 35 */ "columnlist ::= column",
106941 /* 36 */ "column ::= columnid type carglist",
106942 /* 37 */ "columnid ::= nm",
106943 /* 38 */ "id ::= ID",
106944 /* 39 */ "id ::= INDEXED",
106945 /* 40 */ "ids ::= ID|STRING",
106946 /* 41 */ "nm ::= id",
106947 /* 42 */ "nm ::= STRING",
106948 /* 43 */ "nm ::= JOIN_KW",
106949 /* 44 */ "type ::=",
106950 /* 45 */ "type ::= typetoken",
106951 /* 46 */ "typetoken ::= typename",
106952 /* 47 */ "typetoken ::= typename LP signed RP",
106953 /* 48 */ "typetoken ::= typename LP signed COMMA signed RP",
106954 /* 49 */ "typename ::= ids",
106955 /* 50 */ "typename ::= typename ids",
106956 /* 51 */ "signed ::= plus_num",
106957 /* 52 */ "signed ::= minus_num",
106958 /* 53 */ "carglist ::= carglist carg",
106959 /* 54 */ "carglist ::=",
106960 /* 55 */ "carg ::= CONSTRAINT nm ccons",
106961 /* 56 */ "carg ::= ccons",
106962 /* 57 */ "ccons ::= DEFAULT term",
106963 /* 58 */ "ccons ::= DEFAULT LP expr RP",
106964 /* 59 */ "ccons ::= DEFAULT PLUS term",
106965 /* 60 */ "ccons ::= DEFAULT MINUS term",
106966 /* 61 */ "ccons ::= DEFAULT id",
106967 /* 62 */ "ccons ::= NULL onconf",
106968 /* 63 */ "ccons ::= NOT NULL onconf",
106969 /* 64 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
106970 /* 65 */ "ccons ::= UNIQUE onconf",
106971 /* 66 */ "ccons ::= CHECK LP expr RP",
106972 /* 67 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
106973 /* 68 */ "ccons ::= defer_subclause",
106974 /* 69 */ "ccons ::= COLLATE ids",
106975 /* 70 */ "autoinc ::=",
106976 /* 71 */ "autoinc ::= AUTOINCR",
106977 /* 72 */ "refargs ::=",
106978 /* 73 */ "refargs ::= refargs refarg",
106979 /* 74 */ "refarg ::= MATCH nm",
106980 /* 75 */ "refarg ::= ON INSERT refact",
106981 /* 76 */ "refarg ::= ON DELETE refact",
106982 /* 77 */ "refarg ::= ON UPDATE refact",
106983 /* 78 */ "refact ::= SET NULL",
106984 /* 79 */ "refact ::= SET DEFAULT",
106985 /* 80 */ "refact ::= CASCADE",
106986 /* 81 */ "refact ::= RESTRICT",
106987 /* 82 */ "refact ::= NO ACTION",
106988 /* 83 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
106989 /* 84 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
106990 /* 85 */ "init_deferred_pred_opt ::=",
106991 /* 86 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
106992 /* 87 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
106993 /* 88 */ "conslist_opt ::=",
106994 /* 89 */ "conslist_opt ::= COMMA conslist",
106995 /* 90 */ "conslist ::= conslist COMMA tcons",
106996 /* 91 */ "conslist ::= conslist tcons",
106997 /* 92 */ "conslist ::= tcons",
106998 /* 93 */ "tcons ::= CONSTRAINT nm",
106999 /* 94 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
107000 /* 95 */ "tcons ::= UNIQUE LP idxlist RP onconf",
107001 /* 96 */ "tcons ::= CHECK LP expr RP onconf",
107002 /* 97 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
107003 /* 98 */ "defer_subclause_opt ::=",
107004 /* 99 */ "defer_subclause_opt ::= defer_subclause",
107005 /* 100 */ "onconf ::=",
107006 /* 101 */ "onconf ::= ON CONFLICT resolvetype",
107007 /* 102 */ "orconf ::=",
107008 /* 103 */ "orconf ::= OR resolvetype",
107009 /* 104 */ "resolvetype ::= raisetype",
107010 /* 105 */ "resolvetype ::= IGNORE",
107011 /* 106 */ "resolvetype ::= REPLACE",
107012 /* 107 */ "cmd ::= DROP TABLE ifexists fullname",
107013 /* 108 */ "ifexists ::= IF EXISTS",
107014 /* 109 */ "ifexists ::=",
107015 /* 110 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
107016 /* 111 */ "cmd ::= DROP VIEW ifexists fullname",
107017 /* 112 */ "cmd ::= select",
107018 /* 113 */ "select ::= oneselect",
107019 /* 114 */ "select ::= select multiselect_op oneselect",
107020 /* 115 */ "multiselect_op ::= UNION",
107021 /* 116 */ "multiselect_op ::= UNION ALL",
107022 /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
107023 /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
107024 /* 119 */ "distinct ::= DISTINCT",
107025 /* 120 */ "distinct ::= ALL",
107026 /* 121 */ "distinct ::=",
107027 /* 122 */ "sclp ::= selcollist COMMA",
107028 /* 123 */ "sclp ::=",
107029 /* 124 */ "selcollist ::= sclp expr as",
107030 /* 125 */ "selcollist ::= sclp STAR",
107031 /* 126 */ "selcollist ::= sclp nm DOT STAR",
107032 /* 127 */ "as ::= AS nm",
107033 /* 128 */ "as ::= ids",
107034 /* 129 */ "as ::=",
107035 /* 130 */ "from ::=",
107036 /* 131 */ "from ::= FROM seltablist",
107037 /* 132 */ "stl_prefix ::= seltablist joinop",
107038 /* 133 */ "stl_prefix ::=",
107039 /* 134 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
107040 /* 135 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
107041 /* 136 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
107042 /* 137 */ "dbnm ::=",
107043 /* 138 */ "dbnm ::= DOT nm",
107044 /* 139 */ "fullname ::= nm dbnm",
107045 /* 140 */ "joinop ::= COMMA|JOIN",
107046 /* 141 */ "joinop ::= JOIN_KW JOIN",
107047 /* 142 */ "joinop ::= JOIN_KW nm JOIN",
107048 /* 143 */ "joinop ::= JOIN_KW nm nm JOIN",
107049 /* 144 */ "on_opt ::= ON expr",
107050 /* 145 */ "on_opt ::=",
107051 /* 146 */ "indexed_opt ::=",
107052 /* 147 */ "indexed_opt ::= INDEXED BY nm",
107053 /* 148 */ "indexed_opt ::= NOT INDEXED",
107054 /* 149 */ "using_opt ::= USING LP inscollist RP",
107055 /* 150 */ "using_opt ::=",
107056 /* 151 */ "orderby_opt ::=",
107057 /* 152 */ "orderby_opt ::= ORDER BY sortlist",
107058 /* 153 */ "sortlist ::= sortlist COMMA sortitem sortorder",
107059 /* 154 */ "sortlist ::= sortitem sortorder",
107060 /* 155 */ "sortitem ::= expr",
107061 /* 156 */ "sortorder ::= ASC",
107062 /* 157 */ "sortorder ::= DESC",
107063 /* 158 */ "sortorder ::=",
107064 /* 159 */ "groupby_opt ::=",
107065 /* 160 */ "groupby_opt ::= GROUP BY nexprlist",
107066 /* 161 */ "having_opt ::=",
107067 /* 162 */ "having_opt ::= HAVING expr",
107068 /* 163 */ "limit_opt ::=",
107069 /* 164 */ "limit_opt ::= LIMIT expr",
107070 /* 165 */ "limit_opt ::= LIMIT expr OFFSET expr",
107071 /* 166 */ "limit_opt ::= LIMIT expr COMMA expr",
107072 /* 167 */ "cmd ::= DELETE FROM fullname indexed_opt where_opt",
107073 /* 168 */ "where_opt ::=",
107074 /* 169 */ "where_opt ::= WHERE expr",
107075 /* 170 */ "cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt",
107076 /* 171 */ "setlist ::= setlist COMMA nm EQ expr",
107077 /* 172 */ "setlist ::= nm EQ expr",
107078 /* 173 */ "cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP",
107079 /* 174 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select",
107080 /* 175 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
107081 /* 176 */ "insert_cmd ::= INSERT orconf",
107082 /* 177 */ "insert_cmd ::= REPLACE",
107083 /* 178 */ "itemlist ::= itemlist COMMA expr",
107084 /* 179 */ "itemlist ::= expr",
107085 /* 180 */ "inscollist_opt ::=",
107086 /* 181 */ "inscollist_opt ::= LP inscollist RP",
107087 /* 182 */ "inscollist ::= inscollist COMMA nm",
107088 /* 183 */ "inscollist ::= nm",
107089 /* 184 */ "expr ::= term",
107090 /* 185 */ "expr ::= LP expr RP",
107091 /* 186 */ "term ::= NULL",
107092 /* 187 */ "expr ::= id",
107093 /* 188 */ "expr ::= JOIN_KW",
107094 /* 189 */ "expr ::= nm DOT nm",
107095 /* 190 */ "expr ::= nm DOT nm DOT nm",
107096 /* 191 */ "term ::= INTEGER|FLOAT|BLOB",
107097 /* 192 */ "term ::= STRING",
107098 /* 193 */ "expr ::= REGISTER",
107099 /* 194 */ "expr ::= VARIABLE",
107100 /* 195 */ "expr ::= expr COLLATE ids",
107101 /* 196 */ "expr ::= CAST LP expr AS typetoken RP",
107102 /* 197 */ "expr ::= ID LP distinct exprlist RP",
107103 /* 198 */ "expr ::= ID LP STAR RP",
107104 /* 199 */ "term ::= CTIME_KW",
107105 /* 200 */ "expr ::= expr AND expr",
107106 /* 201 */ "expr ::= expr OR expr",
107107 /* 202 */ "expr ::= expr LT|GT|GE|LE expr",
107108 /* 203 */ "expr ::= expr EQ|NE expr",
107109 /* 204 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
107110 /* 205 */ "expr ::= expr PLUS|MINUS expr",
107111 /* 206 */ "expr ::= expr STAR|SLASH|REM expr",
107112 /* 207 */ "expr ::= expr CONCAT expr",
107113 /* 208 */ "likeop ::= LIKE_KW",
107114 /* 209 */ "likeop ::= NOT LIKE_KW",
107115 /* 210 */ "likeop ::= MATCH",
107116 /* 211 */ "likeop ::= NOT MATCH",
107117 /* 212 */ "expr ::= expr likeop expr",
107118 /* 213 */ "expr ::= expr likeop expr ESCAPE expr",
107119 /* 214 */ "expr ::= expr ISNULL|NOTNULL",
107120 /* 215 */ "expr ::= expr NOT NULL",
107121 /* 216 */ "expr ::= expr IS expr",
107122 /* 217 */ "expr ::= expr IS NOT expr",
107123 /* 218 */ "expr ::= NOT expr",
107124 /* 219 */ "expr ::= BITNOT expr",
107125 /* 220 */ "expr ::= MINUS expr",
107126 /* 221 */ "expr ::= PLUS expr",
107127 /* 222 */ "between_op ::= BETWEEN",
107128 /* 223 */ "between_op ::= NOT BETWEEN",
107129 /* 224 */ "expr ::= expr between_op expr AND expr",
107130 /* 225 */ "in_op ::= IN",
107131 /* 226 */ "in_op ::= NOT IN",
107132 /* 227 */ "expr ::= expr in_op LP exprlist RP",
107133 /* 228 */ "expr ::= LP select RP",
107134 /* 229 */ "expr ::= expr in_op LP select RP",
107135 /* 230 */ "expr ::= expr in_op nm dbnm",
107136 /* 231 */ "expr ::= EXISTS LP select RP",
107137 /* 232 */ "expr ::= CASE case_operand case_exprlist case_else END",
107138 /* 233 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
107139 /* 234 */ "case_exprlist ::= WHEN expr THEN expr",
107140 /* 235 */ "case_else ::= ELSE expr",
107141 /* 236 */ "case_else ::=",
107142 /* 237 */ "case_operand ::= expr",
107143 /* 238 */ "case_operand ::=",
107144 /* 239 */ "exprlist ::= nexprlist",
107145 /* 240 */ "exprlist ::=",
107146 /* 241 */ "nexprlist ::= nexprlist COMMA expr",
107147 /* 242 */ "nexprlist ::= expr",
107148 /* 243 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP",
107149 /* 244 */ "uniqueflag ::= UNIQUE",
107150 /* 245 */ "uniqueflag ::=",
107151 /* 246 */ "idxlist_opt ::=",
107152 /* 247 */ "idxlist_opt ::= LP idxlist RP",
107153 /* 248 */ "idxlist ::= idxlist COMMA nm collate sortorder",
107154 /* 249 */ "idxlist ::= nm collate sortorder",
107155 /* 250 */ "collate ::=",
107156 /* 251 */ "collate ::= COLLATE ids",
107157 /* 252 */ "cmd ::= DROP INDEX ifexists fullname",
107158 /* 253 */ "cmd ::= VACUUM",
107159 /* 254 */ "cmd ::= VACUUM nm",
107160 /* 255 */ "cmd ::= PRAGMA nm dbnm",
107161 /* 256 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
107162 /* 257 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
107163 /* 258 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
107164 /* 259 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
107165 /* 260 */ "nmnum ::= plus_num",
107166 /* 261 */ "nmnum ::= nm",
107167 /* 262 */ "nmnum ::= ON",
107168 /* 263 */ "nmnum ::= DELETE",
107169 /* 264 */ "nmnum ::= DEFAULT",
107170 /* 265 */ "plus_num ::= plus_opt number",
107171 /* 266 */ "minus_num ::= MINUS number",
107172 /* 267 */ "number ::= INTEGER|FLOAT",
107173 /* 268 */ "plus_opt ::= PLUS",
107174 /* 269 */ "plus_opt ::=",
107175 /* 270 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
107176 /* 271 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
107177 /* 272 */ "trigger_time ::= BEFORE",
107178 /* 273 */ "trigger_time ::= AFTER",
107179 /* 274 */ "trigger_time ::= INSTEAD OF",
107180 /* 275 */ "trigger_time ::=",
107181 /* 276 */ "trigger_event ::= DELETE|INSERT",
107182 /* 277 */ "trigger_event ::= UPDATE",
107183 /* 278 */ "trigger_event ::= UPDATE OF inscollist",
107184 /* 279 */ "foreach_clause ::=",
107185 /* 280 */ "foreach_clause ::= FOR EACH ROW",
107186 /* 281 */ "when_clause ::=",
107187 /* 282 */ "when_clause ::= WHEN expr",
107188 /* 283 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
107189 /* 284 */ "trigger_cmd_list ::= trigger_cmd SEMI",
107190 /* 285 */ "trnm ::= nm",
107191 /* 286 */ "trnm ::= nm DOT nm",
107192 /* 287 */ "tridxby ::=",
107193 /* 288 */ "tridxby ::= INDEXED BY nm",
107194 /* 289 */ "tridxby ::= NOT INDEXED",
107195 /* 290 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
107196 /* 291 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP",
107197 /* 292 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
107198 /* 293 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
107199 /* 294 */ "trigger_cmd ::= select",
107200 /* 295 */ "expr ::= RAISE LP IGNORE RP",
107201 /* 296 */ "expr ::= RAISE LP raisetype COMMA nm RP",
107202 /* 297 */ "raisetype ::= ROLLBACK",
107203 /* 298 */ "raisetype ::= ABORT",
107204 /* 299 */ "raisetype ::= FAIL",
107205 /* 300 */ "cmd ::= DROP TRIGGER ifexists fullname",
107206 /* 301 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
107207 /* 302 */ "cmd ::= DETACH database_kw_opt expr",
107208 /* 303 */ "key_opt ::=",
107209 /* 304 */ "key_opt ::= KEY expr",
107210 /* 305 */ "database_kw_opt ::= DATABASE",
107211 /* 306 */ "database_kw_opt ::=",
107212 /* 307 */ "cmd ::= REINDEX",
107213 /* 308 */ "cmd ::= REINDEX nm dbnm",
107214 /* 309 */ "cmd ::= ANALYZE",
107215 /* 310 */ "cmd ::= ANALYZE nm dbnm",
107216 /* 311 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
107217 /* 312 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
107218 /* 313 */ "add_column_fullname ::= fullname",
107219 /* 314 */ "kwcolumn_opt ::=",
107220 /* 315 */ "kwcolumn_opt ::= COLUMNKW",
107221 /* 316 */ "cmd ::= create_vtab",
107222 /* 317 */ "cmd ::= create_vtab LP vtabarglist RP",
107223 /* 318 */ "create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm",
107224 /* 319 */ "vtabarglist ::= vtabarg",
107225 /* 320 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
107226 /* 321 */ "vtabarg ::=",
107227 /* 322 */ "vtabarg ::= vtabarg vtabargtoken",
107228 /* 323 */ "vtabargtoken ::= ANY",
107229 /* 324 */ "vtabargtoken ::= lp anylist RP",
107230 /* 325 */ "lp ::= LP",
107231 /* 326 */ "anylist ::=",
107232 /* 327 */ "anylist ::= anylist LP anylist RP",
107233 /* 328 */ "anylist ::= anylist ANY",
107235 #endif /* NDEBUG */
107238 #if YYSTACKDEPTH<=0
107240 ** Try to increase the size of the parser stack.
107242 static void yyGrowStack(yyParser *p){
107243 int newSize;
107244 yyStackEntry *pNew;
107246 newSize = p->yystksz*2 + 100;
107247 pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
107248 if( pNew ){
107249 p->yystack = pNew;
107250 p->yystksz = newSize;
107251 #ifndef NDEBUG
107252 if( yyTraceFILE ){
107253 fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
107254 yyTracePrompt, p->yystksz);
107256 #endif
107259 #endif
107262 ** This function allocates a new parser.
107263 ** The only argument is a pointer to a function which works like
107264 ** malloc.
107266 ** Inputs:
107267 ** A pointer to the function used to allocate memory.
107269 ** Outputs:
107270 ** A pointer to a parser. This pointer is used in subsequent calls
107271 ** to sqlite3Parser and sqlite3ParserFree.
107273 SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
107274 yyParser *pParser;
107275 pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
107276 if( pParser ){
107277 pParser->yyidx = -1;
107278 #ifdef YYTRACKMAXSTACKDEPTH
107279 pParser->yyidxMax = 0;
107280 #endif
107281 #if YYSTACKDEPTH<=0
107282 pParser->yystack = NULL;
107283 pParser->yystksz = 0;
107284 yyGrowStack(pParser);
107285 #endif
107287 return pParser;
107290 /* The following function deletes the value associated with a
107291 ** symbol. The symbol can be either a terminal or nonterminal.
107292 ** "yymajor" is the symbol code, and "yypminor" is a pointer to
107293 ** the value.
107295 static void yy_destructor(
107296 yyParser *yypParser, /* The parser */
107297 YYCODETYPE yymajor, /* Type code for object to destroy */
107298 YYMINORTYPE *yypminor /* The object to be destroyed */
107300 sqlite3ParserARG_FETCH;
107301 switch( yymajor ){
107302 /* Here is inserted the actions which take place when a
107303 ** terminal or non-terminal is destroyed. This can happen
107304 ** when the symbol is popped from the stack during a
107305 ** reduce or during error processing or when a parser is
107306 ** being destroyed before it is finished parsing.
107308 ** Note: during a reduce, the only symbols destroyed are those
107309 ** which appear on the RHS of the rule, but which are not used
107310 ** inside the C code.
107312 case 160: /* select */
107313 case 194: /* oneselect */
107315 sqlite3SelectDelete(pParse->db, (yypminor->yy387));
107317 break;
107318 case 174: /* term */
107319 case 175: /* expr */
107321 sqlite3ExprDelete(pParse->db, (yypminor->yy118).pExpr);
107323 break;
107324 case 179: /* idxlist_opt */
107325 case 187: /* idxlist */
107326 case 197: /* selcollist */
107327 case 200: /* groupby_opt */
107328 case 202: /* orderby_opt */
107329 case 204: /* sclp */
107330 case 214: /* sortlist */
107331 case 216: /* nexprlist */
107332 case 217: /* setlist */
107333 case 220: /* itemlist */
107334 case 221: /* exprlist */
107335 case 226: /* case_exprlist */
107337 sqlite3ExprListDelete(pParse->db, (yypminor->yy322));
107339 break;
107340 case 193: /* fullname */
107341 case 198: /* from */
107342 case 206: /* seltablist */
107343 case 207: /* stl_prefix */
107345 sqlite3SrcListDelete(pParse->db, (yypminor->yy259));
107347 break;
107348 case 199: /* where_opt */
107349 case 201: /* having_opt */
107350 case 210: /* on_opt */
107351 case 215: /* sortitem */
107352 case 225: /* case_operand */
107353 case 227: /* case_else */
107354 case 238: /* when_clause */
107355 case 243: /* key_opt */
107357 sqlite3ExprDelete(pParse->db, (yypminor->yy314));
107359 break;
107360 case 211: /* using_opt */
107361 case 213: /* inscollist */
107362 case 219: /* inscollist_opt */
107364 sqlite3IdListDelete(pParse->db, (yypminor->yy384));
107366 break;
107367 case 234: /* trigger_cmd_list */
107368 case 239: /* trigger_cmd */
107370 sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy203));
107372 break;
107373 case 236: /* trigger_event */
107375 sqlite3IdListDelete(pParse->db, (yypminor->yy90).b);
107377 break;
107378 default: break; /* If no destructor action specified: do nothing */
107383 ** Pop the parser's stack once.
107385 ** If there is a destructor routine associated with the token which
107386 ** is popped from the stack, then call it.
107388 ** Return the major token number for the symbol popped.
107390 static int yy_pop_parser_stack(yyParser *pParser){
107391 YYCODETYPE yymajor;
107392 yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
107394 /* There is no mechanism by which the parser stack can be popped below
107395 ** empty in SQLite. */
107396 if( NEVER(pParser->yyidx<0) ) return 0;
107397 #ifndef NDEBUG
107398 if( yyTraceFILE && pParser->yyidx>=0 ){
107399 fprintf(yyTraceFILE,"%sPopping %s\n",
107400 yyTracePrompt,
107401 yyTokenName[yytos->major]);
107403 #endif
107404 yymajor = yytos->major;
107405 yy_destructor(pParser, yymajor, &yytos->minor);
107406 pParser->yyidx--;
107407 return yymajor;
107411 ** Deallocate and destroy a parser. Destructors are all called for
107412 ** all stack elements before shutting the parser down.
107414 ** Inputs:
107415 ** <ul>
107416 ** <li> A pointer to the parser. This should be a pointer
107417 ** obtained from sqlite3ParserAlloc.
107418 ** <li> A pointer to a function used to reclaim memory obtained
107419 ** from malloc.
107420 ** </ul>
107422 SQLITE_PRIVATE void sqlite3ParserFree(
107423 void *p, /* The parser to be deleted */
107424 void (*freeProc)(void*) /* Function used to reclaim memory */
107426 yyParser *pParser = (yyParser*)p;
107427 /* In SQLite, we never try to destroy a parser that was not successfully
107428 ** created in the first place. */
107429 if( NEVER(pParser==0) ) return;
107430 while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
107431 #if YYSTACKDEPTH<=0
107432 free(pParser->yystack);
107433 #endif
107434 (*freeProc)((void*)pParser);
107438 ** Return the peak depth of the stack for a parser.
107440 #ifdef YYTRACKMAXSTACKDEPTH
107441 SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
107442 yyParser *pParser = (yyParser*)p;
107443 return pParser->yyidxMax;
107445 #endif
107448 ** Find the appropriate action for a parser given the terminal
107449 ** look-ahead token iLookAhead.
107451 ** If the look-ahead token is YYNOCODE, then check to see if the action is
107452 ** independent of the look-ahead. If it is, return the action, otherwise
107453 ** return YY_NO_ACTION.
107455 static int yy_find_shift_action(
107456 yyParser *pParser, /* The parser */
107457 YYCODETYPE iLookAhead /* The look-ahead token */
107459 int i;
107460 int stateno = pParser->yystack[pParser->yyidx].stateno;
107462 if( stateno>YY_SHIFT_COUNT
107463 || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
107464 return yy_default[stateno];
107466 assert( iLookAhead!=YYNOCODE );
107467 i += iLookAhead;
107468 if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
107469 if( iLookAhead>0 ){
107470 #ifdef YYFALLBACK
107471 YYCODETYPE iFallback; /* Fallback token */
107472 if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
107473 && (iFallback = yyFallback[iLookAhead])!=0 ){
107474 #ifndef NDEBUG
107475 if( yyTraceFILE ){
107476 fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
107477 yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
107479 #endif
107480 return yy_find_shift_action(pParser, iFallback);
107482 #endif
107483 #ifdef YYWILDCARD
107485 int j = i - iLookAhead + YYWILDCARD;
107487 #if YY_SHIFT_MIN+YYWILDCARD<0
107488 j>=0 &&
107489 #endif
107490 #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
107491 j<YY_ACTTAB_COUNT &&
107492 #endif
107493 yy_lookahead[j]==YYWILDCARD
107495 #ifndef NDEBUG
107496 if( yyTraceFILE ){
107497 fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
107498 yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
107500 #endif /* NDEBUG */
107501 return yy_action[j];
107504 #endif /* YYWILDCARD */
107506 return yy_default[stateno];
107507 }else{
107508 return yy_action[i];
107513 ** Find the appropriate action for a parser given the non-terminal
107514 ** look-ahead token iLookAhead.
107516 ** If the look-ahead token is YYNOCODE, then check to see if the action is
107517 ** independent of the look-ahead. If it is, return the action, otherwise
107518 ** return YY_NO_ACTION.
107520 static int yy_find_reduce_action(
107521 int stateno, /* Current state number */
107522 YYCODETYPE iLookAhead /* The look-ahead token */
107524 int i;
107525 #ifdef YYERRORSYMBOL
107526 if( stateno>YY_REDUCE_COUNT ){
107527 return yy_default[stateno];
107529 #else
107530 assert( stateno<=YY_REDUCE_COUNT );
107531 #endif
107532 i = yy_reduce_ofst[stateno];
107533 assert( i!=YY_REDUCE_USE_DFLT );
107534 assert( iLookAhead!=YYNOCODE );
107535 i += iLookAhead;
107536 #ifdef YYERRORSYMBOL
107537 if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
107538 return yy_default[stateno];
107540 #else
107541 assert( i>=0 && i<YY_ACTTAB_COUNT );
107542 assert( yy_lookahead[i]==iLookAhead );
107543 #endif
107544 return yy_action[i];
107548 ** The following routine is called if the stack overflows.
107550 static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
107551 sqlite3ParserARG_FETCH;
107552 yypParser->yyidx--;
107553 #ifndef NDEBUG
107554 if( yyTraceFILE ){
107555 fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
107557 #endif
107558 while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
107559 /* Here code is inserted which will execute if the parser
107560 ** stack every overflows */
107562 UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
107563 sqlite3ErrorMsg(pParse, "parser stack overflow");
107564 pParse->parseError = 1;
107565 sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
107569 ** Perform a shift action.
107571 static void yy_shift(
107572 yyParser *yypParser, /* The parser to be shifted */
107573 int yyNewState, /* The new state to shift in */
107574 int yyMajor, /* The major token to shift in */
107575 YYMINORTYPE *yypMinor /* Pointer to the minor token to shift in */
107577 yyStackEntry *yytos;
107578 yypParser->yyidx++;
107579 #ifdef YYTRACKMAXSTACKDEPTH
107580 if( yypParser->yyidx>yypParser->yyidxMax ){
107581 yypParser->yyidxMax = yypParser->yyidx;
107583 #endif
107584 #if YYSTACKDEPTH>0
107585 if( yypParser->yyidx>=YYSTACKDEPTH ){
107586 yyStackOverflow(yypParser, yypMinor);
107587 return;
107589 #else
107590 if( yypParser->yyidx>=yypParser->yystksz ){
107591 yyGrowStack(yypParser);
107592 if( yypParser->yyidx>=yypParser->yystksz ){
107593 yyStackOverflow(yypParser, yypMinor);
107594 return;
107597 #endif
107598 yytos = &yypParser->yystack[yypParser->yyidx];
107599 yytos->stateno = (YYACTIONTYPE)yyNewState;
107600 yytos->major = (YYCODETYPE)yyMajor;
107601 yytos->minor = *yypMinor;
107602 #ifndef NDEBUG
107603 if( yyTraceFILE && yypParser->yyidx>0 ){
107604 int i;
107605 fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
107606 fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
107607 for(i=1; i<=yypParser->yyidx; i++)
107608 fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
107609 fprintf(yyTraceFILE,"\n");
107611 #endif
107614 /* The following table contains information about every rule that
107615 ** is used during the reduce.
107617 static const struct {
107618 YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */
107619 unsigned char nrhs; /* Number of right-hand side symbols in the rule */
107620 } yyRuleInfo[] = {
107621 { 142, 1 },
107622 { 143, 2 },
107623 { 143, 1 },
107624 { 144, 1 },
107625 { 144, 3 },
107626 { 145, 0 },
107627 { 145, 1 },
107628 { 145, 3 },
107629 { 146, 1 },
107630 { 147, 3 },
107631 { 149, 0 },
107632 { 149, 1 },
107633 { 149, 2 },
107634 { 148, 0 },
107635 { 148, 1 },
107636 { 148, 1 },
107637 { 148, 1 },
107638 { 147, 2 },
107639 { 147, 2 },
107640 { 147, 2 },
107641 { 151, 1 },
107642 { 151, 0 },
107643 { 147, 2 },
107644 { 147, 3 },
107645 { 147, 5 },
107646 { 147, 2 },
107647 { 152, 6 },
107648 { 154, 1 },
107649 { 156, 0 },
107650 { 156, 3 },
107651 { 155, 1 },
107652 { 155, 0 },
107653 { 153, 4 },
107654 { 153, 2 },
107655 { 158, 3 },
107656 { 158, 1 },
107657 { 161, 3 },
107658 { 162, 1 },
107659 { 165, 1 },
107660 { 165, 1 },
107661 { 166, 1 },
107662 { 150, 1 },
107663 { 150, 1 },
107664 { 150, 1 },
107665 { 163, 0 },
107666 { 163, 1 },
107667 { 167, 1 },
107668 { 167, 4 },
107669 { 167, 6 },
107670 { 168, 1 },
107671 { 168, 2 },
107672 { 169, 1 },
107673 { 169, 1 },
107674 { 164, 2 },
107675 { 164, 0 },
107676 { 172, 3 },
107677 { 172, 1 },
107678 { 173, 2 },
107679 { 173, 4 },
107680 { 173, 3 },
107681 { 173, 3 },
107682 { 173, 2 },
107683 { 173, 2 },
107684 { 173, 3 },
107685 { 173, 5 },
107686 { 173, 2 },
107687 { 173, 4 },
107688 { 173, 4 },
107689 { 173, 1 },
107690 { 173, 2 },
107691 { 178, 0 },
107692 { 178, 1 },
107693 { 180, 0 },
107694 { 180, 2 },
107695 { 182, 2 },
107696 { 182, 3 },
107697 { 182, 3 },
107698 { 182, 3 },
107699 { 183, 2 },
107700 { 183, 2 },
107701 { 183, 1 },
107702 { 183, 1 },
107703 { 183, 2 },
107704 { 181, 3 },
107705 { 181, 2 },
107706 { 184, 0 },
107707 { 184, 2 },
107708 { 184, 2 },
107709 { 159, 0 },
107710 { 159, 2 },
107711 { 185, 3 },
107712 { 185, 2 },
107713 { 185, 1 },
107714 { 186, 2 },
107715 { 186, 7 },
107716 { 186, 5 },
107717 { 186, 5 },
107718 { 186, 10 },
107719 { 188, 0 },
107720 { 188, 1 },
107721 { 176, 0 },
107722 { 176, 3 },
107723 { 189, 0 },
107724 { 189, 2 },
107725 { 190, 1 },
107726 { 190, 1 },
107727 { 190, 1 },
107728 { 147, 4 },
107729 { 192, 2 },
107730 { 192, 0 },
107731 { 147, 8 },
107732 { 147, 4 },
107733 { 147, 1 },
107734 { 160, 1 },
107735 { 160, 3 },
107736 { 195, 1 },
107737 { 195, 2 },
107738 { 195, 1 },
107739 { 194, 9 },
107740 { 196, 1 },
107741 { 196, 1 },
107742 { 196, 0 },
107743 { 204, 2 },
107744 { 204, 0 },
107745 { 197, 3 },
107746 { 197, 2 },
107747 { 197, 4 },
107748 { 205, 2 },
107749 { 205, 1 },
107750 { 205, 0 },
107751 { 198, 0 },
107752 { 198, 2 },
107753 { 207, 2 },
107754 { 207, 0 },
107755 { 206, 7 },
107756 { 206, 7 },
107757 { 206, 7 },
107758 { 157, 0 },
107759 { 157, 2 },
107760 { 193, 2 },
107761 { 208, 1 },
107762 { 208, 2 },
107763 { 208, 3 },
107764 { 208, 4 },
107765 { 210, 2 },
107766 { 210, 0 },
107767 { 209, 0 },
107768 { 209, 3 },
107769 { 209, 2 },
107770 { 211, 4 },
107771 { 211, 0 },
107772 { 202, 0 },
107773 { 202, 3 },
107774 { 214, 4 },
107775 { 214, 2 },
107776 { 215, 1 },
107777 { 177, 1 },
107778 { 177, 1 },
107779 { 177, 0 },
107780 { 200, 0 },
107781 { 200, 3 },
107782 { 201, 0 },
107783 { 201, 2 },
107784 { 203, 0 },
107785 { 203, 2 },
107786 { 203, 4 },
107787 { 203, 4 },
107788 { 147, 5 },
107789 { 199, 0 },
107790 { 199, 2 },
107791 { 147, 7 },
107792 { 217, 5 },
107793 { 217, 3 },
107794 { 147, 8 },
107795 { 147, 5 },
107796 { 147, 6 },
107797 { 218, 2 },
107798 { 218, 1 },
107799 { 220, 3 },
107800 { 220, 1 },
107801 { 219, 0 },
107802 { 219, 3 },
107803 { 213, 3 },
107804 { 213, 1 },
107805 { 175, 1 },
107806 { 175, 3 },
107807 { 174, 1 },
107808 { 175, 1 },
107809 { 175, 1 },
107810 { 175, 3 },
107811 { 175, 5 },
107812 { 174, 1 },
107813 { 174, 1 },
107814 { 175, 1 },
107815 { 175, 1 },
107816 { 175, 3 },
107817 { 175, 6 },
107818 { 175, 5 },
107819 { 175, 4 },
107820 { 174, 1 },
107821 { 175, 3 },
107822 { 175, 3 },
107823 { 175, 3 },
107824 { 175, 3 },
107825 { 175, 3 },
107826 { 175, 3 },
107827 { 175, 3 },
107828 { 175, 3 },
107829 { 222, 1 },
107830 { 222, 2 },
107831 { 222, 1 },
107832 { 222, 2 },
107833 { 175, 3 },
107834 { 175, 5 },
107835 { 175, 2 },
107836 { 175, 3 },
107837 { 175, 3 },
107838 { 175, 4 },
107839 { 175, 2 },
107840 { 175, 2 },
107841 { 175, 2 },
107842 { 175, 2 },
107843 { 223, 1 },
107844 { 223, 2 },
107845 { 175, 5 },
107846 { 224, 1 },
107847 { 224, 2 },
107848 { 175, 5 },
107849 { 175, 3 },
107850 { 175, 5 },
107851 { 175, 4 },
107852 { 175, 4 },
107853 { 175, 5 },
107854 { 226, 5 },
107855 { 226, 4 },
107856 { 227, 2 },
107857 { 227, 0 },
107858 { 225, 1 },
107859 { 225, 0 },
107860 { 221, 1 },
107861 { 221, 0 },
107862 { 216, 3 },
107863 { 216, 1 },
107864 { 147, 11 },
107865 { 228, 1 },
107866 { 228, 0 },
107867 { 179, 0 },
107868 { 179, 3 },
107869 { 187, 5 },
107870 { 187, 3 },
107871 { 229, 0 },
107872 { 229, 2 },
107873 { 147, 4 },
107874 { 147, 1 },
107875 { 147, 2 },
107876 { 147, 3 },
107877 { 147, 5 },
107878 { 147, 6 },
107879 { 147, 5 },
107880 { 147, 6 },
107881 { 230, 1 },
107882 { 230, 1 },
107883 { 230, 1 },
107884 { 230, 1 },
107885 { 230, 1 },
107886 { 170, 2 },
107887 { 171, 2 },
107888 { 232, 1 },
107889 { 231, 1 },
107890 { 231, 0 },
107891 { 147, 5 },
107892 { 233, 11 },
107893 { 235, 1 },
107894 { 235, 1 },
107895 { 235, 2 },
107896 { 235, 0 },
107897 { 236, 1 },
107898 { 236, 1 },
107899 { 236, 3 },
107900 { 237, 0 },
107901 { 237, 3 },
107902 { 238, 0 },
107903 { 238, 2 },
107904 { 234, 3 },
107905 { 234, 2 },
107906 { 240, 1 },
107907 { 240, 3 },
107908 { 241, 0 },
107909 { 241, 3 },
107910 { 241, 2 },
107911 { 239, 7 },
107912 { 239, 8 },
107913 { 239, 5 },
107914 { 239, 5 },
107915 { 239, 1 },
107916 { 175, 4 },
107917 { 175, 6 },
107918 { 191, 1 },
107919 { 191, 1 },
107920 { 191, 1 },
107921 { 147, 4 },
107922 { 147, 6 },
107923 { 147, 3 },
107924 { 243, 0 },
107925 { 243, 2 },
107926 { 242, 1 },
107927 { 242, 0 },
107928 { 147, 1 },
107929 { 147, 3 },
107930 { 147, 1 },
107931 { 147, 3 },
107932 { 147, 6 },
107933 { 147, 6 },
107934 { 244, 1 },
107935 { 245, 0 },
107936 { 245, 1 },
107937 { 147, 1 },
107938 { 147, 4 },
107939 { 246, 7 },
107940 { 247, 1 },
107941 { 247, 3 },
107942 { 248, 0 },
107943 { 248, 2 },
107944 { 249, 1 },
107945 { 249, 3 },
107946 { 250, 1 },
107947 { 251, 0 },
107948 { 251, 4 },
107949 { 251, 2 },
107952 static void yy_accept(yyParser*); /* Forward Declaration */
107955 ** Perform a reduce action and the shift that must immediately
107956 ** follow the reduce.
107958 static void yy_reduce(
107959 yyParser *yypParser, /* The parser */
107960 int yyruleno /* Number of the rule by which to reduce */
107962 int yygoto; /* The next state */
107963 int yyact; /* The next action */
107964 YYMINORTYPE yygotominor; /* The LHS of the rule reduced */
107965 yyStackEntry *yymsp; /* The top of the parser's stack */
107966 int yysize; /* Amount to pop the stack */
107967 sqlite3ParserARG_FETCH;
107968 yymsp = &yypParser->yystack[yypParser->yyidx];
107969 #ifndef NDEBUG
107970 if( yyTraceFILE && yyruleno>=0
107971 && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
107972 fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
107973 yyRuleName[yyruleno]);
107975 #endif /* NDEBUG */
107977 /* Silence complaints from purify about yygotominor being uninitialized
107978 ** in some cases when it is copied into the stack after the following
107979 ** switch. yygotominor is uninitialized when a rule reduces that does
107980 ** not set the value of its left-hand side nonterminal. Leaving the
107981 ** value of the nonterminal uninitialized is utterly harmless as long
107982 ** as the value is never used. So really the only thing this code
107983 ** accomplishes is to quieten purify.
107985 ** 2007-01-16: The wireshark project (www.wireshark.org) reports that
107986 ** without this code, their parser segfaults. I'm not sure what there
107987 ** parser is doing to make this happen. This is the second bug report
107988 ** from wireshark this week. Clearly they are stressing Lemon in ways
107989 ** that it has not been previously stressed... (SQLite ticket #2172)
107991 /*memset(&yygotominor, 0, sizeof(yygotominor));*/
107992 yygotominor = yyzerominor;
107995 switch( yyruleno ){
107996 /* Beginning here are the reduction cases. A typical example
107997 ** follows:
107998 ** case 0:
107999 ** #line <lineno> <grammarfile>
108000 ** { ... } // User supplied code
108001 ** #line <lineno> <thisfile>
108002 ** break;
108004 case 5: /* explain ::= */
108005 { sqlite3BeginParse(pParse, 0); }
108006 break;
108007 case 6: /* explain ::= EXPLAIN */
108008 { sqlite3BeginParse(pParse, 1); }
108009 break;
108010 case 7: /* explain ::= EXPLAIN QUERY PLAN */
108011 { sqlite3BeginParse(pParse, 2); }
108012 break;
108013 case 8: /* cmdx ::= cmd */
108014 { sqlite3FinishCoding(pParse); }
108015 break;
108016 case 9: /* cmd ::= BEGIN transtype trans_opt */
108017 {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy4);}
108018 break;
108019 case 13: /* transtype ::= */
108020 {yygotominor.yy4 = TK_DEFERRED;}
108021 break;
108022 case 14: /* transtype ::= DEFERRED */
108023 case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
108024 case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
108025 case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
108026 case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
108027 {yygotominor.yy4 = yymsp[0].major;}
108028 break;
108029 case 17: /* cmd ::= COMMIT trans_opt */
108030 case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
108031 {sqlite3CommitTransaction(pParse);}
108032 break;
108033 case 19: /* cmd ::= ROLLBACK trans_opt */
108034 {sqlite3RollbackTransaction(pParse);}
108035 break;
108036 case 22: /* cmd ::= SAVEPOINT nm */
108038 sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
108040 break;
108041 case 23: /* cmd ::= RELEASE savepoint_opt nm */
108043 sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
108045 break;
108046 case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
108048 sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
108050 break;
108051 case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
108053 sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy4,0,0,yymsp[-2].minor.yy4);
108055 break;
108056 case 27: /* createkw ::= CREATE */
108058 pParse->db->lookaside.bEnabled = 0;
108059 yygotominor.yy0 = yymsp[0].minor.yy0;
108061 break;
108062 case 28: /* ifnotexists ::= */
108063 case 31: /* temp ::= */ yytestcase(yyruleno==31);
108064 case 70: /* autoinc ::= */ yytestcase(yyruleno==70);
108065 case 83: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==83);
108066 case 85: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==85);
108067 case 87: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==87);
108068 case 98: /* defer_subclause_opt ::= */ yytestcase(yyruleno==98);
108069 case 109: /* ifexists ::= */ yytestcase(yyruleno==109);
108070 case 120: /* distinct ::= ALL */ yytestcase(yyruleno==120);
108071 case 121: /* distinct ::= */ yytestcase(yyruleno==121);
108072 case 222: /* between_op ::= BETWEEN */ yytestcase(yyruleno==222);
108073 case 225: /* in_op ::= IN */ yytestcase(yyruleno==225);
108074 {yygotominor.yy4 = 0;}
108075 break;
108076 case 29: /* ifnotexists ::= IF NOT EXISTS */
108077 case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
108078 case 71: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==71);
108079 case 86: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==86);
108080 case 108: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==108);
108081 case 119: /* distinct ::= DISTINCT */ yytestcase(yyruleno==119);
108082 case 223: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==223);
108083 case 226: /* in_op ::= NOT IN */ yytestcase(yyruleno==226);
108084 {yygotominor.yy4 = 1;}
108085 break;
108086 case 32: /* create_table_args ::= LP columnlist conslist_opt RP */
108088 sqlite3EndTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0);
108090 break;
108091 case 33: /* create_table_args ::= AS select */
108093 sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy387);
108094 sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy387);
108096 break;
108097 case 36: /* column ::= columnid type carglist */
108099 yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
108100 yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
108102 break;
108103 case 37: /* columnid ::= nm */
108105 sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
108106 yygotominor.yy0 = yymsp[0].minor.yy0;
108108 break;
108109 case 38: /* id ::= ID */
108110 case 39: /* id ::= INDEXED */ yytestcase(yyruleno==39);
108111 case 40: /* ids ::= ID|STRING */ yytestcase(yyruleno==40);
108112 case 41: /* nm ::= id */ yytestcase(yyruleno==41);
108113 case 42: /* nm ::= STRING */ yytestcase(yyruleno==42);
108114 case 43: /* nm ::= JOIN_KW */ yytestcase(yyruleno==43);
108115 case 46: /* typetoken ::= typename */ yytestcase(yyruleno==46);
108116 case 49: /* typename ::= ids */ yytestcase(yyruleno==49);
108117 case 127: /* as ::= AS nm */ yytestcase(yyruleno==127);
108118 case 128: /* as ::= ids */ yytestcase(yyruleno==128);
108119 case 138: /* dbnm ::= DOT nm */ yytestcase(yyruleno==138);
108120 case 147: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==147);
108121 case 251: /* collate ::= COLLATE ids */ yytestcase(yyruleno==251);
108122 case 260: /* nmnum ::= plus_num */ yytestcase(yyruleno==260);
108123 case 261: /* nmnum ::= nm */ yytestcase(yyruleno==261);
108124 case 262: /* nmnum ::= ON */ yytestcase(yyruleno==262);
108125 case 263: /* nmnum ::= DELETE */ yytestcase(yyruleno==263);
108126 case 264: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==264);
108127 case 265: /* plus_num ::= plus_opt number */ yytestcase(yyruleno==265);
108128 case 266: /* minus_num ::= MINUS number */ yytestcase(yyruleno==266);
108129 case 267: /* number ::= INTEGER|FLOAT */ yytestcase(yyruleno==267);
108130 case 285: /* trnm ::= nm */ yytestcase(yyruleno==285);
108131 {yygotominor.yy0 = yymsp[0].minor.yy0;}
108132 break;
108133 case 45: /* type ::= typetoken */
108134 {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
108135 break;
108136 case 47: /* typetoken ::= typename LP signed RP */
108138 yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
108139 yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
108141 break;
108142 case 48: /* typetoken ::= typename LP signed COMMA signed RP */
108144 yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
108145 yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
108147 break;
108148 case 50: /* typename ::= typename ids */
108149 {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);}
108150 break;
108151 case 57: /* ccons ::= DEFAULT term */
108152 case 59: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==59);
108153 {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy118);}
108154 break;
108155 case 58: /* ccons ::= DEFAULT LP expr RP */
108156 {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy118);}
108157 break;
108158 case 60: /* ccons ::= DEFAULT MINUS term */
108160 ExprSpan v;
108161 v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy118.pExpr, 0, 0);
108162 v.zStart = yymsp[-1].minor.yy0.z;
108163 v.zEnd = yymsp[0].minor.yy118.zEnd;
108164 sqlite3AddDefaultValue(pParse,&v);
108166 break;
108167 case 61: /* ccons ::= DEFAULT id */
108169 ExprSpan v;
108170 spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
108171 sqlite3AddDefaultValue(pParse,&v);
108173 break;
108174 case 63: /* ccons ::= NOT NULL onconf */
108175 {sqlite3AddNotNull(pParse, yymsp[0].minor.yy4);}
108176 break;
108177 case 64: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
108178 {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy4,yymsp[0].minor.yy4,yymsp[-2].minor.yy4);}
108179 break;
108180 case 65: /* ccons ::= UNIQUE onconf */
108181 {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy4,0,0,0,0);}
108182 break;
108183 case 66: /* ccons ::= CHECK LP expr RP */
108184 {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy118.pExpr);}
108185 break;
108186 case 67: /* ccons ::= REFERENCES nm idxlist_opt refargs */
108187 {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy322,yymsp[0].minor.yy4);}
108188 break;
108189 case 68: /* ccons ::= defer_subclause */
108190 {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy4);}
108191 break;
108192 case 69: /* ccons ::= COLLATE ids */
108193 {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
108194 break;
108195 case 72: /* refargs ::= */
108196 { yygotominor.yy4 = OE_None*0x0101; /* EV: R-19803-45884 */}
108197 break;
108198 case 73: /* refargs ::= refargs refarg */
108199 { yygotominor.yy4 = (yymsp[-1].minor.yy4 & ~yymsp[0].minor.yy215.mask) | yymsp[0].minor.yy215.value; }
108200 break;
108201 case 74: /* refarg ::= MATCH nm */
108202 case 75: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==75);
108203 { yygotominor.yy215.value = 0; yygotominor.yy215.mask = 0x000000; }
108204 break;
108205 case 76: /* refarg ::= ON DELETE refact */
108206 { yygotominor.yy215.value = yymsp[0].minor.yy4; yygotominor.yy215.mask = 0x0000ff; }
108207 break;
108208 case 77: /* refarg ::= ON UPDATE refact */
108209 { yygotominor.yy215.value = yymsp[0].minor.yy4<<8; yygotominor.yy215.mask = 0x00ff00; }
108210 break;
108211 case 78: /* refact ::= SET NULL */
108212 { yygotominor.yy4 = OE_SetNull; /* EV: R-33326-45252 */}
108213 break;
108214 case 79: /* refact ::= SET DEFAULT */
108215 { yygotominor.yy4 = OE_SetDflt; /* EV: R-33326-45252 */}
108216 break;
108217 case 80: /* refact ::= CASCADE */
108218 { yygotominor.yy4 = OE_Cascade; /* EV: R-33326-45252 */}
108219 break;
108220 case 81: /* refact ::= RESTRICT */
108221 { yygotominor.yy4 = OE_Restrict; /* EV: R-33326-45252 */}
108222 break;
108223 case 82: /* refact ::= NO ACTION */
108224 { yygotominor.yy4 = OE_None; /* EV: R-33326-45252 */}
108225 break;
108226 case 84: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
108227 case 99: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==99);
108228 case 101: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==101);
108229 case 104: /* resolvetype ::= raisetype */ yytestcase(yyruleno==104);
108230 {yygotominor.yy4 = yymsp[0].minor.yy4;}
108231 break;
108232 case 88: /* conslist_opt ::= */
108233 {yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
108234 break;
108235 case 89: /* conslist_opt ::= COMMA conslist */
108236 {yygotominor.yy0 = yymsp[-1].minor.yy0;}
108237 break;
108238 case 94: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
108239 {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy322,yymsp[0].minor.yy4,yymsp[-2].minor.yy4,0);}
108240 break;
108241 case 95: /* tcons ::= UNIQUE LP idxlist RP onconf */
108242 {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy322,yymsp[0].minor.yy4,0,0,0,0);}
108243 break;
108244 case 96: /* tcons ::= CHECK LP expr RP onconf */
108245 {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy118.pExpr);}
108246 break;
108247 case 97: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
108249 sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy322, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy322, yymsp[-1].minor.yy4);
108250 sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy4);
108252 break;
108253 case 100: /* onconf ::= */
108254 {yygotominor.yy4 = OE_Default;}
108255 break;
108256 case 102: /* orconf ::= */
108257 {yygotominor.yy210 = OE_Default;}
108258 break;
108259 case 103: /* orconf ::= OR resolvetype */
108260 {yygotominor.yy210 = (u8)yymsp[0].minor.yy4;}
108261 break;
108262 case 105: /* resolvetype ::= IGNORE */
108263 {yygotominor.yy4 = OE_Ignore;}
108264 break;
108265 case 106: /* resolvetype ::= REPLACE */
108266 {yygotominor.yy4 = OE_Replace;}
108267 break;
108268 case 107: /* cmd ::= DROP TABLE ifexists fullname */
108270 sqlite3DropTable(pParse, yymsp[0].minor.yy259, 0, yymsp[-1].minor.yy4);
108272 break;
108273 case 110: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
108275 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);
108277 break;
108278 case 111: /* cmd ::= DROP VIEW ifexists fullname */
108280 sqlite3DropTable(pParse, yymsp[0].minor.yy259, 1, yymsp[-1].minor.yy4);
108282 break;
108283 case 112: /* cmd ::= select */
108285 SelectDest dest = {SRT_Output, 0, 0, 0, 0};
108286 sqlite3Select(pParse, yymsp[0].minor.yy387, &dest);
108287 sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy387);
108289 break;
108290 case 113: /* select ::= oneselect */
108291 {yygotominor.yy387 = yymsp[0].minor.yy387;}
108292 break;
108293 case 114: /* select ::= select multiselect_op oneselect */
108295 if( yymsp[0].minor.yy387 ){
108296 yymsp[0].minor.yy387->op = (u8)yymsp[-1].minor.yy4;
108297 yymsp[0].minor.yy387->pPrior = yymsp[-2].minor.yy387;
108298 }else{
108299 sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy387);
108301 yygotominor.yy387 = yymsp[0].minor.yy387;
108303 break;
108304 case 116: /* multiselect_op ::= UNION ALL */
108305 {yygotominor.yy4 = TK_ALL;}
108306 break;
108307 case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
108309 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);
108311 break;
108312 case 122: /* sclp ::= selcollist COMMA */
108313 case 247: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==247);
108314 {yygotominor.yy322 = yymsp[-1].minor.yy322;}
108315 break;
108316 case 123: /* sclp ::= */
108317 case 151: /* orderby_opt ::= */ yytestcase(yyruleno==151);
108318 case 159: /* groupby_opt ::= */ yytestcase(yyruleno==159);
108319 case 240: /* exprlist ::= */ yytestcase(yyruleno==240);
108320 case 246: /* idxlist_opt ::= */ yytestcase(yyruleno==246);
108321 {yygotominor.yy322 = 0;}
108322 break;
108323 case 124: /* selcollist ::= sclp expr as */
108325 yygotominor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy322, yymsp[-1].minor.yy118.pExpr);
108326 if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[0].minor.yy0, 1);
108327 sqlite3ExprListSetSpan(pParse,yygotominor.yy322,&yymsp[-1].minor.yy118);
108329 break;
108330 case 125: /* selcollist ::= sclp STAR */
108332 Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
108333 yygotominor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy322, p);
108335 break;
108336 case 126: /* selcollist ::= sclp nm DOT STAR */
108338 Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
108339 Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
108340 Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
108341 yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy322, pDot);
108343 break;
108344 case 129: /* as ::= */
108345 {yygotominor.yy0.n = 0;}
108346 break;
108347 case 130: /* from ::= */
108348 {yygotominor.yy259 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy259));}
108349 break;
108350 case 131: /* from ::= FROM seltablist */
108352 yygotominor.yy259 = yymsp[0].minor.yy259;
108353 sqlite3SrcListShiftJoinType(yygotominor.yy259);
108355 break;
108356 case 132: /* stl_prefix ::= seltablist joinop */
108358 yygotominor.yy259 = yymsp[-1].minor.yy259;
108359 if( ALWAYS(yygotominor.yy259 && yygotominor.yy259->nSrc>0) ) yygotominor.yy259->a[yygotominor.yy259->nSrc-1].jointype = (u8)yymsp[0].minor.yy4;
108361 break;
108362 case 133: /* stl_prefix ::= */
108363 {yygotominor.yy259 = 0;}
108364 break;
108365 case 134: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
108367 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);
108368 sqlite3SrcListIndexedBy(pParse, yygotominor.yy259, &yymsp[-2].minor.yy0);
108370 break;
108371 case 135: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
108373 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);
108375 break;
108376 case 136: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
108378 if( yymsp[-6].minor.yy259==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy314==0 && yymsp[0].minor.yy384==0 ){
108379 yygotominor.yy259 = yymsp[-4].minor.yy259;
108380 }else{
108381 Select *pSubquery;
108382 sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy259);
108383 pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy259,0,0,0,0,0,0,0);
108384 yygotominor.yy259 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy259,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy314,yymsp[0].minor.yy384);
108387 break;
108388 case 137: /* dbnm ::= */
108389 case 146: /* indexed_opt ::= */ yytestcase(yyruleno==146);
108390 {yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
108391 break;
108392 case 139: /* fullname ::= nm dbnm */
108393 {yygotominor.yy259 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
108394 break;
108395 case 140: /* joinop ::= COMMA|JOIN */
108396 { yygotominor.yy4 = JT_INNER; }
108397 break;
108398 case 141: /* joinop ::= JOIN_KW JOIN */
108399 { yygotominor.yy4 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
108400 break;
108401 case 142: /* joinop ::= JOIN_KW nm JOIN */
108402 { yygotominor.yy4 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
108403 break;
108404 case 143: /* joinop ::= JOIN_KW nm nm JOIN */
108405 { yygotominor.yy4 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
108406 break;
108407 case 144: /* on_opt ::= ON expr */
108408 case 155: /* sortitem ::= expr */ yytestcase(yyruleno==155);
108409 case 162: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==162);
108410 case 169: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==169);
108411 case 235: /* case_else ::= ELSE expr */ yytestcase(yyruleno==235);
108412 case 237: /* case_operand ::= expr */ yytestcase(yyruleno==237);
108413 {yygotominor.yy314 = yymsp[0].minor.yy118.pExpr;}
108414 break;
108415 case 145: /* on_opt ::= */
108416 case 161: /* having_opt ::= */ yytestcase(yyruleno==161);
108417 case 168: /* where_opt ::= */ yytestcase(yyruleno==168);
108418 case 236: /* case_else ::= */ yytestcase(yyruleno==236);
108419 case 238: /* case_operand ::= */ yytestcase(yyruleno==238);
108420 {yygotominor.yy314 = 0;}
108421 break;
108422 case 148: /* indexed_opt ::= NOT INDEXED */
108423 {yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
108424 break;
108425 case 149: /* using_opt ::= USING LP inscollist RP */
108426 case 181: /* inscollist_opt ::= LP inscollist RP */ yytestcase(yyruleno==181);
108427 {yygotominor.yy384 = yymsp[-1].minor.yy384;}
108428 break;
108429 case 150: /* using_opt ::= */
108430 case 180: /* inscollist_opt ::= */ yytestcase(yyruleno==180);
108431 {yygotominor.yy384 = 0;}
108432 break;
108433 case 152: /* orderby_opt ::= ORDER BY sortlist */
108434 case 160: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==160);
108435 case 239: /* exprlist ::= nexprlist */ yytestcase(yyruleno==239);
108436 {yygotominor.yy322 = yymsp[0].minor.yy322;}
108437 break;
108438 case 153: /* sortlist ::= sortlist COMMA sortitem sortorder */
108440 yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy322,yymsp[-1].minor.yy314);
108441 if( yygotominor.yy322 ) yygotominor.yy322->a[yygotominor.yy322->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy4;
108443 break;
108444 case 154: /* sortlist ::= sortitem sortorder */
108446 yygotominor.yy322 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy314);
108447 if( yygotominor.yy322 && ALWAYS(yygotominor.yy322->a) ) yygotominor.yy322->a[0].sortOrder = (u8)yymsp[0].minor.yy4;
108449 break;
108450 case 156: /* sortorder ::= ASC */
108451 case 158: /* sortorder ::= */ yytestcase(yyruleno==158);
108452 {yygotominor.yy4 = SQLITE_SO_ASC;}
108453 break;
108454 case 157: /* sortorder ::= DESC */
108455 {yygotominor.yy4 = SQLITE_SO_DESC;}
108456 break;
108457 case 163: /* limit_opt ::= */
108458 {yygotominor.yy292.pLimit = 0; yygotominor.yy292.pOffset = 0;}
108459 break;
108460 case 164: /* limit_opt ::= LIMIT expr */
108461 {yygotominor.yy292.pLimit = yymsp[0].minor.yy118.pExpr; yygotominor.yy292.pOffset = 0;}
108462 break;
108463 case 165: /* limit_opt ::= LIMIT expr OFFSET expr */
108464 {yygotominor.yy292.pLimit = yymsp[-2].minor.yy118.pExpr; yygotominor.yy292.pOffset = yymsp[0].minor.yy118.pExpr;}
108465 break;
108466 case 166: /* limit_opt ::= LIMIT expr COMMA expr */
108467 {yygotominor.yy292.pOffset = yymsp[-2].minor.yy118.pExpr; yygotominor.yy292.pLimit = yymsp[0].minor.yy118.pExpr;}
108468 break;
108469 case 167: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */
108471 sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy259, &yymsp[-1].minor.yy0);
108472 sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy259,yymsp[0].minor.yy314);
108474 break;
108475 case 170: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */
108477 sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy259, &yymsp[-3].minor.yy0);
108478 sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy322,"set list");
108479 sqlite3Update(pParse,yymsp[-4].minor.yy259,yymsp[-1].minor.yy322,yymsp[0].minor.yy314,yymsp[-5].minor.yy210);
108481 break;
108482 case 171: /* setlist ::= setlist COMMA nm EQ expr */
108484 yygotominor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy322, yymsp[0].minor.yy118.pExpr);
108485 sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
108487 break;
108488 case 172: /* setlist ::= nm EQ expr */
108490 yygotominor.yy322 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy118.pExpr);
108491 sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
108493 break;
108494 case 173: /* cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP */
108495 {sqlite3Insert(pParse, yymsp[-5].minor.yy259, yymsp[-1].minor.yy322, 0, yymsp[-4].minor.yy384, yymsp[-7].minor.yy210);}
108496 break;
108497 case 174: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */
108498 {sqlite3Insert(pParse, yymsp[-2].minor.yy259, 0, yymsp[0].minor.yy387, yymsp[-1].minor.yy384, yymsp[-4].minor.yy210);}
108499 break;
108500 case 175: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
108501 {sqlite3Insert(pParse, yymsp[-3].minor.yy259, 0, 0, yymsp[-2].minor.yy384, yymsp[-5].minor.yy210);}
108502 break;
108503 case 176: /* insert_cmd ::= INSERT orconf */
108504 {yygotominor.yy210 = yymsp[0].minor.yy210;}
108505 break;
108506 case 177: /* insert_cmd ::= REPLACE */
108507 {yygotominor.yy210 = OE_Replace;}
108508 break;
108509 case 178: /* itemlist ::= itemlist COMMA expr */
108510 case 241: /* nexprlist ::= nexprlist COMMA expr */ yytestcase(yyruleno==241);
108511 {yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy322,yymsp[0].minor.yy118.pExpr);}
108512 break;
108513 case 179: /* itemlist ::= expr */
108514 case 242: /* nexprlist ::= expr */ yytestcase(yyruleno==242);
108515 {yygotominor.yy322 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy118.pExpr);}
108516 break;
108517 case 182: /* inscollist ::= inscollist COMMA nm */
108518 {yygotominor.yy384 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy384,&yymsp[0].minor.yy0);}
108519 break;
108520 case 183: /* inscollist ::= nm */
108521 {yygotominor.yy384 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
108522 break;
108523 case 184: /* expr ::= term */
108524 {yygotominor.yy118 = yymsp[0].minor.yy118;}
108525 break;
108526 case 185: /* expr ::= LP expr RP */
108527 {yygotominor.yy118.pExpr = yymsp[-1].minor.yy118.pExpr; spanSet(&yygotominor.yy118,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
108528 break;
108529 case 186: /* term ::= NULL */
108530 case 191: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==191);
108531 case 192: /* term ::= STRING */ yytestcase(yyruleno==192);
108532 {spanExpr(&yygotominor.yy118, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
108533 break;
108534 case 187: /* expr ::= id */
108535 case 188: /* expr ::= JOIN_KW */ yytestcase(yyruleno==188);
108536 {spanExpr(&yygotominor.yy118, pParse, TK_ID, &yymsp[0].minor.yy0);}
108537 break;
108538 case 189: /* expr ::= nm DOT nm */
108540 Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
108541 Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
108542 yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
108543 spanSet(&yygotominor.yy118,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
108545 break;
108546 case 190: /* expr ::= nm DOT nm DOT nm */
108548 Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
108549 Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
108550 Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
108551 Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
108552 yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
108553 spanSet(&yygotominor.yy118,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
108555 break;
108556 case 193: /* expr ::= REGISTER */
108558 /* When doing a nested parse, one can include terms in an expression
108559 ** that look like this: #1 #2 ... These terms refer to registers
108560 ** in the virtual machine. #N is the N-th register. */
108561 if( pParse->nested==0 ){
108562 sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
108563 yygotominor.yy118.pExpr = 0;
108564 }else{
108565 yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
108566 if( yygotominor.yy118.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy118.pExpr->iTable);
108568 spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
108570 break;
108571 case 194: /* expr ::= VARIABLE */
108573 spanExpr(&yygotominor.yy118, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
108574 sqlite3ExprAssignVarNumber(pParse, yygotominor.yy118.pExpr);
108575 spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
108577 break;
108578 case 195: /* expr ::= expr COLLATE ids */
108580 yygotominor.yy118.pExpr = sqlite3ExprSetCollByToken(pParse, yymsp[-2].minor.yy118.pExpr, &yymsp[0].minor.yy0);
108581 yygotominor.yy118.zStart = yymsp[-2].minor.yy118.zStart;
108582 yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
108584 break;
108585 case 196: /* expr ::= CAST LP expr AS typetoken RP */
108587 yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy118.pExpr, 0, &yymsp[-1].minor.yy0);
108588 spanSet(&yygotominor.yy118,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
108590 break;
108591 case 197: /* expr ::= ID LP distinct exprlist RP */
108593 if( yymsp[-1].minor.yy322 && yymsp[-1].minor.yy322->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
108594 sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
108596 yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy322, &yymsp[-4].minor.yy0);
108597 spanSet(&yygotominor.yy118,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
108598 if( yymsp[-2].minor.yy4 && yygotominor.yy118.pExpr ){
108599 yygotominor.yy118.pExpr->flags |= EP_Distinct;
108602 break;
108603 case 198: /* expr ::= ID LP STAR RP */
108605 yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
108606 spanSet(&yygotominor.yy118,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
108608 break;
108609 case 199: /* term ::= CTIME_KW */
108611 /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
108612 ** treated as functions that return constants */
108613 yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
108614 if( yygotominor.yy118.pExpr ){
108615 yygotominor.yy118.pExpr->op = TK_CONST_FUNC;
108617 spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
108619 break;
108620 case 200: /* expr ::= expr AND expr */
108621 case 201: /* expr ::= expr OR expr */ yytestcase(yyruleno==201);
108622 case 202: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==202);
108623 case 203: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==203);
108624 case 204: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==204);
108625 case 205: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==205);
108626 case 206: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==206);
108627 case 207: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==207);
108628 {spanBinaryExpr(&yygotominor.yy118,pParse,yymsp[-1].major,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy118);}
108629 break;
108630 case 208: /* likeop ::= LIKE_KW */
108631 case 210: /* likeop ::= MATCH */ yytestcase(yyruleno==210);
108632 {yygotominor.yy342.eOperator = yymsp[0].minor.yy0; yygotominor.yy342.not = 0;}
108633 break;
108634 case 209: /* likeop ::= NOT LIKE_KW */
108635 case 211: /* likeop ::= NOT MATCH */ yytestcase(yyruleno==211);
108636 {yygotominor.yy342.eOperator = yymsp[0].minor.yy0; yygotominor.yy342.not = 1;}
108637 break;
108638 case 212: /* expr ::= expr likeop expr */
108640 ExprList *pList;
108641 pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy118.pExpr);
108642 pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy118.pExpr);
108643 yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy342.eOperator);
108644 if( yymsp[-1].minor.yy342.not ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
108645 yygotominor.yy118.zStart = yymsp[-2].minor.yy118.zStart;
108646 yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
108647 if( yygotominor.yy118.pExpr ) yygotominor.yy118.pExpr->flags |= EP_InfixFunc;
108649 break;
108650 case 213: /* expr ::= expr likeop expr ESCAPE expr */
108652 ExprList *pList;
108653 pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
108654 pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy118.pExpr);
108655 pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy118.pExpr);
108656 yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy342.eOperator);
108657 if( yymsp[-3].minor.yy342.not ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
108658 yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
108659 yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
108660 if( yygotominor.yy118.pExpr ) yygotominor.yy118.pExpr->flags |= EP_InfixFunc;
108662 break;
108663 case 214: /* expr ::= expr ISNULL|NOTNULL */
108664 {spanUnaryPostfix(&yygotominor.yy118,pParse,yymsp[0].major,&yymsp[-1].minor.yy118,&yymsp[0].minor.yy0);}
108665 break;
108666 case 215: /* expr ::= expr NOT NULL */
108667 {spanUnaryPostfix(&yygotominor.yy118,pParse,TK_NOTNULL,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy0);}
108668 break;
108669 case 216: /* expr ::= expr IS expr */
108671 spanBinaryExpr(&yygotominor.yy118,pParse,TK_IS,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy118);
108672 binaryToUnaryIfNull(pParse, yymsp[0].minor.yy118.pExpr, yygotominor.yy118.pExpr, TK_ISNULL);
108674 break;
108675 case 217: /* expr ::= expr IS NOT expr */
108677 spanBinaryExpr(&yygotominor.yy118,pParse,TK_ISNOT,&yymsp[-3].minor.yy118,&yymsp[0].minor.yy118);
108678 binaryToUnaryIfNull(pParse, yymsp[0].minor.yy118.pExpr, yygotominor.yy118.pExpr, TK_NOTNULL);
108680 break;
108681 case 218: /* expr ::= NOT expr */
108682 case 219: /* expr ::= BITNOT expr */ yytestcase(yyruleno==219);
108683 {spanUnaryPrefix(&yygotominor.yy118,pParse,yymsp[-1].major,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
108684 break;
108685 case 220: /* expr ::= MINUS expr */
108686 {spanUnaryPrefix(&yygotominor.yy118,pParse,TK_UMINUS,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
108687 break;
108688 case 221: /* expr ::= PLUS expr */
108689 {spanUnaryPrefix(&yygotominor.yy118,pParse,TK_UPLUS,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
108690 break;
108691 case 224: /* expr ::= expr between_op expr AND expr */
108693 ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
108694 pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy118.pExpr);
108695 yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy118.pExpr, 0, 0);
108696 if( yygotominor.yy118.pExpr ){
108697 yygotominor.yy118.pExpr->x.pList = pList;
108698 }else{
108699 sqlite3ExprListDelete(pParse->db, pList);
108701 if( yymsp[-3].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
108702 yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
108703 yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
108705 break;
108706 case 227: /* expr ::= expr in_op LP exprlist RP */
108708 if( yymsp[-1].minor.yy322==0 ){
108709 /* Expressions of the form
108711 ** expr1 IN ()
108712 ** expr1 NOT IN ()
108714 ** simplify to constants 0 (false) and 1 (true), respectively,
108715 ** regardless of the value of expr1.
108717 yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy4]);
108718 sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy118.pExpr);
108719 }else{
108720 yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy118.pExpr, 0, 0);
108721 if( yygotominor.yy118.pExpr ){
108722 yygotominor.yy118.pExpr->x.pList = yymsp[-1].minor.yy322;
108723 sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
108724 }else{
108725 sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy322);
108727 if( yymsp[-3].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
108729 yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
108730 yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
108732 break;
108733 case 228: /* expr ::= LP select RP */
108735 yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
108736 if( yygotominor.yy118.pExpr ){
108737 yygotominor.yy118.pExpr->x.pSelect = yymsp[-1].minor.yy387;
108738 ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect);
108739 sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
108740 }else{
108741 sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
108743 yygotominor.yy118.zStart = yymsp[-2].minor.yy0.z;
108744 yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
108746 break;
108747 case 229: /* expr ::= expr in_op LP select RP */
108749 yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy118.pExpr, 0, 0);
108750 if( yygotominor.yy118.pExpr ){
108751 yygotominor.yy118.pExpr->x.pSelect = yymsp[-1].minor.yy387;
108752 ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect);
108753 sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
108754 }else{
108755 sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
108757 if( yymsp[-3].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
108758 yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
108759 yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
108761 break;
108762 case 230: /* expr ::= expr in_op nm dbnm */
108764 SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
108765 yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy118.pExpr, 0, 0);
108766 if( yygotominor.yy118.pExpr ){
108767 yygotominor.yy118.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
108768 ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect);
108769 sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
108770 }else{
108771 sqlite3SrcListDelete(pParse->db, pSrc);
108773 if( yymsp[-2].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
108774 yygotominor.yy118.zStart = yymsp[-3].minor.yy118.zStart;
108775 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];
108777 break;
108778 case 231: /* expr ::= EXISTS LP select RP */
108780 Expr *p = yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
108781 if( p ){
108782 p->x.pSelect = yymsp[-1].minor.yy387;
108783 ExprSetProperty(p, EP_xIsSelect);
108784 sqlite3ExprSetHeight(pParse, p);
108785 }else{
108786 sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
108788 yygotominor.yy118.zStart = yymsp[-3].minor.yy0.z;
108789 yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
108791 break;
108792 case 232: /* expr ::= CASE case_operand case_exprlist case_else END */
108794 yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy314, yymsp[-1].minor.yy314, 0);
108795 if( yygotominor.yy118.pExpr ){
108796 yygotominor.yy118.pExpr->x.pList = yymsp[-2].minor.yy322;
108797 sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
108798 }else{
108799 sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy322);
108801 yygotominor.yy118.zStart = yymsp[-4].minor.yy0.z;
108802 yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
108804 break;
108805 case 233: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
108807 yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy322, yymsp[-2].minor.yy118.pExpr);
108808 yygotominor.yy322 = sqlite3ExprListAppend(pParse,yygotominor.yy322, yymsp[0].minor.yy118.pExpr);
108810 break;
108811 case 234: /* case_exprlist ::= WHEN expr THEN expr */
108813 yygotominor.yy322 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
108814 yygotominor.yy322 = sqlite3ExprListAppend(pParse,yygotominor.yy322, yymsp[0].minor.yy118.pExpr);
108816 break;
108817 case 243: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP */
108819 sqlite3CreateIndex(pParse, &yymsp[-6].minor.yy0, &yymsp[-5].minor.yy0,
108820 sqlite3SrcListAppend(pParse->db,0,&yymsp[-3].minor.yy0,0), yymsp[-1].minor.yy322, yymsp[-9].minor.yy4,
108821 &yymsp[-10].minor.yy0, &yymsp[0].minor.yy0, SQLITE_SO_ASC, yymsp[-7].minor.yy4);
108823 break;
108824 case 244: /* uniqueflag ::= UNIQUE */
108825 case 298: /* raisetype ::= ABORT */ yytestcase(yyruleno==298);
108826 {yygotominor.yy4 = OE_Abort;}
108827 break;
108828 case 245: /* uniqueflag ::= */
108829 {yygotominor.yy4 = OE_None;}
108830 break;
108831 case 248: /* idxlist ::= idxlist COMMA nm collate sortorder */
108833 Expr *p = 0;
108834 if( yymsp[-1].minor.yy0.n>0 ){
108835 p = sqlite3Expr(pParse->db, TK_COLUMN, 0);
108836 sqlite3ExprSetCollByToken(pParse, p, &yymsp[-1].minor.yy0);
108838 yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy322, p);
108839 sqlite3ExprListSetName(pParse,yygotominor.yy322,&yymsp[-2].minor.yy0,1);
108840 sqlite3ExprListCheckLength(pParse, yygotominor.yy322, "index");
108841 if( yygotominor.yy322 ) yygotominor.yy322->a[yygotominor.yy322->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy4;
108843 break;
108844 case 249: /* idxlist ::= nm collate sortorder */
108846 Expr *p = 0;
108847 if( yymsp[-1].minor.yy0.n>0 ){
108848 p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
108849 sqlite3ExprSetCollByToken(pParse, p, &yymsp[-1].minor.yy0);
108851 yygotominor.yy322 = sqlite3ExprListAppend(pParse,0, p);
108852 sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
108853 sqlite3ExprListCheckLength(pParse, yygotominor.yy322, "index");
108854 if( yygotominor.yy322 ) yygotominor.yy322->a[yygotominor.yy322->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy4;
108856 break;
108857 case 250: /* collate ::= */
108858 {yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
108859 break;
108860 case 252: /* cmd ::= DROP INDEX ifexists fullname */
108861 {sqlite3DropIndex(pParse, yymsp[0].minor.yy259, yymsp[-1].minor.yy4);}
108862 break;
108863 case 253: /* cmd ::= VACUUM */
108864 case 254: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==254);
108865 {sqlite3Vacuum(pParse);}
108866 break;
108867 case 255: /* cmd ::= PRAGMA nm dbnm */
108868 {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
108869 break;
108870 case 256: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
108871 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
108872 break;
108873 case 257: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
108874 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
108875 break;
108876 case 258: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
108877 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
108878 break;
108879 case 259: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
108880 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
108881 break;
108882 case 270: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
108884 Token all;
108885 all.z = yymsp[-3].minor.yy0.z;
108886 all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
108887 sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy203, &all);
108889 break;
108890 case 271: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
108892 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);
108893 yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
108895 break;
108896 case 272: /* trigger_time ::= BEFORE */
108897 case 275: /* trigger_time ::= */ yytestcase(yyruleno==275);
108898 { yygotominor.yy4 = TK_BEFORE; }
108899 break;
108900 case 273: /* trigger_time ::= AFTER */
108901 { yygotominor.yy4 = TK_AFTER; }
108902 break;
108903 case 274: /* trigger_time ::= INSTEAD OF */
108904 { yygotominor.yy4 = TK_INSTEAD;}
108905 break;
108906 case 276: /* trigger_event ::= DELETE|INSERT */
108907 case 277: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==277);
108908 {yygotominor.yy90.a = yymsp[0].major; yygotominor.yy90.b = 0;}
108909 break;
108910 case 278: /* trigger_event ::= UPDATE OF inscollist */
108911 {yygotominor.yy90.a = TK_UPDATE; yygotominor.yy90.b = yymsp[0].minor.yy384;}
108912 break;
108913 case 281: /* when_clause ::= */
108914 case 303: /* key_opt ::= */ yytestcase(yyruleno==303);
108915 { yygotominor.yy314 = 0; }
108916 break;
108917 case 282: /* when_clause ::= WHEN expr */
108918 case 304: /* key_opt ::= KEY expr */ yytestcase(yyruleno==304);
108919 { yygotominor.yy314 = yymsp[0].minor.yy118.pExpr; }
108920 break;
108921 case 283: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
108923 assert( yymsp[-2].minor.yy203!=0 );
108924 yymsp[-2].minor.yy203->pLast->pNext = yymsp[-1].minor.yy203;
108925 yymsp[-2].minor.yy203->pLast = yymsp[-1].minor.yy203;
108926 yygotominor.yy203 = yymsp[-2].minor.yy203;
108928 break;
108929 case 284: /* trigger_cmd_list ::= trigger_cmd SEMI */
108931 assert( yymsp[-1].minor.yy203!=0 );
108932 yymsp[-1].minor.yy203->pLast = yymsp[-1].minor.yy203;
108933 yygotominor.yy203 = yymsp[-1].minor.yy203;
108935 break;
108936 case 286: /* trnm ::= nm DOT nm */
108938 yygotominor.yy0 = yymsp[0].minor.yy0;
108939 sqlite3ErrorMsg(pParse,
108940 "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
108941 "statements within triggers");
108943 break;
108944 case 288: /* tridxby ::= INDEXED BY nm */
108946 sqlite3ErrorMsg(pParse,
108947 "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
108948 "within triggers");
108950 break;
108951 case 289: /* tridxby ::= NOT INDEXED */
108953 sqlite3ErrorMsg(pParse,
108954 "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
108955 "within triggers");
108957 break;
108958 case 290: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
108959 { yygotominor.yy203 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy322, yymsp[0].minor.yy314, yymsp[-5].minor.yy210); }
108960 break;
108961 case 291: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP */
108962 {yygotominor.yy203 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy384, yymsp[-1].minor.yy322, 0, yymsp[-7].minor.yy210);}
108963 break;
108964 case 292: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
108965 {yygotominor.yy203 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy384, 0, yymsp[0].minor.yy387, yymsp[-4].minor.yy210);}
108966 break;
108967 case 293: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
108968 {yygotominor.yy203 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy314);}
108969 break;
108970 case 294: /* trigger_cmd ::= select */
108971 {yygotominor.yy203 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy387); }
108972 break;
108973 case 295: /* expr ::= RAISE LP IGNORE RP */
108975 yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0);
108976 if( yygotominor.yy118.pExpr ){
108977 yygotominor.yy118.pExpr->affinity = OE_Ignore;
108979 yygotominor.yy118.zStart = yymsp[-3].minor.yy0.z;
108980 yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
108982 break;
108983 case 296: /* expr ::= RAISE LP raisetype COMMA nm RP */
108985 yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
108986 if( yygotominor.yy118.pExpr ) {
108987 yygotominor.yy118.pExpr->affinity = (char)yymsp[-3].minor.yy4;
108989 yygotominor.yy118.zStart = yymsp[-5].minor.yy0.z;
108990 yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
108992 break;
108993 case 297: /* raisetype ::= ROLLBACK */
108994 {yygotominor.yy4 = OE_Rollback;}
108995 break;
108996 case 299: /* raisetype ::= FAIL */
108997 {yygotominor.yy4 = OE_Fail;}
108998 break;
108999 case 300: /* cmd ::= DROP TRIGGER ifexists fullname */
109001 sqlite3DropTrigger(pParse,yymsp[0].minor.yy259,yymsp[-1].minor.yy4);
109003 break;
109004 case 301: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
109006 sqlite3Attach(pParse, yymsp[-3].minor.yy118.pExpr, yymsp[-1].minor.yy118.pExpr, yymsp[0].minor.yy314);
109008 break;
109009 case 302: /* cmd ::= DETACH database_kw_opt expr */
109011 sqlite3Detach(pParse, yymsp[0].minor.yy118.pExpr);
109013 break;
109014 case 307: /* cmd ::= REINDEX */
109015 {sqlite3Reindex(pParse, 0, 0);}
109016 break;
109017 case 308: /* cmd ::= REINDEX nm dbnm */
109018 {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
109019 break;
109020 case 309: /* cmd ::= ANALYZE */
109021 {sqlite3Analyze(pParse, 0, 0);}
109022 break;
109023 case 310: /* cmd ::= ANALYZE nm dbnm */
109024 {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
109025 break;
109026 case 311: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
109028 sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy259,&yymsp[0].minor.yy0);
109030 break;
109031 case 312: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
109033 sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
109035 break;
109036 case 313: /* add_column_fullname ::= fullname */
109038 pParse->db->lookaside.bEnabled = 0;
109039 sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy259);
109041 break;
109042 case 316: /* cmd ::= create_vtab */
109043 {sqlite3VtabFinishParse(pParse,0);}
109044 break;
109045 case 317: /* cmd ::= create_vtab LP vtabarglist RP */
109046 {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
109047 break;
109048 case 318: /* create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm */
109050 sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0);
109052 break;
109053 case 321: /* vtabarg ::= */
109054 {sqlite3VtabArgInit(pParse);}
109055 break;
109056 case 323: /* vtabargtoken ::= ANY */
109057 case 324: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==324);
109058 case 325: /* lp ::= LP */ yytestcase(yyruleno==325);
109059 {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
109060 break;
109061 default:
109062 /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
109063 /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
109064 /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
109065 /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
109066 /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
109067 /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
109068 /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
109069 /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
109070 /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
109071 /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
109072 /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
109073 /* (34) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==34);
109074 /* (35) columnlist ::= column */ yytestcase(yyruleno==35);
109075 /* (44) type ::= */ yytestcase(yyruleno==44);
109076 /* (51) signed ::= plus_num */ yytestcase(yyruleno==51);
109077 /* (52) signed ::= minus_num */ yytestcase(yyruleno==52);
109078 /* (53) carglist ::= carglist carg */ yytestcase(yyruleno==53);
109079 /* (54) carglist ::= */ yytestcase(yyruleno==54);
109080 /* (55) carg ::= CONSTRAINT nm ccons */ yytestcase(yyruleno==55);
109081 /* (56) carg ::= ccons */ yytestcase(yyruleno==56);
109082 /* (62) ccons ::= NULL onconf */ yytestcase(yyruleno==62);
109083 /* (90) conslist ::= conslist COMMA tcons */ yytestcase(yyruleno==90);
109084 /* (91) conslist ::= conslist tcons */ yytestcase(yyruleno==91);
109085 /* (92) conslist ::= tcons */ yytestcase(yyruleno==92);
109086 /* (93) tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==93);
109087 /* (268) plus_opt ::= PLUS */ yytestcase(yyruleno==268);
109088 /* (269) plus_opt ::= */ yytestcase(yyruleno==269);
109089 /* (279) foreach_clause ::= */ yytestcase(yyruleno==279);
109090 /* (280) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==280);
109091 /* (287) tridxby ::= */ yytestcase(yyruleno==287);
109092 /* (305) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==305);
109093 /* (306) database_kw_opt ::= */ yytestcase(yyruleno==306);
109094 /* (314) kwcolumn_opt ::= */ yytestcase(yyruleno==314);
109095 /* (315) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==315);
109096 /* (319) vtabarglist ::= vtabarg */ yytestcase(yyruleno==319);
109097 /* (320) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==320);
109098 /* (322) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==322);
109099 /* (326) anylist ::= */ yytestcase(yyruleno==326);
109100 /* (327) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==327);
109101 /* (328) anylist ::= anylist ANY */ yytestcase(yyruleno==328);
109102 break;
109104 yygoto = yyRuleInfo[yyruleno].lhs;
109105 yysize = yyRuleInfo[yyruleno].nrhs;
109106 yypParser->yyidx -= yysize;
109107 yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
109108 if( yyact < YYNSTATE ){
109109 #ifdef NDEBUG
109110 /* If we are not debugging and the reduce action popped at least
109111 ** one element off the stack, then we can push the new element back
109112 ** onto the stack here, and skip the stack overflow test in yy_shift().
109113 ** That gives a significant speed improvement. */
109114 if( yysize ){
109115 yypParser->yyidx++;
109116 yymsp -= yysize-1;
109117 yymsp->stateno = (YYACTIONTYPE)yyact;
109118 yymsp->major = (YYCODETYPE)yygoto;
109119 yymsp->minor = yygotominor;
109120 }else
109121 #endif
109123 yy_shift(yypParser,yyact,yygoto,&yygotominor);
109125 }else{
109126 assert( yyact == YYNSTATE + YYNRULE + 1 );
109127 yy_accept(yypParser);
109132 ** The following code executes when the parse fails
109134 #ifndef YYNOERRORRECOVERY
109135 static void yy_parse_failed(
109136 yyParser *yypParser /* The parser */
109138 sqlite3ParserARG_FETCH;
109139 #ifndef NDEBUG
109140 if( yyTraceFILE ){
109141 fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
109143 #endif
109144 while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
109145 /* Here code is inserted which will be executed whenever the
109146 ** parser fails */
109147 sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
109149 #endif /* YYNOERRORRECOVERY */
109152 ** The following code executes when a syntax error first occurs.
109154 static void yy_syntax_error(
109155 yyParser *yypParser, /* The parser */
109156 int yymajor, /* The major type of the error token */
109157 YYMINORTYPE yyminor /* The minor type of the error token */
109159 sqlite3ParserARG_FETCH;
109160 #define TOKEN (yyminor.yy0)
109162 UNUSED_PARAMETER(yymajor); /* Silence some compiler warnings */
109163 assert( TOKEN.z[0] ); /* The tokenizer always gives us a token */
109164 sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
109165 pParse->parseError = 1;
109166 sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
109170 ** The following is executed when the parser accepts
109172 static void yy_accept(
109173 yyParser *yypParser /* The parser */
109175 sqlite3ParserARG_FETCH;
109176 #ifndef NDEBUG
109177 if( yyTraceFILE ){
109178 fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
109180 #endif
109181 while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
109182 /* Here code is inserted which will be executed whenever the
109183 ** parser accepts */
109184 sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
109187 /* The main parser program.
109188 ** The first argument is a pointer to a structure obtained from
109189 ** "sqlite3ParserAlloc" which describes the current state of the parser.
109190 ** The second argument is the major token number. The third is
109191 ** the minor token. The fourth optional argument is whatever the
109192 ** user wants (and specified in the grammar) and is available for
109193 ** use by the action routines.
109195 ** Inputs:
109196 ** <ul>
109197 ** <li> A pointer to the parser (an opaque structure.)
109198 ** <li> The major token number.
109199 ** <li> The minor token number.
109200 ** <li> An option argument of a grammar-specified type.
109201 ** </ul>
109203 ** Outputs:
109204 ** None.
109206 SQLITE_PRIVATE void sqlite3Parser(
109207 void *yyp, /* The parser */
109208 int yymajor, /* The major token code number */
109209 sqlite3ParserTOKENTYPE yyminor /* The value for the token */
109210 sqlite3ParserARG_PDECL /* Optional %extra_argument parameter */
109212 YYMINORTYPE yyminorunion;
109213 int yyact; /* The parser action. */
109214 #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
109215 int yyendofinput; /* True if we are at the end of input */
109216 #endif
109217 #ifdef YYERRORSYMBOL
109218 int yyerrorhit = 0; /* True if yymajor has invoked an error */
109219 #endif
109220 yyParser *yypParser; /* The parser */
109222 /* (re)initialize the parser, if necessary */
109223 yypParser = (yyParser*)yyp;
109224 if( yypParser->yyidx<0 ){
109225 #if YYSTACKDEPTH<=0
109226 if( yypParser->yystksz <=0 ){
109227 /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
109228 yyminorunion = yyzerominor;
109229 yyStackOverflow(yypParser, &yyminorunion);
109230 return;
109232 #endif
109233 yypParser->yyidx = 0;
109234 yypParser->yyerrcnt = -1;
109235 yypParser->yystack[0].stateno = 0;
109236 yypParser->yystack[0].major = 0;
109238 yyminorunion.yy0 = yyminor;
109239 #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
109240 yyendofinput = (yymajor==0);
109241 #endif
109242 sqlite3ParserARG_STORE;
109244 #ifndef NDEBUG
109245 if( yyTraceFILE ){
109246 fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
109248 #endif
109251 yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
109252 if( yyact<YYNSTATE ){
109253 yy_shift(yypParser,yyact,yymajor,&yyminorunion);
109254 yypParser->yyerrcnt--;
109255 yymajor = YYNOCODE;
109256 }else if( yyact < YYNSTATE + YYNRULE ){
109257 yy_reduce(yypParser,yyact-YYNSTATE);
109258 }else{
109259 assert( yyact == YY_ERROR_ACTION );
109260 #ifdef YYERRORSYMBOL
109261 int yymx;
109262 #endif
109263 #ifndef NDEBUG
109264 if( yyTraceFILE ){
109265 fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
109267 #endif
109268 #ifdef YYERRORSYMBOL
109269 /* A syntax error has occurred.
109270 ** The response to an error depends upon whether or not the
109271 ** grammar defines an error token "ERROR".
109273 ** This is what we do if the grammar does define ERROR:
109275 ** * Call the %syntax_error function.
109277 ** * Begin popping the stack until we enter a state where
109278 ** it is legal to shift the error symbol, then shift
109279 ** the error symbol.
109281 ** * Set the error count to three.
109283 ** * Begin accepting and shifting new tokens. No new error
109284 ** processing will occur until three tokens have been
109285 ** shifted successfully.
109288 if( yypParser->yyerrcnt<0 ){
109289 yy_syntax_error(yypParser,yymajor,yyminorunion);
109291 yymx = yypParser->yystack[yypParser->yyidx].major;
109292 if( yymx==YYERRORSYMBOL || yyerrorhit ){
109293 #ifndef NDEBUG
109294 if( yyTraceFILE ){
109295 fprintf(yyTraceFILE,"%sDiscard input token %s\n",
109296 yyTracePrompt,yyTokenName[yymajor]);
109298 #endif
109299 yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
109300 yymajor = YYNOCODE;
109301 }else{
109302 while(
109303 yypParser->yyidx >= 0 &&
109304 yymx != YYERRORSYMBOL &&
109305 (yyact = yy_find_reduce_action(
109306 yypParser->yystack[yypParser->yyidx].stateno,
109307 YYERRORSYMBOL)) >= YYNSTATE
109309 yy_pop_parser_stack(yypParser);
109311 if( yypParser->yyidx < 0 || yymajor==0 ){
109312 yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
109313 yy_parse_failed(yypParser);
109314 yymajor = YYNOCODE;
109315 }else if( yymx!=YYERRORSYMBOL ){
109316 YYMINORTYPE u2;
109317 u2.YYERRSYMDT = 0;
109318 yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
109321 yypParser->yyerrcnt = 3;
109322 yyerrorhit = 1;
109323 #elif defined(YYNOERRORRECOVERY)
109324 /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
109325 ** do any kind of error recovery. Instead, simply invoke the syntax
109326 ** error routine and continue going as if nothing had happened.
109328 ** Applications can set this macro (for example inside %include) if
109329 ** they intend to abandon the parse upon the first syntax error seen.
109331 yy_syntax_error(yypParser,yymajor,yyminorunion);
109332 yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
109333 yymajor = YYNOCODE;
109335 #else /* YYERRORSYMBOL is not defined */
109336 /* This is what we do if the grammar does not define ERROR:
109338 ** * Report an error message, and throw away the input token.
109340 ** * If the input token is $, then fail the parse.
109342 ** As before, subsequent error messages are suppressed until
109343 ** three input tokens have been successfully shifted.
109345 if( yypParser->yyerrcnt<=0 ){
109346 yy_syntax_error(yypParser,yymajor,yyminorunion);
109348 yypParser->yyerrcnt = 3;
109349 yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
109350 if( yyendofinput ){
109351 yy_parse_failed(yypParser);
109353 yymajor = YYNOCODE;
109354 #endif
109356 }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
109357 return;
109360 /************** End of parse.c ***********************************************/
109361 /************** Begin file tokenize.c ****************************************/
109363 ** 2001 September 15
109365 ** The author disclaims copyright to this source code. In place of
109366 ** a legal notice, here is a blessing:
109368 ** May you do good and not evil.
109369 ** May you find forgiveness for yourself and forgive others.
109370 ** May you share freely, never taking more than you give.
109372 *************************************************************************
109373 ** An tokenizer for SQL
109375 ** This file contains C code that splits an SQL input string up into
109376 ** individual tokens and sends those tokens one-by-one over to the
109377 ** parser for analysis.
109379 /* #include <stdlib.h> */
109382 ** The charMap() macro maps alphabetic characters into their
109383 ** lower-case ASCII equivalent. On ASCII machines, this is just
109384 ** an upper-to-lower case map. On EBCDIC machines we also need
109385 ** to adjust the encoding. Only alphabetic characters and underscores
109386 ** need to be translated.
109388 #ifdef SQLITE_ASCII
109389 # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
109390 #endif
109391 #ifdef SQLITE_EBCDIC
109392 # define charMap(X) ebcdicToAscii[(unsigned char)X]
109393 const unsigned char ebcdicToAscii[] = {
109394 /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
109395 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
109396 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
109397 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
109398 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 3x */
109399 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4x */
109400 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 5x */
109401 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 0, 0, /* 6x */
109402 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 7x */
109403 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* 8x */
109404 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* 9x */
109405 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ax */
109406 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
109407 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* Cx */
109408 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* Dx */
109409 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ex */
109410 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Fx */
109412 #endif
109415 ** The sqlite3KeywordCode function looks up an identifier to determine if
109416 ** it is a keyword. If it is a keyword, the token code of that keyword is
109417 ** returned. If the input is not a keyword, TK_ID is returned.
109419 ** The implementation of this routine was generated by a program,
109420 ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
109421 ** The output of the mkkeywordhash.c program is written into a file
109422 ** named keywordhash.h and then included into this source file by
109423 ** the #include below.
109425 /************** Include keywordhash.h in the middle of tokenize.c ************/
109426 /************** Begin file keywordhash.h *************************************/
109427 /***** This file contains automatically generated code ******
109429 ** The code in this file has been automatically generated by
109431 ** sqlite/tool/mkkeywordhash.c
109433 ** The code in this file implements a function that determines whether
109434 ** or not a given identifier is really an SQL keyword. The same thing
109435 ** might be implemented more directly using a hand-written hash table.
109436 ** But by using this automatically generated code, the size of the code
109437 ** is substantially reduced. This is important for embedded applications
109438 ** on platforms with limited memory.
109440 /* Hash score: 175 */
109441 static int keywordCode(const char *z, int n){
109442 /* zText[] encodes 811 bytes of keywords in 541 bytes */
109443 /* REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT */
109444 /* ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE */
109445 /* XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY */
109446 /* UNIQUERYATTACHAVINGROUPDATEBEGINNERELEASEBETWEENOTNULLIKE */
109447 /* CASCADELETECASECOLLATECREATECURRENT_DATEDETACHIMMEDIATEJOIN */
109448 /* SERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHENWHERENAME */
109449 /* AFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS */
109450 /* CURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOBYIF */
109451 /* ISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUMVIEW */
109452 /* INITIALLY */
109453 static const char zText[540] = {
109454 'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
109455 'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
109456 'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
109457 'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
109458 'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
109459 'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
109460 'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
109461 'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
109462 'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
109463 'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
109464 'U','E','R','Y','A','T','T','A','C','H','A','V','I','N','G','R','O','U',
109465 'P','D','A','T','E','B','E','G','I','N','N','E','R','E','L','E','A','S',
109466 'E','B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C',
109467 'A','S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L',
109468 'A','T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D',
109469 'A','T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E',
109470 'J','O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A',
109471 'L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U',
109472 'E','S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W',
109473 'H','E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C',
109474 'E','A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R',
109475 'E','M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M',
109476 'M','I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U',
109477 'R','R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M',
109478 'A','R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T',
109479 'D','R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L',
109480 'O','B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S',
109481 'T','R','I','C','T','O','U','T','E','R','I','G','H','T','R','O','L','L',
109482 'B','A','C','K','R','O','W','U','N','I','O','N','U','S','I','N','G','V',
109483 'A','C','U','U','M','V','I','E','W','I','N','I','T','I','A','L','L','Y',
109485 static const unsigned char aHash[127] = {
109486 72, 101, 114, 70, 0, 45, 0, 0, 78, 0, 73, 0, 0,
109487 42, 12, 74, 15, 0, 113, 81, 50, 108, 0, 19, 0, 0,
109488 118, 0, 116, 111, 0, 22, 89, 0, 9, 0, 0, 66, 67,
109489 0, 65, 6, 0, 48, 86, 98, 0, 115, 97, 0, 0, 44,
109490 0, 99, 24, 0, 17, 0, 119, 49, 23, 0, 5, 106, 25,
109491 92, 0, 0, 121, 102, 56, 120, 53, 28, 51, 0, 87, 0,
109492 96, 26, 0, 95, 0, 0, 0, 91, 88, 93, 84, 105, 14,
109493 39, 104, 0, 77, 0, 18, 85, 107, 32, 0, 117, 76, 109,
109494 58, 46, 80, 0, 0, 90, 40, 0, 112, 0, 36, 0, 0,
109495 29, 0, 82, 59, 60, 0, 20, 57, 0, 52,
109497 static const unsigned char aNext[121] = {
109498 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0,
109499 0, 2, 0, 0, 0, 0, 0, 0, 13, 0, 0, 0, 0,
109500 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
109501 0, 0, 0, 0, 33, 0, 21, 0, 0, 0, 43, 3, 47,
109502 0, 0, 0, 0, 30, 0, 54, 0, 38, 0, 0, 0, 1,
109503 62, 0, 0, 63, 0, 41, 0, 0, 0, 0, 0, 0, 0,
109504 61, 0, 0, 0, 0, 31, 55, 16, 34, 10, 0, 0, 0,
109505 0, 0, 0, 0, 11, 68, 75, 0, 8, 0, 100, 94, 0,
109506 103, 0, 83, 0, 71, 0, 0, 110, 27, 37, 69, 79, 0,
109507 35, 64, 0, 0,
109509 static const unsigned char aLen[121] = {
109510 7, 7, 5, 4, 6, 4, 5, 3, 6, 7, 3, 6, 6,
109511 7, 7, 3, 8, 2, 6, 5, 4, 4, 3, 10, 4, 6,
109512 11, 6, 2, 7, 5, 5, 9, 6, 9, 9, 7, 10, 10,
109513 4, 6, 2, 3, 9, 4, 2, 6, 5, 6, 6, 5, 6,
109514 5, 5, 7, 7, 7, 3, 2, 4, 4, 7, 3, 6, 4,
109515 7, 6, 12, 6, 9, 4, 6, 5, 4, 7, 6, 5, 6,
109516 7, 5, 4, 5, 6, 5, 7, 3, 7, 13, 2, 2, 4,
109517 6, 6, 8, 5, 17, 12, 7, 8, 8, 2, 4, 4, 4,
109518 4, 4, 2, 2, 6, 5, 8, 5, 5, 8, 3, 5, 5,
109519 6, 4, 9, 3,
109521 static const unsigned short int aOffset[121] = {
109522 0, 2, 2, 8, 9, 14, 16, 20, 23, 25, 25, 29, 33,
109523 36, 41, 46, 48, 53, 54, 59, 62, 65, 67, 69, 78, 81,
109524 86, 91, 95, 96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
109525 159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 189, 194, 197,
109526 203, 206, 210, 217, 223, 223, 223, 226, 229, 233, 234, 238, 244,
109527 248, 255, 261, 273, 279, 288, 290, 296, 301, 303, 310, 315, 320,
109528 326, 332, 337, 341, 344, 350, 354, 361, 363, 370, 372, 374, 383,
109529 387, 393, 399, 407, 412, 412, 428, 435, 442, 443, 450, 454, 458,
109530 462, 466, 469, 471, 473, 479, 483, 491, 495, 500, 508, 511, 516,
109531 521, 527, 531, 536,
109533 static const unsigned char aCode[121] = {
109534 TK_REINDEX, TK_INDEXED, TK_INDEX, TK_DESC, TK_ESCAPE,
109535 TK_EACH, TK_CHECK, TK_KEY, TK_BEFORE, TK_FOREIGN,
109536 TK_FOR, TK_IGNORE, TK_LIKE_KW, TK_EXPLAIN, TK_INSTEAD,
109537 TK_ADD, TK_DATABASE, TK_AS, TK_SELECT, TK_TABLE,
109538 TK_JOIN_KW, TK_THEN, TK_END, TK_DEFERRABLE, TK_ELSE,
109539 TK_EXCEPT, TK_TRANSACTION,TK_ACTION, TK_ON, TK_JOIN_KW,
109540 TK_ALTER, TK_RAISE, TK_EXCLUSIVE, TK_EXISTS, TK_SAVEPOINT,
109541 TK_INTERSECT, TK_TRIGGER, TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
109542 TK_OFFSET, TK_OF, TK_SET, TK_TEMP, TK_TEMP,
109543 TK_OR, TK_UNIQUE, TK_QUERY, TK_ATTACH, TK_HAVING,
109544 TK_GROUP, TK_UPDATE, TK_BEGIN, TK_JOIN_KW, TK_RELEASE,
109545 TK_BETWEEN, TK_NOTNULL, TK_NOT, TK_NO, TK_NULL,
109546 TK_LIKE_KW, TK_CASCADE, TK_ASC, TK_DELETE, TK_CASE,
109547 TK_COLLATE, TK_CREATE, TK_CTIME_KW, TK_DETACH, TK_IMMEDIATE,
109548 TK_JOIN, TK_INSERT, TK_MATCH, TK_PLAN, TK_ANALYZE,
109549 TK_PRAGMA, TK_ABORT, TK_VALUES, TK_VIRTUAL, TK_LIMIT,
109550 TK_WHEN, TK_WHERE, TK_RENAME, TK_AFTER, TK_REPLACE,
109551 TK_AND, TK_DEFAULT, TK_AUTOINCR, TK_TO, TK_IN,
109552 TK_CAST, TK_COLUMNKW, TK_COMMIT, TK_CONFLICT, TK_JOIN_KW,
109553 TK_CTIME_KW, TK_CTIME_KW, TK_PRIMARY, TK_DEFERRED, TK_DISTINCT,
109554 TK_IS, TK_DROP, TK_FAIL, TK_FROM, TK_JOIN_KW,
109555 TK_LIKE_KW, TK_BY, TK_IF, TK_ISNULL, TK_ORDER,
109556 TK_RESTRICT, TK_JOIN_KW, TK_JOIN_KW, TK_ROLLBACK, TK_ROW,
109557 TK_UNION, TK_USING, TK_VACUUM, TK_VIEW, TK_INITIALLY,
109558 TK_ALL,
109560 int h, i;
109561 if( n<2 ) return TK_ID;
109562 h = ((charMap(z[0])*4) ^
109563 (charMap(z[n-1])*3) ^
109564 n) % 127;
109565 for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
109566 if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
109567 testcase( i==0 ); /* REINDEX */
109568 testcase( i==1 ); /* INDEXED */
109569 testcase( i==2 ); /* INDEX */
109570 testcase( i==3 ); /* DESC */
109571 testcase( i==4 ); /* ESCAPE */
109572 testcase( i==5 ); /* EACH */
109573 testcase( i==6 ); /* CHECK */
109574 testcase( i==7 ); /* KEY */
109575 testcase( i==8 ); /* BEFORE */
109576 testcase( i==9 ); /* FOREIGN */
109577 testcase( i==10 ); /* FOR */
109578 testcase( i==11 ); /* IGNORE */
109579 testcase( i==12 ); /* REGEXP */
109580 testcase( i==13 ); /* EXPLAIN */
109581 testcase( i==14 ); /* INSTEAD */
109582 testcase( i==15 ); /* ADD */
109583 testcase( i==16 ); /* DATABASE */
109584 testcase( i==17 ); /* AS */
109585 testcase( i==18 ); /* SELECT */
109586 testcase( i==19 ); /* TABLE */
109587 testcase( i==20 ); /* LEFT */
109588 testcase( i==21 ); /* THEN */
109589 testcase( i==22 ); /* END */
109590 testcase( i==23 ); /* DEFERRABLE */
109591 testcase( i==24 ); /* ELSE */
109592 testcase( i==25 ); /* EXCEPT */
109593 testcase( i==26 ); /* TRANSACTION */
109594 testcase( i==27 ); /* ACTION */
109595 testcase( i==28 ); /* ON */
109596 testcase( i==29 ); /* NATURAL */
109597 testcase( i==30 ); /* ALTER */
109598 testcase( i==31 ); /* RAISE */
109599 testcase( i==32 ); /* EXCLUSIVE */
109600 testcase( i==33 ); /* EXISTS */
109601 testcase( i==34 ); /* SAVEPOINT */
109602 testcase( i==35 ); /* INTERSECT */
109603 testcase( i==36 ); /* TRIGGER */
109604 testcase( i==37 ); /* REFERENCES */
109605 testcase( i==38 ); /* CONSTRAINT */
109606 testcase( i==39 ); /* INTO */
109607 testcase( i==40 ); /* OFFSET */
109608 testcase( i==41 ); /* OF */
109609 testcase( i==42 ); /* SET */
109610 testcase( i==43 ); /* TEMPORARY */
109611 testcase( i==44 ); /* TEMP */
109612 testcase( i==45 ); /* OR */
109613 testcase( i==46 ); /* UNIQUE */
109614 testcase( i==47 ); /* QUERY */
109615 testcase( i==48 ); /* ATTACH */
109616 testcase( i==49 ); /* HAVING */
109617 testcase( i==50 ); /* GROUP */
109618 testcase( i==51 ); /* UPDATE */
109619 testcase( i==52 ); /* BEGIN */
109620 testcase( i==53 ); /* INNER */
109621 testcase( i==54 ); /* RELEASE */
109622 testcase( i==55 ); /* BETWEEN */
109623 testcase( i==56 ); /* NOTNULL */
109624 testcase( i==57 ); /* NOT */
109625 testcase( i==58 ); /* NO */
109626 testcase( i==59 ); /* NULL */
109627 testcase( i==60 ); /* LIKE */
109628 testcase( i==61 ); /* CASCADE */
109629 testcase( i==62 ); /* ASC */
109630 testcase( i==63 ); /* DELETE */
109631 testcase( i==64 ); /* CASE */
109632 testcase( i==65 ); /* COLLATE */
109633 testcase( i==66 ); /* CREATE */
109634 testcase( i==67 ); /* CURRENT_DATE */
109635 testcase( i==68 ); /* DETACH */
109636 testcase( i==69 ); /* IMMEDIATE */
109637 testcase( i==70 ); /* JOIN */
109638 testcase( i==71 ); /* INSERT */
109639 testcase( i==72 ); /* MATCH */
109640 testcase( i==73 ); /* PLAN */
109641 testcase( i==74 ); /* ANALYZE */
109642 testcase( i==75 ); /* PRAGMA */
109643 testcase( i==76 ); /* ABORT */
109644 testcase( i==77 ); /* VALUES */
109645 testcase( i==78 ); /* VIRTUAL */
109646 testcase( i==79 ); /* LIMIT */
109647 testcase( i==80 ); /* WHEN */
109648 testcase( i==81 ); /* WHERE */
109649 testcase( i==82 ); /* RENAME */
109650 testcase( i==83 ); /* AFTER */
109651 testcase( i==84 ); /* REPLACE */
109652 testcase( i==85 ); /* AND */
109653 testcase( i==86 ); /* DEFAULT */
109654 testcase( i==87 ); /* AUTOINCREMENT */
109655 testcase( i==88 ); /* TO */
109656 testcase( i==89 ); /* IN */
109657 testcase( i==90 ); /* CAST */
109658 testcase( i==91 ); /* COLUMN */
109659 testcase( i==92 ); /* COMMIT */
109660 testcase( i==93 ); /* CONFLICT */
109661 testcase( i==94 ); /* CROSS */
109662 testcase( i==95 ); /* CURRENT_TIMESTAMP */
109663 testcase( i==96 ); /* CURRENT_TIME */
109664 testcase( i==97 ); /* PRIMARY */
109665 testcase( i==98 ); /* DEFERRED */
109666 testcase( i==99 ); /* DISTINCT */
109667 testcase( i==100 ); /* IS */
109668 testcase( i==101 ); /* DROP */
109669 testcase( i==102 ); /* FAIL */
109670 testcase( i==103 ); /* FROM */
109671 testcase( i==104 ); /* FULL */
109672 testcase( i==105 ); /* GLOB */
109673 testcase( i==106 ); /* BY */
109674 testcase( i==107 ); /* IF */
109675 testcase( i==108 ); /* ISNULL */
109676 testcase( i==109 ); /* ORDER */
109677 testcase( i==110 ); /* RESTRICT */
109678 testcase( i==111 ); /* OUTER */
109679 testcase( i==112 ); /* RIGHT */
109680 testcase( i==113 ); /* ROLLBACK */
109681 testcase( i==114 ); /* ROW */
109682 testcase( i==115 ); /* UNION */
109683 testcase( i==116 ); /* USING */
109684 testcase( i==117 ); /* VACUUM */
109685 testcase( i==118 ); /* VIEW */
109686 testcase( i==119 ); /* INITIALLY */
109687 testcase( i==120 ); /* ALL */
109688 return aCode[i];
109691 return TK_ID;
109693 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
109694 return keywordCode((char*)z, n);
109696 #define SQLITE_N_KEYWORD 121
109698 /************** End of keywordhash.h *****************************************/
109699 /************** Continuing where we left off in tokenize.c *******************/
109703 ** If X is a character that can be used in an identifier then
109704 ** IdChar(X) will be true. Otherwise it is false.
109706 ** For ASCII, any character with the high-order bit set is
109707 ** allowed in an identifier. For 7-bit characters,
109708 ** sqlite3IsIdChar[X] must be 1.
109710 ** For EBCDIC, the rules are more complex but have the same
109711 ** end result.
109713 ** Ticket #1066. the SQL standard does not allow '$' in the
109714 ** middle of identfiers. But many SQL implementations do.
109715 ** SQLite will allow '$' in identifiers for compatibility.
109716 ** But the feature is undocumented.
109718 #ifdef SQLITE_ASCII
109719 #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
109720 #endif
109721 #ifdef SQLITE_EBCDIC
109722 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
109723 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
109724 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 4x */
109725 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, /* 5x */
109726 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, /* 6x */
109727 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* 7x */
109728 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, /* 8x */
109729 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, /* 9x */
109730 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, /* Ax */
109731 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
109732 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Cx */
109733 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Dx */
109734 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Ex */
109735 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, /* Fx */
109737 #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
109738 #endif
109742 ** Return the length of the token that begins at z[0].
109743 ** Store the token type in *tokenType before returning.
109745 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
109746 int i, c;
109747 switch( *z ){
109748 case ' ': case '\t': case '\n': case '\f': case '\r': {
109749 testcase( z[0]==' ' );
109750 testcase( z[0]=='\t' );
109751 testcase( z[0]=='\n' );
109752 testcase( z[0]=='\f' );
109753 testcase( z[0]=='\r' );
109754 for(i=1; sqlite3Isspace(z[i]); i++){}
109755 *tokenType = TK_SPACE;
109756 return i;
109758 case '-': {
109759 if( z[1]=='-' ){
109760 /* IMP: R-15891-05542 -- syntax diagram for comments */
109761 for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
109762 *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
109763 return i;
109765 *tokenType = TK_MINUS;
109766 return 1;
109768 case '(': {
109769 *tokenType = TK_LP;
109770 return 1;
109772 case ')': {
109773 *tokenType = TK_RP;
109774 return 1;
109776 case ';': {
109777 *tokenType = TK_SEMI;
109778 return 1;
109780 case '+': {
109781 *tokenType = TK_PLUS;
109782 return 1;
109784 case '*': {
109785 *tokenType = TK_STAR;
109786 return 1;
109788 case '/': {
109789 if( z[1]!='*' || z[2]==0 ){
109790 *tokenType = TK_SLASH;
109791 return 1;
109793 /* IMP: R-15891-05542 -- syntax diagram for comments */
109794 for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
109795 if( c ) i++;
109796 *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
109797 return i;
109799 case '%': {
109800 *tokenType = TK_REM;
109801 return 1;
109803 case '=': {
109804 *tokenType = TK_EQ;
109805 return 1 + (z[1]=='=');
109807 case '<': {
109808 if( (c=z[1])=='=' ){
109809 *tokenType = TK_LE;
109810 return 2;
109811 }else if( c=='>' ){
109812 *tokenType = TK_NE;
109813 return 2;
109814 }else if( c=='<' ){
109815 *tokenType = TK_LSHIFT;
109816 return 2;
109817 }else{
109818 *tokenType = TK_LT;
109819 return 1;
109822 case '>': {
109823 if( (c=z[1])=='=' ){
109824 *tokenType = TK_GE;
109825 return 2;
109826 }else if( c=='>' ){
109827 *tokenType = TK_RSHIFT;
109828 return 2;
109829 }else{
109830 *tokenType = TK_GT;
109831 return 1;
109834 case '!': {
109835 if( z[1]!='=' ){
109836 *tokenType = TK_ILLEGAL;
109837 return 2;
109838 }else{
109839 *tokenType = TK_NE;
109840 return 2;
109843 case '|': {
109844 if( z[1]!='|' ){
109845 *tokenType = TK_BITOR;
109846 return 1;
109847 }else{
109848 *tokenType = TK_CONCAT;
109849 return 2;
109852 case ',': {
109853 *tokenType = TK_COMMA;
109854 return 1;
109856 case '&': {
109857 *tokenType = TK_BITAND;
109858 return 1;
109860 case '~': {
109861 *tokenType = TK_BITNOT;
109862 return 1;
109864 case '`':
109865 case '\'':
109866 case '"': {
109867 int delim = z[0];
109868 testcase( delim=='`' );
109869 testcase( delim=='\'' );
109870 testcase( delim=='"' );
109871 for(i=1; (c=z[i])!=0; i++){
109872 if( c==delim ){
109873 if( z[i+1]==delim ){
109875 }else{
109876 break;
109880 if( c=='\'' ){
109881 *tokenType = TK_STRING;
109882 return i+1;
109883 }else if( c!=0 ){
109884 *tokenType = TK_ID;
109885 return i+1;
109886 }else{
109887 *tokenType = TK_ILLEGAL;
109888 return i;
109891 case '.': {
109892 #ifndef SQLITE_OMIT_FLOATING_POINT
109893 if( !sqlite3Isdigit(z[1]) )
109894 #endif
109896 *tokenType = TK_DOT;
109897 return 1;
109899 /* If the next character is a digit, this is a floating point
109900 ** number that begins with ".". Fall thru into the next case */
109902 case '0': case '1': case '2': case '3': case '4':
109903 case '5': case '6': case '7': case '8': case '9': {
109904 testcase( z[0]=='0' ); testcase( z[0]=='1' ); testcase( z[0]=='2' );
109905 testcase( z[0]=='3' ); testcase( z[0]=='4' ); testcase( z[0]=='5' );
109906 testcase( z[0]=='6' ); testcase( z[0]=='7' ); testcase( z[0]=='8' );
109907 testcase( z[0]=='9' );
109908 *tokenType = TK_INTEGER;
109909 for(i=0; sqlite3Isdigit(z[i]); i++){}
109910 #ifndef SQLITE_OMIT_FLOATING_POINT
109911 if( z[i]=='.' ){
109913 while( sqlite3Isdigit(z[i]) ){ i++; }
109914 *tokenType = TK_FLOAT;
109916 if( (z[i]=='e' || z[i]=='E') &&
109917 ( sqlite3Isdigit(z[i+1])
109918 || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
109921 i += 2;
109922 while( sqlite3Isdigit(z[i]) ){ i++; }
109923 *tokenType = TK_FLOAT;
109925 #endif
109926 while( IdChar(z[i]) ){
109927 *tokenType = TK_ILLEGAL;
109930 return i;
109932 case '[': {
109933 for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
109934 *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
109935 return i;
109937 case '?': {
109938 *tokenType = TK_VARIABLE;
109939 for(i=1; sqlite3Isdigit(z[i]); i++){}
109940 return i;
109942 case '#': {
109943 for(i=1; sqlite3Isdigit(z[i]); i++){}
109944 if( i>1 ){
109945 /* Parameters of the form #NNN (where NNN is a number) are used
109946 ** internally by sqlite3NestedParse. */
109947 *tokenType = TK_REGISTER;
109948 return i;
109950 /* Fall through into the next case if the '#' is not followed by
109951 ** a digit. Try to match #AAAA where AAAA is a parameter name. */
109953 #ifndef SQLITE_OMIT_TCL_VARIABLE
109954 case '$':
109955 #endif
109956 case '@': /* For compatibility with MS SQL Server */
109957 case ':': {
109958 int n = 0;
109959 testcase( z[0]=='$' ); testcase( z[0]=='@' ); testcase( z[0]==':' );
109960 *tokenType = TK_VARIABLE;
109961 for(i=1; (c=z[i])!=0; i++){
109962 if( IdChar(c) ){
109964 #ifndef SQLITE_OMIT_TCL_VARIABLE
109965 }else if( c=='(' && n>0 ){
109968 }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
109969 if( c==')' ){
109971 }else{
109972 *tokenType = TK_ILLEGAL;
109974 break;
109975 }else if( c==':' && z[i+1]==':' ){
109977 #endif
109978 }else{
109979 break;
109982 if( n==0 ) *tokenType = TK_ILLEGAL;
109983 return i;
109985 #ifndef SQLITE_OMIT_BLOB_LITERAL
109986 case 'x': case 'X': {
109987 testcase( z[0]=='x' ); testcase( z[0]=='X' );
109988 if( z[1]=='\'' ){
109989 *tokenType = TK_BLOB;
109990 for(i=2; sqlite3Isxdigit(z[i]); i++){}
109991 if( z[i]!='\'' || i%2 ){
109992 *tokenType = TK_ILLEGAL;
109993 while( z[i] && z[i]!='\'' ){ i++; }
109995 if( z[i] ) i++;
109996 return i;
109998 /* Otherwise fall through to the next case */
110000 #endif
110001 default: {
110002 if( !IdChar(*z) ){
110003 break;
110005 for(i=1; IdChar(z[i]); i++){}
110006 *tokenType = keywordCode((char*)z, i);
110007 return i;
110010 *tokenType = TK_ILLEGAL;
110011 return 1;
110015 ** Run the parser on the given SQL string. The parser structure is
110016 ** passed in. An SQLITE_ status code is returned. If an error occurs
110017 ** then an and attempt is made to write an error message into
110018 ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
110019 ** error message.
110021 SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
110022 int nErr = 0; /* Number of errors encountered */
110023 int i; /* Loop counter */
110024 void *pEngine; /* The LEMON-generated LALR(1) parser */
110025 int tokenType; /* type of the next token */
110026 int lastTokenParsed = -1; /* type of the previous token */
110027 u8 enableLookaside; /* Saved value of db->lookaside.bEnabled */
110028 sqlite3 *db = pParse->db; /* The database connection */
110029 int mxSqlLen; /* Max length of an SQL string */
110032 mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
110033 if( db->activeVdbeCnt==0 ){
110034 db->u1.isInterrupted = 0;
110036 pParse->rc = SQLITE_OK;
110037 pParse->zTail = zSql;
110038 i = 0;
110039 assert( pzErrMsg!=0 );
110040 pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc);
110041 if( pEngine==0 ){
110042 db->mallocFailed = 1;
110043 return SQLITE_NOMEM;
110045 assert( pParse->pNewTable==0 );
110046 assert( pParse->pNewTrigger==0 );
110047 assert( pParse->nVar==0 );
110048 assert( pParse->nzVar==0 );
110049 assert( pParse->azVar==0 );
110050 enableLookaside = db->lookaside.bEnabled;
110051 if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
110052 while( !db->mallocFailed && zSql[i]!=0 ){
110053 assert( i>=0 );
110054 pParse->sLastToken.z = &zSql[i];
110055 pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
110056 i += pParse->sLastToken.n;
110057 if( i>mxSqlLen ){
110058 pParse->rc = SQLITE_TOOBIG;
110059 break;
110061 switch( tokenType ){
110062 case TK_SPACE: {
110063 if( db->u1.isInterrupted ){
110064 sqlite3ErrorMsg(pParse, "interrupt");
110065 pParse->rc = SQLITE_INTERRUPT;
110066 goto abort_parse;
110068 break;
110070 case TK_ILLEGAL: {
110071 sqlite3DbFree(db, *pzErrMsg);
110072 *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
110073 &pParse->sLastToken);
110074 nErr++;
110075 goto abort_parse;
110077 case TK_SEMI: {
110078 pParse->zTail = &zSql[i];
110079 /* Fall thru into the default case */
110081 default: {
110082 sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
110083 lastTokenParsed = tokenType;
110084 if( pParse->rc!=SQLITE_OK ){
110085 goto abort_parse;
110087 break;
110091 abort_parse:
110092 if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
110093 if( lastTokenParsed!=TK_SEMI ){
110094 sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
110095 pParse->zTail = &zSql[i];
110097 sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
110099 #ifdef YYTRACKMAXSTACKDEPTH
110100 sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
110101 sqlite3ParserStackPeak(pEngine)
110103 #endif /* YYDEBUG */
110104 sqlite3ParserFree(pEngine, sqlite3_free);
110105 db->lookaside.bEnabled = enableLookaside;
110106 if( db->mallocFailed ){
110107 pParse->rc = SQLITE_NOMEM;
110109 if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
110110 sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
110112 assert( pzErrMsg!=0 );
110113 if( pParse->zErrMsg ){
110114 *pzErrMsg = pParse->zErrMsg;
110115 sqlite3_log(pParse->rc, "%s", *pzErrMsg);
110116 pParse->zErrMsg = 0;
110117 nErr++;
110119 if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
110120 sqlite3VdbeDelete(pParse->pVdbe);
110121 pParse->pVdbe = 0;
110123 #ifndef SQLITE_OMIT_SHARED_CACHE
110124 if( pParse->nested==0 ){
110125 sqlite3DbFree(db, pParse->aTableLock);
110126 pParse->aTableLock = 0;
110127 pParse->nTableLock = 0;
110129 #endif
110130 #ifndef SQLITE_OMIT_VIRTUALTABLE
110131 sqlite3_free(pParse->apVtabLock);
110132 #endif
110134 if( !IN_DECLARE_VTAB ){
110135 /* If the pParse->declareVtab flag is set, do not delete any table
110136 ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
110137 ** will take responsibility for freeing the Table structure.
110139 sqlite3DeleteTable(db, pParse->pNewTable);
110142 sqlite3DeleteTrigger(db, pParse->pNewTrigger);
110143 for(i=pParse->nzVar-1; i>=0; i--) sqlite3DbFree(db, pParse->azVar[i]);
110144 sqlite3DbFree(db, pParse->azVar);
110145 sqlite3DbFree(db, pParse->aAlias);
110146 while( pParse->pAinc ){
110147 AutoincInfo *p = pParse->pAinc;
110148 pParse->pAinc = p->pNext;
110149 sqlite3DbFree(db, p);
110151 while( pParse->pZombieTab ){
110152 Table *p = pParse->pZombieTab;
110153 pParse->pZombieTab = p->pNextZombie;
110154 sqlite3DeleteTable(db, p);
110156 if( nErr>0 && pParse->rc==SQLITE_OK ){
110157 pParse->rc = SQLITE_ERROR;
110159 return nErr;
110162 /************** End of tokenize.c ********************************************/
110163 /************** Begin file complete.c ****************************************/
110165 ** 2001 September 15
110167 ** The author disclaims copyright to this source code. In place of
110168 ** a legal notice, here is a blessing:
110170 ** May you do good and not evil.
110171 ** May you find forgiveness for yourself and forgive others.
110172 ** May you share freely, never taking more than you give.
110174 *************************************************************************
110175 ** An tokenizer for SQL
110177 ** This file contains C code that implements the sqlite3_complete() API.
110178 ** This code used to be part of the tokenizer.c source file. But by
110179 ** separating it out, the code will be automatically omitted from
110180 ** static links that do not use it.
110182 #ifndef SQLITE_OMIT_COMPLETE
110185 ** This is defined in tokenize.c. We just have to import the definition.
110187 #ifndef SQLITE_AMALGAMATION
110188 #ifdef SQLITE_ASCII
110189 #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
110190 #endif
110191 #ifdef SQLITE_EBCDIC
110192 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
110193 #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
110194 #endif
110195 #endif /* SQLITE_AMALGAMATION */
110199 ** Token types used by the sqlite3_complete() routine. See the header
110200 ** comments on that procedure for additional information.
110202 #define tkSEMI 0
110203 #define tkWS 1
110204 #define tkOTHER 2
110205 #ifndef SQLITE_OMIT_TRIGGER
110206 #define tkEXPLAIN 3
110207 #define tkCREATE 4
110208 #define tkTEMP 5
110209 #define tkTRIGGER 6
110210 #define tkEND 7
110211 #endif
110214 ** Return TRUE if the given SQL string ends in a semicolon.
110216 ** Special handling is require for CREATE TRIGGER statements.
110217 ** Whenever the CREATE TRIGGER keywords are seen, the statement
110218 ** must end with ";END;".
110220 ** This implementation uses a state machine with 8 states:
110222 ** (0) INVALID We have not yet seen a non-whitespace character.
110224 ** (1) START At the beginning or end of an SQL statement. This routine
110225 ** returns 1 if it ends in the START state and 0 if it ends
110226 ** in any other state.
110228 ** (2) NORMAL We are in the middle of statement which ends with a single
110229 ** semicolon.
110231 ** (3) EXPLAIN The keyword EXPLAIN has been seen at the beginning of
110232 ** a statement.
110234 ** (4) CREATE The keyword CREATE has been seen at the beginning of a
110235 ** statement, possibly preceeded by EXPLAIN and/or followed by
110236 ** TEMP or TEMPORARY
110238 ** (5) TRIGGER We are in the middle of a trigger definition that must be
110239 ** ended by a semicolon, the keyword END, and another semicolon.
110241 ** (6) SEMI We've seen the first semicolon in the ";END;" that occurs at
110242 ** the end of a trigger definition.
110244 ** (7) END We've seen the ";END" of the ";END;" that occurs at the end
110245 ** of a trigger difinition.
110247 ** Transitions between states above are determined by tokens extracted
110248 ** from the input. The following tokens are significant:
110250 ** (0) tkSEMI A semicolon.
110251 ** (1) tkWS Whitespace.
110252 ** (2) tkOTHER Any other SQL token.
110253 ** (3) tkEXPLAIN The "explain" keyword.
110254 ** (4) tkCREATE The "create" keyword.
110255 ** (5) tkTEMP The "temp" or "temporary" keyword.
110256 ** (6) tkTRIGGER The "trigger" keyword.
110257 ** (7) tkEND The "end" keyword.
110259 ** Whitespace never causes a state transition and is always ignored.
110260 ** This means that a SQL string of all whitespace is invalid.
110262 ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
110263 ** to recognize the end of a trigger can be omitted. All we have to do
110264 ** is look for a semicolon that is not part of an string or comment.
110266 SQLITE_API int sqlite3_complete(const char *zSql){
110267 u8 state = 0; /* Current state, using numbers defined in header comment */
110268 u8 token; /* Value of the next token */
110270 #ifndef SQLITE_OMIT_TRIGGER
110271 /* A complex statement machine used to detect the end of a CREATE TRIGGER
110272 ** statement. This is the normal case.
110274 static const u8 trans[8][8] = {
110275 /* Token: */
110276 /* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */
110277 /* 0 INVALID: */ { 1, 0, 2, 3, 4, 2, 2, 2, },
110278 /* 1 START: */ { 1, 1, 2, 3, 4, 2, 2, 2, },
110279 /* 2 NORMAL: */ { 1, 2, 2, 2, 2, 2, 2, 2, },
110280 /* 3 EXPLAIN: */ { 1, 3, 3, 2, 4, 2, 2, 2, },
110281 /* 4 CREATE: */ { 1, 4, 2, 2, 2, 4, 5, 2, },
110282 /* 5 TRIGGER: */ { 6, 5, 5, 5, 5, 5, 5, 5, },
110283 /* 6 SEMI: */ { 6, 6, 5, 5, 5, 5, 5, 7, },
110284 /* 7 END: */ { 1, 7, 5, 5, 5, 5, 5, 5, },
110286 #else
110287 /* If triggers are not supported by this compile then the statement machine
110288 ** used to detect the end of a statement is much simplier
110290 static const u8 trans[3][3] = {
110291 /* Token: */
110292 /* State: ** SEMI WS OTHER */
110293 /* 0 INVALID: */ { 1, 0, 2, },
110294 /* 1 START: */ { 1, 1, 2, },
110295 /* 2 NORMAL: */ { 1, 2, 2, },
110297 #endif /* SQLITE_OMIT_TRIGGER */
110299 while( *zSql ){
110300 switch( *zSql ){
110301 case ';': { /* A semicolon */
110302 token = tkSEMI;
110303 break;
110305 case ' ':
110306 case '\r':
110307 case '\t':
110308 case '\n':
110309 case '\f': { /* White space is ignored */
110310 token = tkWS;
110311 break;
110313 case '/': { /* C-style comments */
110314 if( zSql[1]!='*' ){
110315 token = tkOTHER;
110316 break;
110318 zSql += 2;
110319 while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
110320 if( zSql[0]==0 ) return 0;
110321 zSql++;
110322 token = tkWS;
110323 break;
110325 case '-': { /* SQL-style comments from "--" to end of line */
110326 if( zSql[1]!='-' ){
110327 token = tkOTHER;
110328 break;
110330 while( *zSql && *zSql!='\n' ){ zSql++; }
110331 if( *zSql==0 ) return state==1;
110332 token = tkWS;
110333 break;
110335 case '[': { /* Microsoft-style identifiers in [...] */
110336 zSql++;
110337 while( *zSql && *zSql!=']' ){ zSql++; }
110338 if( *zSql==0 ) return 0;
110339 token = tkOTHER;
110340 break;
110342 case '`': /* Grave-accent quoted symbols used by MySQL */
110343 case '"': /* single- and double-quoted strings */
110344 case '\'': {
110345 int c = *zSql;
110346 zSql++;
110347 while( *zSql && *zSql!=c ){ zSql++; }
110348 if( *zSql==0 ) return 0;
110349 token = tkOTHER;
110350 break;
110352 default: {
110353 #ifdef SQLITE_EBCDIC
110354 unsigned char c;
110355 #endif
110356 if( IdChar((u8)*zSql) ){
110357 /* Keywords and unquoted identifiers */
110358 int nId;
110359 for(nId=1; IdChar(zSql[nId]); nId++){}
110360 #ifdef SQLITE_OMIT_TRIGGER
110361 token = tkOTHER;
110362 #else
110363 switch( *zSql ){
110364 case 'c': case 'C': {
110365 if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
110366 token = tkCREATE;
110367 }else{
110368 token = tkOTHER;
110370 break;
110372 case 't': case 'T': {
110373 if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
110374 token = tkTRIGGER;
110375 }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
110376 token = tkTEMP;
110377 }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
110378 token = tkTEMP;
110379 }else{
110380 token = tkOTHER;
110382 break;
110384 case 'e': case 'E': {
110385 if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
110386 token = tkEND;
110387 }else
110388 #ifndef SQLITE_OMIT_EXPLAIN
110389 if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
110390 token = tkEXPLAIN;
110391 }else
110392 #endif
110394 token = tkOTHER;
110396 break;
110398 default: {
110399 token = tkOTHER;
110400 break;
110403 #endif /* SQLITE_OMIT_TRIGGER */
110404 zSql += nId-1;
110405 }else{
110406 /* Operators and special symbols */
110407 token = tkOTHER;
110409 break;
110412 state = trans[state][token];
110413 zSql++;
110415 return state==1;
110418 #ifndef SQLITE_OMIT_UTF16
110420 ** This routine is the same as the sqlite3_complete() routine described
110421 ** above, except that the parameter is required to be UTF-16 encoded, not
110422 ** UTF-8.
110424 SQLITE_API int sqlite3_complete16(const void *zSql){
110425 sqlite3_value *pVal;
110426 char const *zSql8;
110427 int rc = SQLITE_NOMEM;
110429 #ifndef SQLITE_OMIT_AUTOINIT
110430 rc = sqlite3_initialize();
110431 if( rc ) return rc;
110432 #endif
110433 pVal = sqlite3ValueNew(0);
110434 sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
110435 zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
110436 if( zSql8 ){
110437 rc = sqlite3_complete(zSql8);
110438 }else{
110439 rc = SQLITE_NOMEM;
110441 sqlite3ValueFree(pVal);
110442 return sqlite3ApiExit(0, rc);
110444 #endif /* SQLITE_OMIT_UTF16 */
110445 #endif /* SQLITE_OMIT_COMPLETE */
110447 /************** End of complete.c ********************************************/
110448 /************** Begin file main.c ********************************************/
110450 ** 2001 September 15
110452 ** The author disclaims copyright to this source code. In place of
110453 ** a legal notice, here is a blessing:
110455 ** May you do good and not evil.
110456 ** May you find forgiveness for yourself and forgive others.
110457 ** May you share freely, never taking more than you give.
110459 *************************************************************************
110460 ** Main file for the SQLite library. The routines in this file
110461 ** implement the programmer interface to the library. Routines in
110462 ** other files are for internal use by SQLite and should not be
110463 ** accessed by users of the library.
110466 #ifdef SQLITE_ENABLE_FTS3
110467 /************** Include fts3.h in the middle of main.c ***********************/
110468 /************** Begin file fts3.h ********************************************/
110470 ** 2006 Oct 10
110472 ** The author disclaims copyright to this source code. In place of
110473 ** a legal notice, here is a blessing:
110475 ** May you do good and not evil.
110476 ** May you find forgiveness for yourself and forgive others.
110477 ** May you share freely, never taking more than you give.
110479 ******************************************************************************
110481 ** This header file is used by programs that want to link against the
110482 ** FTS3 library. All it does is declare the sqlite3Fts3Init() interface.
110485 #if 0
110486 extern "C" {
110487 #endif /* __cplusplus */
110489 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
110491 #if 0
110492 } /* extern "C" */
110493 #endif /* __cplusplus */
110495 /************** End of fts3.h ************************************************/
110496 /************** Continuing where we left off in main.c ***********************/
110497 #endif
110498 #ifdef SQLITE_ENABLE_RTREE
110499 /************** Include rtree.h in the middle of main.c **********************/
110500 /************** Begin file rtree.h *******************************************/
110502 ** 2008 May 26
110504 ** The author disclaims copyright to this source code. In place of
110505 ** a legal notice, here is a blessing:
110507 ** May you do good and not evil.
110508 ** May you find forgiveness for yourself and forgive others.
110509 ** May you share freely, never taking more than you give.
110511 ******************************************************************************
110513 ** This header file is used by programs that want to link against the
110514 ** RTREE library. All it does is declare the sqlite3RtreeInit() interface.
110517 #if 0
110518 extern "C" {
110519 #endif /* __cplusplus */
110521 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
110523 #if 0
110524 } /* extern "C" */
110525 #endif /* __cplusplus */
110527 /************** End of rtree.h ***********************************************/
110528 /************** Continuing where we left off in main.c ***********************/
110529 #endif
110530 #ifdef SQLITE_ENABLE_ICU
110531 /************** Include sqliteicu.h in the middle of main.c ******************/
110532 /************** Begin file sqliteicu.h ***************************************/
110534 ** 2008 May 26
110536 ** The author disclaims copyright to this source code. In place of
110537 ** a legal notice, here is a blessing:
110539 ** May you do good and not evil.
110540 ** May you find forgiveness for yourself and forgive others.
110541 ** May you share freely, never taking more than you give.
110543 ******************************************************************************
110545 ** This header file is used by programs that want to link against the
110546 ** ICU extension. All it does is declare the sqlite3IcuInit() interface.
110549 #if 0
110550 extern "C" {
110551 #endif /* __cplusplus */
110553 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
110555 #if 0
110556 } /* extern "C" */
110557 #endif /* __cplusplus */
110560 /************** End of sqliteicu.h *******************************************/
110561 /************** Continuing where we left off in main.c ***********************/
110562 #endif
110564 #ifndef SQLITE_AMALGAMATION
110565 /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
110566 ** contains the text of SQLITE_VERSION macro.
110568 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
110569 #endif
110571 /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
110572 ** a pointer to the to the sqlite3_version[] string constant.
110574 SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
110576 /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
110577 ** pointer to a string constant whose value is the same as the
110578 ** SQLITE_SOURCE_ID C preprocessor macro.
110580 SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
110582 /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
110583 ** returns an integer equal to SQLITE_VERSION_NUMBER.
110585 SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
110587 /* IMPLEMENTATION-OF: R-54823-41343 The sqlite3_threadsafe() function returns
110588 ** zero if and only if SQLite was compiled mutexing code omitted due to
110589 ** the SQLITE_THREADSAFE compile-time option being set to 0.
110591 SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
110593 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
110595 ** If the following function pointer is not NULL and if
110596 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
110597 ** I/O active are written using this function. These messages
110598 ** are intended for debugging activity only.
110600 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
110601 #endif
110604 ** If the following global variable points to a string which is the
110605 ** name of a directory, then that directory will be used to store
110606 ** temporary files.
110608 ** See also the "PRAGMA temp_store_directory" SQL command.
110610 SQLITE_API char *sqlite3_temp_directory = 0;
110613 ** Initialize SQLite.
110615 ** This routine must be called to initialize the memory allocation,
110616 ** VFS, and mutex subsystems prior to doing any serious work with
110617 ** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT
110618 ** this routine will be called automatically by key routines such as
110619 ** sqlite3_open().
110621 ** This routine is a no-op except on its very first call for the process,
110622 ** or for the first call after a call to sqlite3_shutdown.
110624 ** The first thread to call this routine runs the initialization to
110625 ** completion. If subsequent threads call this routine before the first
110626 ** thread has finished the initialization process, then the subsequent
110627 ** threads must block until the first thread finishes with the initialization.
110629 ** The first thread might call this routine recursively. Recursive
110630 ** calls to this routine should not block, of course. Otherwise the
110631 ** initialization process would never complete.
110633 ** Let X be the first thread to enter this routine. Let Y be some other
110634 ** thread. Then while the initial invocation of this routine by X is
110635 ** incomplete, it is required that:
110637 ** * Calls to this routine from Y must block until the outer-most
110638 ** call by X completes.
110640 ** * Recursive calls to this routine from thread X return immediately
110641 ** without blocking.
110643 SQLITE_API int sqlite3_initialize(void){
110644 MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
110645 int rc; /* Result code */
110647 #ifdef SQLITE_OMIT_WSD
110648 rc = sqlite3_wsd_init(4096, 24);
110649 if( rc!=SQLITE_OK ){
110650 return rc;
110652 #endif
110654 /* If SQLite is already completely initialized, then this call
110655 ** to sqlite3_initialize() should be a no-op. But the initialization
110656 ** must be complete. So isInit must not be set until the very end
110657 ** of this routine.
110659 if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
110661 /* Make sure the mutex subsystem is initialized. If unable to
110662 ** initialize the mutex subsystem, return early with the error.
110663 ** If the system is so sick that we are unable to allocate a mutex,
110664 ** there is not much SQLite is going to be able to do.
110666 ** The mutex subsystem must take care of serializing its own
110667 ** initialization.
110669 rc = sqlite3MutexInit();
110670 if( rc ) return rc;
110672 /* Initialize the malloc() system and the recursive pInitMutex mutex.
110673 ** This operation is protected by the STATIC_MASTER mutex. Note that
110674 ** MutexAlloc() is called for a static mutex prior to initializing the
110675 ** malloc subsystem - this implies that the allocation of a static
110676 ** mutex must not require support from the malloc subsystem.
110678 MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
110679 sqlite3_mutex_enter(pMaster);
110680 sqlite3GlobalConfig.isMutexInit = 1;
110681 if( !sqlite3GlobalConfig.isMallocInit ){
110682 rc = sqlite3MallocInit();
110684 if( rc==SQLITE_OK ){
110685 sqlite3GlobalConfig.isMallocInit = 1;
110686 if( !sqlite3GlobalConfig.pInitMutex ){
110687 sqlite3GlobalConfig.pInitMutex =
110688 sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
110689 if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
110690 rc = SQLITE_NOMEM;
110694 if( rc==SQLITE_OK ){
110695 sqlite3GlobalConfig.nRefInitMutex++;
110697 sqlite3_mutex_leave(pMaster);
110699 /* If rc is not SQLITE_OK at this point, then either the malloc
110700 ** subsystem could not be initialized or the system failed to allocate
110701 ** the pInitMutex mutex. Return an error in either case. */
110702 if( rc!=SQLITE_OK ){
110703 return rc;
110706 /* Do the rest of the initialization under the recursive mutex so
110707 ** that we will be able to handle recursive calls into
110708 ** sqlite3_initialize(). The recursive calls normally come through
110709 ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
110710 ** recursive calls might also be possible.
110712 ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
110713 ** to the xInit method, so the xInit method need not be threadsafe.
110715 ** The following mutex is what serializes access to the appdef pcache xInit
110716 ** methods. The sqlite3_pcache_methods.xInit() all is embedded in the
110717 ** call to sqlite3PcacheInitialize().
110719 sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
110720 if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
110721 FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
110722 sqlite3GlobalConfig.inProgress = 1;
110723 memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
110724 sqlite3RegisterGlobalFunctions();
110725 if( sqlite3GlobalConfig.isPCacheInit==0 ){
110726 rc = sqlite3PcacheInitialize();
110728 if( rc==SQLITE_OK ){
110729 sqlite3GlobalConfig.isPCacheInit = 1;
110730 rc = sqlite3OsInit();
110732 if( rc==SQLITE_OK ){
110733 sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
110734 sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
110735 sqlite3GlobalConfig.isInit = 1;
110737 sqlite3GlobalConfig.inProgress = 0;
110739 sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
110741 /* Go back under the static mutex and clean up the recursive
110742 ** mutex to prevent a resource leak.
110744 sqlite3_mutex_enter(pMaster);
110745 sqlite3GlobalConfig.nRefInitMutex--;
110746 if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
110747 assert( sqlite3GlobalConfig.nRefInitMutex==0 );
110748 sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
110749 sqlite3GlobalConfig.pInitMutex = 0;
110751 sqlite3_mutex_leave(pMaster);
110753 /* The following is just a sanity check to make sure SQLite has
110754 ** been compiled correctly. It is important to run this code, but
110755 ** we don't want to run it too often and soak up CPU cycles for no
110756 ** reason. So we run it once during initialization.
110758 #ifndef NDEBUG
110759 #ifndef SQLITE_OMIT_FLOATING_POINT
110760 /* This section of code's only "output" is via assert() statements. */
110761 if ( rc==SQLITE_OK ){
110762 u64 x = (((u64)1)<<63)-1;
110763 double y;
110764 assert(sizeof(x)==8);
110765 assert(sizeof(x)==sizeof(y));
110766 memcpy(&y, &x, 8);
110767 assert( sqlite3IsNaN(y) );
110769 #endif
110770 #endif
110772 /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
110773 ** compile-time option.
110775 #ifdef SQLITE_EXTRA_INIT
110776 if( rc==SQLITE_OK && sqlite3GlobalConfig.isInit ){
110777 int SQLITE_EXTRA_INIT(void);
110778 rc = SQLITE_EXTRA_INIT();
110780 #endif
110782 return rc;
110786 ** Undo the effects of sqlite3_initialize(). Must not be called while
110787 ** there are outstanding database connections or memory allocations or
110788 ** while any part of SQLite is otherwise in use in any thread. This
110789 ** routine is not threadsafe. But it is safe to invoke this routine
110790 ** on when SQLite is already shut down. If SQLite is already shut down
110791 ** when this routine is invoked, then this routine is a harmless no-op.
110793 SQLITE_API int sqlite3_shutdown(void){
110794 if( sqlite3GlobalConfig.isInit ){
110795 sqlite3_os_end();
110796 sqlite3_reset_auto_extension();
110797 sqlite3GlobalConfig.isInit = 0;
110799 if( sqlite3GlobalConfig.isPCacheInit ){
110800 sqlite3PcacheShutdown();
110801 sqlite3GlobalConfig.isPCacheInit = 0;
110803 if( sqlite3GlobalConfig.isMallocInit ){
110804 sqlite3MallocEnd();
110805 sqlite3GlobalConfig.isMallocInit = 0;
110807 if( sqlite3GlobalConfig.isMutexInit ){
110808 sqlite3MutexEnd();
110809 sqlite3GlobalConfig.isMutexInit = 0;
110812 return SQLITE_OK;
110816 ** This API allows applications to modify the global configuration of
110817 ** the SQLite library at run-time.
110819 ** This routine should only be called when there are no outstanding
110820 ** database connections or memory allocations. This routine is not
110821 ** threadsafe. Failure to heed these warnings can lead to unpredictable
110822 ** behavior.
110824 SQLITE_API int sqlite3_config(int op, ...){
110825 va_list ap;
110826 int rc = SQLITE_OK;
110828 /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
110829 ** the SQLite library is in use. */
110830 if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
110832 va_start(ap, op);
110833 switch( op ){
110835 /* Mutex configuration options are only available in a threadsafe
110836 ** compile.
110838 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
110839 case SQLITE_CONFIG_SINGLETHREAD: {
110840 /* Disable all mutexing */
110841 sqlite3GlobalConfig.bCoreMutex = 0;
110842 sqlite3GlobalConfig.bFullMutex = 0;
110843 break;
110845 case SQLITE_CONFIG_MULTITHREAD: {
110846 /* Disable mutexing of database connections */
110847 /* Enable mutexing of core data structures */
110848 sqlite3GlobalConfig.bCoreMutex = 1;
110849 sqlite3GlobalConfig.bFullMutex = 0;
110850 break;
110852 case SQLITE_CONFIG_SERIALIZED: {
110853 /* Enable all mutexing */
110854 sqlite3GlobalConfig.bCoreMutex = 1;
110855 sqlite3GlobalConfig.bFullMutex = 1;
110856 break;
110858 case SQLITE_CONFIG_MUTEX: {
110859 /* Specify an alternative mutex implementation */
110860 sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
110861 break;
110863 case SQLITE_CONFIG_GETMUTEX: {
110864 /* Retrieve the current mutex implementation */
110865 *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
110866 break;
110868 #endif
110871 case SQLITE_CONFIG_MALLOC: {
110872 /* Specify an alternative malloc implementation */
110873 sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
110874 break;
110876 case SQLITE_CONFIG_GETMALLOC: {
110877 /* Retrieve the current malloc() implementation */
110878 if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
110879 *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
110880 break;
110882 case SQLITE_CONFIG_MEMSTATUS: {
110883 /* Enable or disable the malloc status collection */
110884 sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
110885 break;
110887 case SQLITE_CONFIG_SCRATCH: {
110888 /* Designate a buffer for scratch memory space */
110889 sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
110890 sqlite3GlobalConfig.szScratch = va_arg(ap, int);
110891 sqlite3GlobalConfig.nScratch = va_arg(ap, int);
110892 break;
110894 case SQLITE_CONFIG_PAGECACHE: {
110895 /* Designate a buffer for page cache memory space */
110896 sqlite3GlobalConfig.pPage = va_arg(ap, void*);
110897 sqlite3GlobalConfig.szPage = va_arg(ap, int);
110898 sqlite3GlobalConfig.nPage = va_arg(ap, int);
110899 break;
110902 case SQLITE_CONFIG_PCACHE: {
110903 /* Specify an alternative page cache implementation */
110904 sqlite3GlobalConfig.pcache = *va_arg(ap, sqlite3_pcache_methods*);
110905 break;
110908 case SQLITE_CONFIG_GETPCACHE: {
110909 if( sqlite3GlobalConfig.pcache.xInit==0 ){
110910 sqlite3PCacheSetDefault();
110912 *va_arg(ap, sqlite3_pcache_methods*) = sqlite3GlobalConfig.pcache;
110913 break;
110916 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
110917 case SQLITE_CONFIG_HEAP: {
110918 /* Designate a buffer for heap memory space */
110919 sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
110920 sqlite3GlobalConfig.nHeap = va_arg(ap, int);
110921 sqlite3GlobalConfig.mnReq = va_arg(ap, int);
110923 if( sqlite3GlobalConfig.mnReq<1 ){
110924 sqlite3GlobalConfig.mnReq = 1;
110925 }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
110926 /* cap min request size at 2^12 */
110927 sqlite3GlobalConfig.mnReq = (1<<12);
110930 if( sqlite3GlobalConfig.pHeap==0 ){
110931 /* If the heap pointer is NULL, then restore the malloc implementation
110932 ** back to NULL pointers too. This will cause the malloc to go
110933 ** back to its default implementation when sqlite3_initialize() is
110934 ** run.
110936 memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
110937 }else{
110938 /* The heap pointer is not NULL, then install one of the
110939 ** mem5.c/mem3.c methods. If neither ENABLE_MEMSYS3 nor
110940 ** ENABLE_MEMSYS5 is defined, return an error.
110942 #ifdef SQLITE_ENABLE_MEMSYS3
110943 sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
110944 #endif
110945 #ifdef SQLITE_ENABLE_MEMSYS5
110946 sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
110947 #endif
110949 break;
110951 #endif
110953 case SQLITE_CONFIG_LOOKASIDE: {
110954 sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
110955 sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
110956 break;
110959 /* Record a pointer to the logger funcction and its first argument.
110960 ** The default is NULL. Logging is disabled if the function pointer is
110961 ** NULL.
110963 case SQLITE_CONFIG_LOG: {
110964 /* MSVC is picky about pulling func ptrs from va lists.
110965 ** http://support.microsoft.com/kb/47961
110966 ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
110968 typedef void(*LOGFUNC_t)(void*,int,const char*);
110969 sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
110970 sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
110971 break;
110974 case SQLITE_CONFIG_URI: {
110975 sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
110976 break;
110979 default: {
110980 rc = SQLITE_ERROR;
110981 break;
110984 va_end(ap);
110985 return rc;
110989 ** Set up the lookaside buffers for a database connection.
110990 ** Return SQLITE_OK on success.
110991 ** If lookaside is already active, return SQLITE_BUSY.
110993 ** The sz parameter is the number of bytes in each lookaside slot.
110994 ** The cnt parameter is the number of slots. If pStart is NULL the
110995 ** space for the lookaside memory is obtained from sqlite3_malloc().
110996 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
110997 ** the lookaside memory.
110999 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
111000 void *pStart;
111001 if( db->lookaside.nOut ){
111002 return SQLITE_BUSY;
111004 /* Free any existing lookaside buffer for this handle before
111005 ** allocating a new one so we don't have to have space for
111006 ** both at the same time.
111008 if( db->lookaside.bMalloced ){
111009 sqlite3_free(db->lookaside.pStart);
111011 /* The size of a lookaside slot needs to be larger than a pointer
111012 ** to be useful.
111014 if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
111015 if( cnt<0 ) cnt = 0;
111016 if( sz==0 || cnt==0 ){
111017 sz = 0;
111018 pStart = 0;
111019 }else if( pBuf==0 ){
111020 sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
111021 sqlite3BeginBenignMalloc();
111022 pStart = sqlite3Malloc( sz*cnt ); /* IMP: R-61949-35727 */
111023 sqlite3EndBenignMalloc();
111024 }else{
111025 sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
111026 pStart = pBuf;
111028 db->lookaside.pStart = pStart;
111029 db->lookaside.pFree = 0;
111030 db->lookaside.sz = (u16)sz;
111031 if( pStart ){
111032 int i;
111033 LookasideSlot *p;
111034 assert( sz > (int)sizeof(LookasideSlot*) );
111035 p = (LookasideSlot*)pStart;
111036 for(i=cnt-1; i>=0; i--){
111037 p->pNext = db->lookaside.pFree;
111038 db->lookaside.pFree = p;
111039 p = (LookasideSlot*)&((u8*)p)[sz];
111041 db->lookaside.pEnd = p;
111042 db->lookaside.bEnabled = 1;
111043 db->lookaside.bMalloced = pBuf==0 ?1:0;
111044 }else{
111045 db->lookaside.pEnd = 0;
111046 db->lookaside.bEnabled = 0;
111047 db->lookaside.bMalloced = 0;
111049 return SQLITE_OK;
111053 ** Return the mutex associated with a database connection.
111055 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
111056 return db->mutex;
111060 ** Configuration settings for an individual database connection
111062 SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
111063 va_list ap;
111064 int rc;
111065 va_start(ap, op);
111066 switch( op ){
111067 case SQLITE_DBCONFIG_LOOKASIDE: {
111068 void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
111069 int sz = va_arg(ap, int); /* IMP: R-47871-25994 */
111070 int cnt = va_arg(ap, int); /* IMP: R-04460-53386 */
111071 rc = setupLookaside(db, pBuf, sz, cnt);
111072 break;
111074 default: {
111075 static const struct {
111076 int op; /* The opcode */
111077 u32 mask; /* Mask of the bit in sqlite3.flags to set/clear */
111078 } aFlagOp[] = {
111079 { SQLITE_DBCONFIG_ENABLE_FKEY, SQLITE_ForeignKeys },
111080 { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger },
111082 unsigned int i;
111083 rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
111084 for(i=0; i<ArraySize(aFlagOp); i++){
111085 if( aFlagOp[i].op==op ){
111086 int onoff = va_arg(ap, int);
111087 int *pRes = va_arg(ap, int*);
111088 int oldFlags = db->flags;
111089 if( onoff>0 ){
111090 db->flags |= aFlagOp[i].mask;
111091 }else if( onoff==0 ){
111092 db->flags &= ~aFlagOp[i].mask;
111094 if( oldFlags!=db->flags ){
111095 sqlite3ExpirePreparedStatements(db);
111097 if( pRes ){
111098 *pRes = (db->flags & aFlagOp[i].mask)!=0;
111100 rc = SQLITE_OK;
111101 break;
111104 break;
111107 va_end(ap);
111108 return rc;
111113 ** Return true if the buffer z[0..n-1] contains all spaces.
111115 static int allSpaces(const char *z, int n){
111116 while( n>0 && z[n-1]==' ' ){ n--; }
111117 return n==0;
111121 ** This is the default collating function named "BINARY" which is always
111122 ** available.
111124 ** If the padFlag argument is not NULL then space padding at the end
111125 ** of strings is ignored. This implements the RTRIM collation.
111127 static int binCollFunc(
111128 void *padFlag,
111129 int nKey1, const void *pKey1,
111130 int nKey2, const void *pKey2
111132 int rc, n;
111133 n = nKey1<nKey2 ? nKey1 : nKey2;
111134 rc = memcmp(pKey1, pKey2, n);
111135 if( rc==0 ){
111136 if( padFlag
111137 && allSpaces(((char*)pKey1)+n, nKey1-n)
111138 && allSpaces(((char*)pKey2)+n, nKey2-n)
111140 /* Leave rc unchanged at 0 */
111141 }else{
111142 rc = nKey1 - nKey2;
111145 return rc;
111149 ** Another built-in collating sequence: NOCASE.
111151 ** This collating sequence is intended to be used for "case independant
111152 ** comparison". SQLite's knowledge of upper and lower case equivalents
111153 ** extends only to the 26 characters used in the English language.
111155 ** At the moment there is only a UTF-8 implementation.
111157 static int nocaseCollatingFunc(
111158 void *NotUsed,
111159 int nKey1, const void *pKey1,
111160 int nKey2, const void *pKey2
111162 int r = sqlite3StrNICmp(
111163 (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
111164 UNUSED_PARAMETER(NotUsed);
111165 if( 0==r ){
111166 r = nKey1-nKey2;
111168 return r;
111172 ** Return the ROWID of the most recent insert
111174 SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
111175 return db->lastRowid;
111179 ** Return the number of changes in the most recent call to sqlite3_exec().
111181 SQLITE_API int sqlite3_changes(sqlite3 *db){
111182 return db->nChange;
111186 ** Return the number of changes since the database handle was opened.
111188 SQLITE_API int sqlite3_total_changes(sqlite3 *db){
111189 return db->nTotalChange;
111193 ** Close all open savepoints. This function only manipulates fields of the
111194 ** database handle object, it does not close any savepoints that may be open
111195 ** at the b-tree/pager level.
111197 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
111198 while( db->pSavepoint ){
111199 Savepoint *pTmp = db->pSavepoint;
111200 db->pSavepoint = pTmp->pNext;
111201 sqlite3DbFree(db, pTmp);
111203 db->nSavepoint = 0;
111204 db->nStatement = 0;
111205 db->isTransactionSavepoint = 0;
111209 ** Invoke the destructor function associated with FuncDef p, if any. Except,
111210 ** if this is not the last copy of the function, do not invoke it. Multiple
111211 ** copies of a single function are created when create_function() is called
111212 ** with SQLITE_ANY as the encoding.
111214 static void functionDestroy(sqlite3 *db, FuncDef *p){
111215 FuncDestructor *pDestructor = p->pDestructor;
111216 if( pDestructor ){
111217 pDestructor->nRef--;
111218 if( pDestructor->nRef==0 ){
111219 pDestructor->xDestroy(pDestructor->pUserData);
111220 sqlite3DbFree(db, pDestructor);
111226 ** Close an existing SQLite database
111228 SQLITE_API int sqlite3_close(sqlite3 *db){
111229 HashElem *i; /* Hash table iterator */
111230 int j;
111232 if( !db ){
111233 return SQLITE_OK;
111235 if( !sqlite3SafetyCheckSickOrOk(db) ){
111236 return SQLITE_MISUSE_BKPT;
111238 sqlite3_mutex_enter(db->mutex);
111240 /* Force xDestroy calls on all virtual tables */
111241 sqlite3ResetInternalSchema(db, -1);
111243 /* If a transaction is open, the ResetInternalSchema() call above
111244 ** will not have called the xDisconnect() method on any virtual
111245 ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
111246 ** call will do so. We need to do this before the check for active
111247 ** SQL statements below, as the v-table implementation may be storing
111248 ** some prepared statements internally.
111250 sqlite3VtabRollback(db);
111252 /* If there are any outstanding VMs, return SQLITE_BUSY. */
111253 if( db->pVdbe ){
111254 sqlite3Error(db, SQLITE_BUSY,
111255 "unable to close due to unfinalised statements");
111256 sqlite3_mutex_leave(db->mutex);
111257 return SQLITE_BUSY;
111259 assert( sqlite3SafetyCheckSickOrOk(db) );
111261 for(j=0; j<db->nDb; j++){
111262 Btree *pBt = db->aDb[j].pBt;
111263 if( pBt && sqlite3BtreeIsInBackup(pBt) ){
111264 sqlite3Error(db, SQLITE_BUSY,
111265 "unable to close due to unfinished backup operation");
111266 sqlite3_mutex_leave(db->mutex);
111267 return SQLITE_BUSY;
111271 /* Free any outstanding Savepoint structures. */
111272 sqlite3CloseSavepoints(db);
111274 for(j=0; j<db->nDb; j++){
111275 struct Db *pDb = &db->aDb[j];
111276 if( pDb->pBt ){
111277 sqlite3BtreeClose(pDb->pBt);
111278 pDb->pBt = 0;
111279 if( j!=1 ){
111280 pDb->pSchema = 0;
111284 sqlite3ResetInternalSchema(db, -1);
111286 /* Tell the code in notify.c that the connection no longer holds any
111287 ** locks and does not require any further unlock-notify callbacks.
111289 sqlite3ConnectionClosed(db);
111291 assert( db->nDb<=2 );
111292 assert( db->aDb==db->aDbStatic );
111293 for(j=0; j<ArraySize(db->aFunc.a); j++){
111294 FuncDef *pNext, *pHash, *p;
111295 for(p=db->aFunc.a[j]; p; p=pHash){
111296 pHash = p->pHash;
111297 while( p ){
111298 functionDestroy(db, p);
111299 pNext = p->pNext;
111300 sqlite3DbFree(db, p);
111301 p = pNext;
111305 for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
111306 CollSeq *pColl = (CollSeq *)sqliteHashData(i);
111307 /* Invoke any destructors registered for collation sequence user data. */
111308 for(j=0; j<3; j++){
111309 if( pColl[j].xDel ){
111310 pColl[j].xDel(pColl[j].pUser);
111313 sqlite3DbFree(db, pColl);
111315 sqlite3HashClear(&db->aCollSeq);
111316 #ifndef SQLITE_OMIT_VIRTUALTABLE
111317 for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
111318 Module *pMod = (Module *)sqliteHashData(i);
111319 if( pMod->xDestroy ){
111320 pMod->xDestroy(pMod->pAux);
111322 sqlite3DbFree(db, pMod);
111324 sqlite3HashClear(&db->aModule);
111325 #endif
111327 sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
111328 if( db->pErr ){
111329 sqlite3ValueFree(db->pErr);
111331 sqlite3CloseExtensions(db);
111333 db->magic = SQLITE_MAGIC_ERROR;
111335 /* The temp-database schema is allocated differently from the other schema
111336 ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
111337 ** So it needs to be freed here. Todo: Why not roll the temp schema into
111338 ** the same sqliteMalloc() as the one that allocates the database
111339 ** structure?
111341 sqlite3DbFree(db, db->aDb[1].pSchema);
111342 sqlite3_mutex_leave(db->mutex);
111343 db->magic = SQLITE_MAGIC_CLOSED;
111344 sqlite3_mutex_free(db->mutex);
111345 assert( db->lookaside.nOut==0 ); /* Fails on a lookaside memory leak */
111346 if( db->lookaside.bMalloced ){
111347 sqlite3_free(db->lookaside.pStart);
111349 sqlite3_free(db);
111350 return SQLITE_OK;
111354 ** Rollback all database files.
111356 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db){
111357 int i;
111358 int inTrans = 0;
111359 assert( sqlite3_mutex_held(db->mutex) );
111360 sqlite3BeginBenignMalloc();
111361 for(i=0; i<db->nDb; i++){
111362 if( db->aDb[i].pBt ){
111363 if( sqlite3BtreeIsInTrans(db->aDb[i].pBt) ){
111364 inTrans = 1;
111366 sqlite3BtreeRollback(db->aDb[i].pBt);
111367 db->aDb[i].inTrans = 0;
111370 sqlite3VtabRollback(db);
111371 sqlite3EndBenignMalloc();
111373 if( db->flags&SQLITE_InternChanges ){
111374 sqlite3ExpirePreparedStatements(db);
111375 sqlite3ResetInternalSchema(db, -1);
111378 /* Any deferred constraint violations have now been resolved. */
111379 db->nDeferredCons = 0;
111381 /* If one has been configured, invoke the rollback-hook callback */
111382 if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
111383 db->xRollbackCallback(db->pRollbackArg);
111388 ** Return a static string that describes the kind of error specified in the
111389 ** argument.
111391 SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
111392 static const char* const aMsg[] = {
111393 /* SQLITE_OK */ "not an error",
111394 /* SQLITE_ERROR */ "SQL logic error or missing database",
111395 /* SQLITE_INTERNAL */ 0,
111396 /* SQLITE_PERM */ "access permission denied",
111397 /* SQLITE_ABORT */ "callback requested query abort",
111398 /* SQLITE_BUSY */ "database is locked",
111399 /* SQLITE_LOCKED */ "database table is locked",
111400 /* SQLITE_NOMEM */ "out of memory",
111401 /* SQLITE_READONLY */ "attempt to write a readonly database",
111402 /* SQLITE_INTERRUPT */ "interrupted",
111403 /* SQLITE_IOERR */ "disk I/O error",
111404 /* SQLITE_CORRUPT */ "database disk image is malformed",
111405 /* SQLITE_NOTFOUND */ "unknown operation",
111406 /* SQLITE_FULL */ "database or disk is full",
111407 /* SQLITE_CANTOPEN */ "unable to open database file",
111408 /* SQLITE_PROTOCOL */ "locking protocol",
111409 /* SQLITE_EMPTY */ "table contains no data",
111410 /* SQLITE_SCHEMA */ "database schema has changed",
111411 /* SQLITE_TOOBIG */ "string or blob too big",
111412 /* SQLITE_CONSTRAINT */ "constraint failed",
111413 /* SQLITE_MISMATCH */ "datatype mismatch",
111414 /* SQLITE_MISUSE */ "library routine called out of sequence",
111415 /* SQLITE_NOLFS */ "large file support is disabled",
111416 /* SQLITE_AUTH */ "authorization denied",
111417 /* SQLITE_FORMAT */ "auxiliary database format error",
111418 /* SQLITE_RANGE */ "bind or column index out of range",
111419 /* SQLITE_NOTADB */ "file is encrypted or is not a database",
111421 rc &= 0xff;
111422 if( ALWAYS(rc>=0) && rc<(int)(sizeof(aMsg)/sizeof(aMsg[0])) && aMsg[rc]!=0 ){
111423 return aMsg[rc];
111424 }else{
111425 return "unknown error";
111430 ** This routine implements a busy callback that sleeps and tries
111431 ** again until a timeout value is reached. The timeout value is
111432 ** an integer number of milliseconds passed in as the first
111433 ** argument.
111435 static int sqliteDefaultBusyCallback(
111436 void *ptr, /* Database connection */
111437 int count /* Number of times table has been busy */
111439 #if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
111440 static const u8 delays[] =
111441 { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 };
111442 static const u8 totals[] =
111443 { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 };
111444 # define NDELAY ArraySize(delays)
111445 sqlite3 *db = (sqlite3 *)ptr;
111446 int timeout = db->busyTimeout;
111447 int delay, prior;
111449 assert( count>=0 );
111450 if( count < NDELAY ){
111451 delay = delays[count];
111452 prior = totals[count];
111453 }else{
111454 delay = delays[NDELAY-1];
111455 prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
111457 if( prior + delay > timeout ){
111458 delay = timeout - prior;
111459 if( delay<=0 ) return 0;
111461 sqlite3OsSleep(db->pVfs, delay*1000);
111462 return 1;
111463 #else
111464 sqlite3 *db = (sqlite3 *)ptr;
111465 int timeout = ((sqlite3 *)ptr)->busyTimeout;
111466 if( (count+1)*1000 > timeout ){
111467 return 0;
111469 sqlite3OsSleep(db->pVfs, 1000000);
111470 return 1;
111471 #endif
111475 ** Invoke the given busy handler.
111477 ** This routine is called when an operation failed with a lock.
111478 ** If this routine returns non-zero, the lock is retried. If it
111479 ** returns 0, the operation aborts with an SQLITE_BUSY error.
111481 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
111482 int rc;
111483 if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
111484 rc = p->xFunc(p->pArg, p->nBusy);
111485 if( rc==0 ){
111486 p->nBusy = -1;
111487 }else{
111488 p->nBusy++;
111490 return rc;
111494 ** This routine sets the busy callback for an Sqlite database to the
111495 ** given callback function with the given argument.
111497 SQLITE_API int sqlite3_busy_handler(
111498 sqlite3 *db,
111499 int (*xBusy)(void*,int),
111500 void *pArg
111502 sqlite3_mutex_enter(db->mutex);
111503 db->busyHandler.xFunc = xBusy;
111504 db->busyHandler.pArg = pArg;
111505 db->busyHandler.nBusy = 0;
111506 sqlite3_mutex_leave(db->mutex);
111507 return SQLITE_OK;
111510 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
111512 ** This routine sets the progress callback for an Sqlite database to the
111513 ** given callback function with the given argument. The progress callback will
111514 ** be invoked every nOps opcodes.
111516 SQLITE_API void sqlite3_progress_handler(
111517 sqlite3 *db,
111518 int nOps,
111519 int (*xProgress)(void*),
111520 void *pArg
111522 sqlite3_mutex_enter(db->mutex);
111523 if( nOps>0 ){
111524 db->xProgress = xProgress;
111525 db->nProgressOps = nOps;
111526 db->pProgressArg = pArg;
111527 }else{
111528 db->xProgress = 0;
111529 db->nProgressOps = 0;
111530 db->pProgressArg = 0;
111532 sqlite3_mutex_leave(db->mutex);
111534 #endif
111538 ** This routine installs a default busy handler that waits for the
111539 ** specified number of milliseconds before returning 0.
111541 SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
111542 if( ms>0 ){
111543 db->busyTimeout = ms;
111544 sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
111545 }else{
111546 sqlite3_busy_handler(db, 0, 0);
111548 return SQLITE_OK;
111552 ** Cause any pending operation to stop at its earliest opportunity.
111554 SQLITE_API void sqlite3_interrupt(sqlite3 *db){
111555 db->u1.isInterrupted = 1;
111560 ** This function is exactly the same as sqlite3_create_function(), except
111561 ** that it is designed to be called by internal code. The difference is
111562 ** that if a malloc() fails in sqlite3_create_function(), an error code
111563 ** is returned and the mallocFailed flag cleared.
111565 SQLITE_PRIVATE int sqlite3CreateFunc(
111566 sqlite3 *db,
111567 const char *zFunctionName,
111568 int nArg,
111569 int enc,
111570 void *pUserData,
111571 void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
111572 void (*xStep)(sqlite3_context*,int,sqlite3_value **),
111573 void (*xFinal)(sqlite3_context*),
111574 FuncDestructor *pDestructor
111576 FuncDef *p;
111577 int nName;
111579 assert( sqlite3_mutex_held(db->mutex) );
111580 if( zFunctionName==0 ||
111581 (xFunc && (xFinal || xStep)) ||
111582 (!xFunc && (xFinal && !xStep)) ||
111583 (!xFunc && (!xFinal && xStep)) ||
111584 (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
111585 (255<(nName = sqlite3Strlen30( zFunctionName))) ){
111586 return SQLITE_MISUSE_BKPT;
111589 #ifndef SQLITE_OMIT_UTF16
111590 /* If SQLITE_UTF16 is specified as the encoding type, transform this
111591 ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
111592 ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
111594 ** If SQLITE_ANY is specified, add three versions of the function
111595 ** to the hash table.
111597 if( enc==SQLITE_UTF16 ){
111598 enc = SQLITE_UTF16NATIVE;
111599 }else if( enc==SQLITE_ANY ){
111600 int rc;
111601 rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
111602 pUserData, xFunc, xStep, xFinal, pDestructor);
111603 if( rc==SQLITE_OK ){
111604 rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
111605 pUserData, xFunc, xStep, xFinal, pDestructor);
111607 if( rc!=SQLITE_OK ){
111608 return rc;
111610 enc = SQLITE_UTF16BE;
111612 #else
111613 enc = SQLITE_UTF8;
111614 #endif
111616 /* Check if an existing function is being overridden or deleted. If so,
111617 ** and there are active VMs, then return SQLITE_BUSY. If a function
111618 ** is being overridden/deleted but there are no active VMs, allow the
111619 ** operation to continue but invalidate all precompiled statements.
111621 p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
111622 if( p && p->iPrefEnc==enc && p->nArg==nArg ){
111623 if( db->activeVdbeCnt ){
111624 sqlite3Error(db, SQLITE_BUSY,
111625 "unable to delete/modify user-function due to active statements");
111626 assert( !db->mallocFailed );
111627 return SQLITE_BUSY;
111628 }else{
111629 sqlite3ExpirePreparedStatements(db);
111633 p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
111634 assert(p || db->mallocFailed);
111635 if( !p ){
111636 return SQLITE_NOMEM;
111639 /* If an older version of the function with a configured destructor is
111640 ** being replaced invoke the destructor function here. */
111641 functionDestroy(db, p);
111643 if( pDestructor ){
111644 pDestructor->nRef++;
111646 p->pDestructor = pDestructor;
111647 p->flags = 0;
111648 p->xFunc = xFunc;
111649 p->xStep = xStep;
111650 p->xFinalize = xFinal;
111651 p->pUserData = pUserData;
111652 p->nArg = (u16)nArg;
111653 return SQLITE_OK;
111657 ** Create new user functions.
111659 SQLITE_API int sqlite3_create_function(
111660 sqlite3 *db,
111661 const char *zFunc,
111662 int nArg,
111663 int enc,
111664 void *p,
111665 void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
111666 void (*xStep)(sqlite3_context*,int,sqlite3_value **),
111667 void (*xFinal)(sqlite3_context*)
111669 return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
111670 xFinal, 0);
111673 SQLITE_API int sqlite3_create_function_v2(
111674 sqlite3 *db,
111675 const char *zFunc,
111676 int nArg,
111677 int enc,
111678 void *p,
111679 void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
111680 void (*xStep)(sqlite3_context*,int,sqlite3_value **),
111681 void (*xFinal)(sqlite3_context*),
111682 void (*xDestroy)(void *)
111684 int rc = SQLITE_ERROR;
111685 FuncDestructor *pArg = 0;
111686 sqlite3_mutex_enter(db->mutex);
111687 if( xDestroy ){
111688 pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
111689 if( !pArg ){
111690 xDestroy(p);
111691 goto out;
111693 pArg->xDestroy = xDestroy;
111694 pArg->pUserData = p;
111696 rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
111697 if( pArg && pArg->nRef==0 ){
111698 assert( rc!=SQLITE_OK );
111699 xDestroy(p);
111700 sqlite3DbFree(db, pArg);
111704 rc = sqlite3ApiExit(db, rc);
111705 sqlite3_mutex_leave(db->mutex);
111706 return rc;
111709 #ifndef SQLITE_OMIT_UTF16
111710 SQLITE_API int sqlite3_create_function16(
111711 sqlite3 *db,
111712 const void *zFunctionName,
111713 int nArg,
111714 int eTextRep,
111715 void *p,
111716 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
111717 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
111718 void (*xFinal)(sqlite3_context*)
111720 int rc;
111721 char *zFunc8;
111722 sqlite3_mutex_enter(db->mutex);
111723 assert( !db->mallocFailed );
111724 zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
111725 rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
111726 sqlite3DbFree(db, zFunc8);
111727 rc = sqlite3ApiExit(db, rc);
111728 sqlite3_mutex_leave(db->mutex);
111729 return rc;
111731 #endif
111735 ** Declare that a function has been overloaded by a virtual table.
111737 ** If the function already exists as a regular global function, then
111738 ** this routine is a no-op. If the function does not exist, then create
111739 ** a new one that always throws a run-time error.
111741 ** When virtual tables intend to provide an overloaded function, they
111742 ** should call this routine to make sure the global function exists.
111743 ** A global function must exist in order for name resolution to work
111744 ** properly.
111746 SQLITE_API int sqlite3_overload_function(
111747 sqlite3 *db,
111748 const char *zName,
111749 int nArg
111751 int nName = sqlite3Strlen30(zName);
111752 int rc = SQLITE_OK;
111753 sqlite3_mutex_enter(db->mutex);
111754 if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
111755 rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
111756 0, sqlite3InvalidFunction, 0, 0, 0);
111758 rc = sqlite3ApiExit(db, rc);
111759 sqlite3_mutex_leave(db->mutex);
111760 return rc;
111763 #ifndef SQLITE_OMIT_TRACE
111765 ** Register a trace function. The pArg from the previously registered trace
111766 ** is returned.
111768 ** A NULL trace function means that no tracing is executes. A non-NULL
111769 ** trace is a pointer to a function that is invoked at the start of each
111770 ** SQL statement.
111772 SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
111773 void *pOld;
111774 sqlite3_mutex_enter(db->mutex);
111775 pOld = db->pTraceArg;
111776 db->xTrace = xTrace;
111777 db->pTraceArg = pArg;
111778 sqlite3_mutex_leave(db->mutex);
111779 return pOld;
111782 ** Register a profile function. The pArg from the previously registered
111783 ** profile function is returned.
111785 ** A NULL profile function means that no profiling is executes. A non-NULL
111786 ** profile is a pointer to a function that is invoked at the conclusion of
111787 ** each SQL statement that is run.
111789 SQLITE_API void *sqlite3_profile(
111790 sqlite3 *db,
111791 void (*xProfile)(void*,const char*,sqlite_uint64),
111792 void *pArg
111794 void *pOld;
111795 sqlite3_mutex_enter(db->mutex);
111796 pOld = db->pProfileArg;
111797 db->xProfile = xProfile;
111798 db->pProfileArg = pArg;
111799 sqlite3_mutex_leave(db->mutex);
111800 return pOld;
111802 #endif /* SQLITE_OMIT_TRACE */
111804 /*** EXPERIMENTAL ***
111806 ** Register a function to be invoked when a transaction comments.
111807 ** If the invoked function returns non-zero, then the commit becomes a
111808 ** rollback.
111810 SQLITE_API void *sqlite3_commit_hook(
111811 sqlite3 *db, /* Attach the hook to this database */
111812 int (*xCallback)(void*), /* Function to invoke on each commit */
111813 void *pArg /* Argument to the function */
111815 void *pOld;
111816 sqlite3_mutex_enter(db->mutex);
111817 pOld = db->pCommitArg;
111818 db->xCommitCallback = xCallback;
111819 db->pCommitArg = pArg;
111820 sqlite3_mutex_leave(db->mutex);
111821 return pOld;
111825 ** Register a callback to be invoked each time a row is updated,
111826 ** inserted or deleted using this database connection.
111828 SQLITE_API void *sqlite3_update_hook(
111829 sqlite3 *db, /* Attach the hook to this database */
111830 void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
111831 void *pArg /* Argument to the function */
111833 void *pRet;
111834 sqlite3_mutex_enter(db->mutex);
111835 pRet = db->pUpdateArg;
111836 db->xUpdateCallback = xCallback;
111837 db->pUpdateArg = pArg;
111838 sqlite3_mutex_leave(db->mutex);
111839 return pRet;
111843 ** Register a callback to be invoked each time a transaction is rolled
111844 ** back by this database connection.
111846 SQLITE_API void *sqlite3_rollback_hook(
111847 sqlite3 *db, /* Attach the hook to this database */
111848 void (*xCallback)(void*), /* Callback function */
111849 void *pArg /* Argument to the function */
111851 void *pRet;
111852 sqlite3_mutex_enter(db->mutex);
111853 pRet = db->pRollbackArg;
111854 db->xRollbackCallback = xCallback;
111855 db->pRollbackArg = pArg;
111856 sqlite3_mutex_leave(db->mutex);
111857 return pRet;
111860 #ifndef SQLITE_OMIT_WAL
111862 ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
111863 ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
111864 ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
111865 ** wal_autocheckpoint()).
111867 SQLITE_PRIVATE int sqlite3WalDefaultHook(
111868 void *pClientData, /* Argument */
111869 sqlite3 *db, /* Connection */
111870 const char *zDb, /* Database */
111871 int nFrame /* Size of WAL */
111873 if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
111874 sqlite3BeginBenignMalloc();
111875 sqlite3_wal_checkpoint(db, zDb);
111876 sqlite3EndBenignMalloc();
111878 return SQLITE_OK;
111880 #endif /* SQLITE_OMIT_WAL */
111883 ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
111884 ** a database after committing a transaction if there are nFrame or
111885 ** more frames in the log file. Passing zero or a negative value as the
111886 ** nFrame parameter disables automatic checkpoints entirely.
111888 ** The callback registered by this function replaces any existing callback
111889 ** registered using sqlite3_wal_hook(). Likewise, registering a callback
111890 ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
111891 ** configured by this function.
111893 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
111894 #ifdef SQLITE_OMIT_WAL
111895 UNUSED_PARAMETER(db);
111896 UNUSED_PARAMETER(nFrame);
111897 #else
111898 if( nFrame>0 ){
111899 sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
111900 }else{
111901 sqlite3_wal_hook(db, 0, 0);
111903 #endif
111904 return SQLITE_OK;
111908 ** Register a callback to be invoked each time a transaction is written
111909 ** into the write-ahead-log by this database connection.
111911 SQLITE_API void *sqlite3_wal_hook(
111912 sqlite3 *db, /* Attach the hook to this db handle */
111913 int(*xCallback)(void *, sqlite3*, const char*, int),
111914 void *pArg /* First argument passed to xCallback() */
111916 #ifndef SQLITE_OMIT_WAL
111917 void *pRet;
111918 sqlite3_mutex_enter(db->mutex);
111919 pRet = db->pWalArg;
111920 db->xWalCallback = xCallback;
111921 db->pWalArg = pArg;
111922 sqlite3_mutex_leave(db->mutex);
111923 return pRet;
111924 #else
111925 return 0;
111926 #endif
111930 ** Checkpoint database zDb.
111932 SQLITE_API int sqlite3_wal_checkpoint_v2(
111933 sqlite3 *db, /* Database handle */
111934 const char *zDb, /* Name of attached database (or NULL) */
111935 int eMode, /* SQLITE_CHECKPOINT_* value */
111936 int *pnLog, /* OUT: Size of WAL log in frames */
111937 int *pnCkpt /* OUT: Total number of frames checkpointed */
111939 #ifdef SQLITE_OMIT_WAL
111940 return SQLITE_OK;
111941 #else
111942 int rc; /* Return code */
111943 int iDb = SQLITE_MAX_ATTACHED; /* sqlite3.aDb[] index of db to checkpoint */
111945 /* Initialize the output variables to -1 in case an error occurs. */
111946 if( pnLog ) *pnLog = -1;
111947 if( pnCkpt ) *pnCkpt = -1;
111949 assert( SQLITE_CHECKPOINT_FULL>SQLITE_CHECKPOINT_PASSIVE );
111950 assert( SQLITE_CHECKPOINT_FULL<SQLITE_CHECKPOINT_RESTART );
111951 assert( SQLITE_CHECKPOINT_PASSIVE+2==SQLITE_CHECKPOINT_RESTART );
111952 if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_RESTART ){
111953 return SQLITE_MISUSE;
111956 sqlite3_mutex_enter(db->mutex);
111957 if( zDb && zDb[0] ){
111958 iDb = sqlite3FindDbName(db, zDb);
111960 if( iDb<0 ){
111961 rc = SQLITE_ERROR;
111962 sqlite3Error(db, SQLITE_ERROR, "unknown database: %s", zDb);
111963 }else{
111964 rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
111965 sqlite3Error(db, rc, 0);
111967 rc = sqlite3ApiExit(db, rc);
111968 sqlite3_mutex_leave(db->mutex);
111969 return rc;
111970 #endif
111975 ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
111976 ** to contains a zero-length string, all attached databases are
111977 ** checkpointed.
111979 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
111980 return sqlite3_wal_checkpoint_v2(db, zDb, SQLITE_CHECKPOINT_PASSIVE, 0, 0);
111983 #ifndef SQLITE_OMIT_WAL
111985 ** Run a checkpoint on database iDb. This is a no-op if database iDb is
111986 ** not currently open in WAL mode.
111988 ** If a transaction is open on the database being checkpointed, this
111989 ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
111990 ** an error occurs while running the checkpoint, an SQLite error code is
111991 ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
111993 ** The mutex on database handle db should be held by the caller. The mutex
111994 ** associated with the specific b-tree being checkpointed is taken by
111995 ** this function while the checkpoint is running.
111997 ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
111998 ** checkpointed. If an error is encountered it is returned immediately -
111999 ** no attempt is made to checkpoint any remaining databases.
112001 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
112003 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
112004 int rc = SQLITE_OK; /* Return code */
112005 int i; /* Used to iterate through attached dbs */
112006 int bBusy = 0; /* True if SQLITE_BUSY has been encountered */
112008 assert( sqlite3_mutex_held(db->mutex) );
112009 assert( !pnLog || *pnLog==-1 );
112010 assert( !pnCkpt || *pnCkpt==-1 );
112012 for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
112013 if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
112014 rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
112015 pnLog = 0;
112016 pnCkpt = 0;
112017 if( rc==SQLITE_BUSY ){
112018 bBusy = 1;
112019 rc = SQLITE_OK;
112024 return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
112026 #endif /* SQLITE_OMIT_WAL */
112029 ** This function returns true if main-memory should be used instead of
112030 ** a temporary file for transient pager files and statement journals.
112031 ** The value returned depends on the value of db->temp_store (runtime
112032 ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
112033 ** following table describes the relationship between these two values
112034 ** and this functions return value.
112036 ** SQLITE_TEMP_STORE db->temp_store Location of temporary database
112037 ** ----------------- -------------- ------------------------------
112038 ** 0 any file (return 0)
112039 ** 1 1 file (return 0)
112040 ** 1 2 memory (return 1)
112041 ** 1 0 file (return 0)
112042 ** 2 1 file (return 0)
112043 ** 2 2 memory (return 1)
112044 ** 2 0 memory (return 1)
112045 ** 3 any memory (return 1)
112047 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
112048 #if SQLITE_TEMP_STORE==1
112049 return ( db->temp_store==2 );
112050 #endif
112051 #if SQLITE_TEMP_STORE==2
112052 return ( db->temp_store!=1 );
112053 #endif
112054 #if SQLITE_TEMP_STORE==3
112055 return 1;
112056 #endif
112057 #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
112058 return 0;
112059 #endif
112063 ** Return UTF-8 encoded English language explanation of the most recent
112064 ** error.
112066 SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
112067 const char *z;
112068 if( !db ){
112069 return sqlite3ErrStr(SQLITE_NOMEM);
112071 if( !sqlite3SafetyCheckSickOrOk(db) ){
112072 return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
112074 sqlite3_mutex_enter(db->mutex);
112075 if( db->mallocFailed ){
112076 z = sqlite3ErrStr(SQLITE_NOMEM);
112077 }else{
112078 z = (char*)sqlite3_value_text(db->pErr);
112079 assert( !db->mallocFailed );
112080 if( z==0 ){
112081 z = sqlite3ErrStr(db->errCode);
112084 sqlite3_mutex_leave(db->mutex);
112085 return z;
112088 #ifndef SQLITE_OMIT_UTF16
112090 ** Return UTF-16 encoded English language explanation of the most recent
112091 ** error.
112093 SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
112094 static const u16 outOfMem[] = {
112095 'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
112097 static const u16 misuse[] = {
112098 'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
112099 'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
112100 'c', 'a', 'l', 'l', 'e', 'd', ' ',
112101 'o', 'u', 't', ' ',
112102 'o', 'f', ' ',
112103 's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
112106 const void *z;
112107 if( !db ){
112108 return (void *)outOfMem;
112110 if( !sqlite3SafetyCheckSickOrOk(db) ){
112111 return (void *)misuse;
112113 sqlite3_mutex_enter(db->mutex);
112114 if( db->mallocFailed ){
112115 z = (void *)outOfMem;
112116 }else{
112117 z = sqlite3_value_text16(db->pErr);
112118 if( z==0 ){
112119 sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
112120 SQLITE_UTF8, SQLITE_STATIC);
112121 z = sqlite3_value_text16(db->pErr);
112123 /* A malloc() may have failed within the call to sqlite3_value_text16()
112124 ** above. If this is the case, then the db->mallocFailed flag needs to
112125 ** be cleared before returning. Do this directly, instead of via
112126 ** sqlite3ApiExit(), to avoid setting the database handle error message.
112128 db->mallocFailed = 0;
112130 sqlite3_mutex_leave(db->mutex);
112131 return z;
112133 #endif /* SQLITE_OMIT_UTF16 */
112136 ** Return the most recent error code generated by an SQLite routine. If NULL is
112137 ** passed to this function, we assume a malloc() failed during sqlite3_open().
112139 SQLITE_API int sqlite3_errcode(sqlite3 *db){
112140 if( db && !sqlite3SafetyCheckSickOrOk(db) ){
112141 return SQLITE_MISUSE_BKPT;
112143 if( !db || db->mallocFailed ){
112144 return SQLITE_NOMEM;
112146 return db->errCode & db->errMask;
112148 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
112149 if( db && !sqlite3SafetyCheckSickOrOk(db) ){
112150 return SQLITE_MISUSE_BKPT;
112152 if( !db || db->mallocFailed ){
112153 return SQLITE_NOMEM;
112155 return db->errCode;
112159 ** Create a new collating function for database "db". The name is zName
112160 ** and the encoding is enc.
112162 static int createCollation(
112163 sqlite3* db,
112164 const char *zName,
112165 u8 enc,
112166 u8 collType,
112167 void* pCtx,
112168 int(*xCompare)(void*,int,const void*,int,const void*),
112169 void(*xDel)(void*)
112171 CollSeq *pColl;
112172 int enc2;
112173 int nName = sqlite3Strlen30(zName);
112175 assert( sqlite3_mutex_held(db->mutex) );
112177 /* If SQLITE_UTF16 is specified as the encoding type, transform this
112178 ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
112179 ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
112181 enc2 = enc;
112182 testcase( enc2==SQLITE_UTF16 );
112183 testcase( enc2==SQLITE_UTF16_ALIGNED );
112184 if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
112185 enc2 = SQLITE_UTF16NATIVE;
112187 if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
112188 return SQLITE_MISUSE_BKPT;
112191 /* Check if this call is removing or replacing an existing collation
112192 ** sequence. If so, and there are active VMs, return busy. If there
112193 ** are no active VMs, invalidate any pre-compiled statements.
112195 pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
112196 if( pColl && pColl->xCmp ){
112197 if( db->activeVdbeCnt ){
112198 sqlite3Error(db, SQLITE_BUSY,
112199 "unable to delete/modify collation sequence due to active statements");
112200 return SQLITE_BUSY;
112202 sqlite3ExpirePreparedStatements(db);
112204 /* If collation sequence pColl was created directly by a call to
112205 ** sqlite3_create_collation, and not generated by synthCollSeq(),
112206 ** then any copies made by synthCollSeq() need to be invalidated.
112207 ** Also, collation destructor - CollSeq.xDel() - function may need
112208 ** to be called.
112210 if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
112211 CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
112212 int j;
112213 for(j=0; j<3; j++){
112214 CollSeq *p = &aColl[j];
112215 if( p->enc==pColl->enc ){
112216 if( p->xDel ){
112217 p->xDel(p->pUser);
112219 p->xCmp = 0;
112225 pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
112226 if( pColl==0 ) return SQLITE_NOMEM;
112227 pColl->xCmp = xCompare;
112228 pColl->pUser = pCtx;
112229 pColl->xDel = xDel;
112230 pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
112231 pColl->type = collType;
112232 sqlite3Error(db, SQLITE_OK, 0);
112233 return SQLITE_OK;
112238 ** This array defines hard upper bounds on limit values. The
112239 ** initializer must be kept in sync with the SQLITE_LIMIT_*
112240 ** #defines in sqlite3.h.
112242 static const int aHardLimit[] = {
112243 SQLITE_MAX_LENGTH,
112244 SQLITE_MAX_SQL_LENGTH,
112245 SQLITE_MAX_COLUMN,
112246 SQLITE_MAX_EXPR_DEPTH,
112247 SQLITE_MAX_COMPOUND_SELECT,
112248 SQLITE_MAX_VDBE_OP,
112249 SQLITE_MAX_FUNCTION_ARG,
112250 SQLITE_MAX_ATTACHED,
112251 SQLITE_MAX_LIKE_PATTERN_LENGTH,
112252 SQLITE_MAX_VARIABLE_NUMBER,
112253 SQLITE_MAX_TRIGGER_DEPTH,
112257 ** Make sure the hard limits are set to reasonable values
112259 #if SQLITE_MAX_LENGTH<100
112260 # error SQLITE_MAX_LENGTH must be at least 100
112261 #endif
112262 #if SQLITE_MAX_SQL_LENGTH<100
112263 # error SQLITE_MAX_SQL_LENGTH must be at least 100
112264 #endif
112265 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
112266 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
112267 #endif
112268 #if SQLITE_MAX_COMPOUND_SELECT<2
112269 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
112270 #endif
112271 #if SQLITE_MAX_VDBE_OP<40
112272 # error SQLITE_MAX_VDBE_OP must be at least 40
112273 #endif
112274 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
112275 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
112276 #endif
112277 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>62
112278 # error SQLITE_MAX_ATTACHED must be between 0 and 62
112279 #endif
112280 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
112281 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
112282 #endif
112283 #if SQLITE_MAX_COLUMN>32767
112284 # error SQLITE_MAX_COLUMN must not exceed 32767
112285 #endif
112286 #if SQLITE_MAX_TRIGGER_DEPTH<1
112287 # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
112288 #endif
112292 ** Change the value of a limit. Report the old value.
112293 ** If an invalid limit index is supplied, report -1.
112294 ** Make no changes but still report the old value if the
112295 ** new limit is negative.
112297 ** A new lower limit does not shrink existing constructs.
112298 ** It merely prevents new constructs that exceed the limit
112299 ** from forming.
112301 SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
112302 int oldLimit;
112305 /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
112306 ** there is a hard upper bound set at compile-time by a C preprocessor
112307 ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
112308 ** "_MAX_".)
112310 assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
112311 assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
112312 assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
112313 assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
112314 assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
112315 assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
112316 assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
112317 assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
112318 assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
112319 SQLITE_MAX_LIKE_PATTERN_LENGTH );
112320 assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
112321 assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
112322 assert( SQLITE_LIMIT_TRIGGER_DEPTH==(SQLITE_N_LIMIT-1) );
112325 if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
112326 return -1;
112328 oldLimit = db->aLimit[limitId];
112329 if( newLimit>=0 ){ /* IMP: R-52476-28732 */
112330 if( newLimit>aHardLimit[limitId] ){
112331 newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */
112333 db->aLimit[limitId] = newLimit;
112335 return oldLimit; /* IMP: R-53341-35419 */
112339 ** This function is used to parse both URIs and non-URI filenames passed by the
112340 ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
112341 ** URIs specified as part of ATTACH statements.
112343 ** The first argument to this function is the name of the VFS to use (or
112344 ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
112345 ** query parameter. The second argument contains the URI (or non-URI filename)
112346 ** itself. When this function is called the *pFlags variable should contain
112347 ** the default flags to open the database handle with. The value stored in
112348 ** *pFlags may be updated before returning if the URI filename contains
112349 ** "cache=xxx" or "mode=xxx" query parameters.
112351 ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
112352 ** the VFS that should be used to open the database file. *pzFile is set to
112353 ** point to a buffer containing the name of the file to open. It is the
112354 ** responsibility of the caller to eventually call sqlite3_free() to release
112355 ** this buffer.
112357 ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
112358 ** may be set to point to a buffer containing an English language error
112359 ** message. It is the responsibility of the caller to eventually release
112360 ** this buffer by calling sqlite3_free().
112362 SQLITE_PRIVATE int sqlite3ParseUri(
112363 const char *zDefaultVfs, /* VFS to use if no "vfs=xxx" query option */
112364 const char *zUri, /* Nul-terminated URI to parse */
112365 unsigned int *pFlags, /* IN/OUT: SQLITE_OPEN_XXX flags */
112366 sqlite3_vfs **ppVfs, /* OUT: VFS to use */
112367 char **pzFile, /* OUT: Filename component of URI */
112368 char **pzErrMsg /* OUT: Error message (if rc!=SQLITE_OK) */
112370 int rc = SQLITE_OK;
112371 unsigned int flags = *pFlags;
112372 const char *zVfs = zDefaultVfs;
112373 char *zFile;
112374 char c;
112375 int nUri = sqlite3Strlen30(zUri);
112377 assert( *pzErrMsg==0 );
112379 if( ((flags & SQLITE_OPEN_URI) || sqlite3GlobalConfig.bOpenUri)
112380 && nUri>=5 && memcmp(zUri, "file:", 5)==0
112382 char *zOpt;
112383 int eState; /* Parser state when parsing URI */
112384 int iIn; /* Input character index */
112385 int iOut = 0; /* Output character index */
112386 int nByte = nUri+2; /* Bytes of space to allocate */
112388 /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
112389 ** method that there may be extra parameters following the file-name. */
112390 flags |= SQLITE_OPEN_URI;
112392 for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
112393 zFile = sqlite3_malloc(nByte);
112394 if( !zFile ) return SQLITE_NOMEM;
112396 /* Discard the scheme and authority segments of the URI. */
112397 if( zUri[5]=='/' && zUri[6]=='/' ){
112398 iIn = 7;
112399 while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
112401 if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
112402 *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
112403 iIn-7, &zUri[7]);
112404 rc = SQLITE_ERROR;
112405 goto parse_uri_out;
112407 }else{
112408 iIn = 5;
112411 /* Copy the filename and any query parameters into the zFile buffer.
112412 ** Decode %HH escape codes along the way.
112414 ** Within this loop, variable eState may be set to 0, 1 or 2, depending
112415 ** on the parsing context. As follows:
112417 ** 0: Parsing file-name.
112418 ** 1: Parsing name section of a name=value query parameter.
112419 ** 2: Parsing value section of a name=value query parameter.
112421 eState = 0;
112422 while( (c = zUri[iIn])!=0 && c!='#' ){
112423 iIn++;
112424 if( c=='%'
112425 && sqlite3Isxdigit(zUri[iIn])
112426 && sqlite3Isxdigit(zUri[iIn+1])
112428 int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
112429 octet += sqlite3HexToInt(zUri[iIn++]);
112431 assert( octet>=0 && octet<256 );
112432 if( octet==0 ){
112433 /* This branch is taken when "%00" appears within the URI. In this
112434 ** case we ignore all text in the remainder of the path, name or
112435 ** value currently being parsed. So ignore the current character
112436 ** and skip to the next "?", "=" or "&", as appropriate. */
112437 while( (c = zUri[iIn])!=0 && c!='#'
112438 && (eState!=0 || c!='?')
112439 && (eState!=1 || (c!='=' && c!='&'))
112440 && (eState!=2 || c!='&')
112442 iIn++;
112444 continue;
112446 c = octet;
112447 }else if( eState==1 && (c=='&' || c=='=') ){
112448 if( zFile[iOut-1]==0 ){
112449 /* An empty option name. Ignore this option altogether. */
112450 while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
112451 continue;
112453 if( c=='&' ){
112454 zFile[iOut++] = '\0';
112455 }else{
112456 eState = 2;
112458 c = 0;
112459 }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
112460 c = 0;
112461 eState = 1;
112463 zFile[iOut++] = c;
112465 if( eState==1 ) zFile[iOut++] = '\0';
112466 zFile[iOut++] = '\0';
112467 zFile[iOut++] = '\0';
112469 /* Check if there were any options specified that should be interpreted
112470 ** here. Options that are interpreted here include "vfs" and those that
112471 ** correspond to flags that may be passed to the sqlite3_open_v2()
112472 ** method. */
112473 zOpt = &zFile[sqlite3Strlen30(zFile)+1];
112474 while( zOpt[0] ){
112475 int nOpt = sqlite3Strlen30(zOpt);
112476 char *zVal = &zOpt[nOpt+1];
112477 int nVal = sqlite3Strlen30(zVal);
112479 if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
112480 zVfs = zVal;
112481 }else{
112482 struct OpenMode {
112483 const char *z;
112484 int mode;
112485 } *aMode = 0;
112486 char *zModeType = 0;
112487 int mask = 0;
112488 int limit = 0;
112490 if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
112491 static struct OpenMode aCacheMode[] = {
112492 { "shared", SQLITE_OPEN_SHAREDCACHE },
112493 { "private", SQLITE_OPEN_PRIVATECACHE },
112494 { 0, 0 }
112497 mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
112498 aMode = aCacheMode;
112499 limit = mask;
112500 zModeType = "cache";
112502 if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
112503 static struct OpenMode aOpenMode[] = {
112504 { "ro", SQLITE_OPEN_READONLY },
112505 { "rw", SQLITE_OPEN_READWRITE },
112506 { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
112507 { 0, 0 }
112510 mask = SQLITE_OPEN_READONLY|SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
112511 aMode = aOpenMode;
112512 limit = mask & flags;
112513 zModeType = "access";
112516 if( aMode ){
112517 int i;
112518 int mode = 0;
112519 for(i=0; aMode[i].z; i++){
112520 const char *z = aMode[i].z;
112521 if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
112522 mode = aMode[i].mode;
112523 break;
112526 if( mode==0 ){
112527 *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
112528 rc = SQLITE_ERROR;
112529 goto parse_uri_out;
112531 if( mode>limit ){
112532 *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
112533 zModeType, zVal);
112534 rc = SQLITE_PERM;
112535 goto parse_uri_out;
112537 flags = (flags & ~mask) | mode;
112541 zOpt = &zVal[nVal+1];
112544 }else{
112545 zFile = sqlite3_malloc(nUri+2);
112546 if( !zFile ) return SQLITE_NOMEM;
112547 memcpy(zFile, zUri, nUri);
112548 zFile[nUri] = '\0';
112549 zFile[nUri+1] = '\0';
112552 *ppVfs = sqlite3_vfs_find(zVfs);
112553 if( *ppVfs==0 ){
112554 *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
112555 rc = SQLITE_ERROR;
112557 parse_uri_out:
112558 if( rc!=SQLITE_OK ){
112559 sqlite3_free(zFile);
112560 zFile = 0;
112562 *pFlags = flags;
112563 *pzFile = zFile;
112564 return rc;
112569 ** This routine does the work of opening a database on behalf of
112570 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
112571 ** is UTF-8 encoded.
112573 static int openDatabase(
112574 const char *zFilename, /* Database filename UTF-8 encoded */
112575 sqlite3 **ppDb, /* OUT: Returned database handle */
112576 unsigned int flags, /* Operational flags */
112577 const char *zVfs /* Name of the VFS to use */
112579 sqlite3 *db; /* Store allocated handle here */
112580 int rc; /* Return code */
112581 int isThreadsafe; /* True for threadsafe connections */
112582 char *zOpen = 0; /* Filename argument to pass to BtreeOpen() */
112583 char *zErrMsg = 0; /* Error message from sqlite3ParseUri() */
112585 *ppDb = 0;
112586 #ifndef SQLITE_OMIT_AUTOINIT
112587 rc = sqlite3_initialize();
112588 if( rc ) return rc;
112589 #endif
112591 /* Only allow sensible combinations of bits in the flags argument.
112592 ** Throw an error if any non-sense combination is used. If we
112593 ** do not block illegal combinations here, it could trigger
112594 ** assert() statements in deeper layers. Sensible combinations
112595 ** are:
112597 ** 1: SQLITE_OPEN_READONLY
112598 ** 2: SQLITE_OPEN_READWRITE
112599 ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
112601 assert( SQLITE_OPEN_READONLY == 0x01 );
112602 assert( SQLITE_OPEN_READWRITE == 0x02 );
112603 assert( SQLITE_OPEN_CREATE == 0x04 );
112604 testcase( (1<<(flags&7))==0x02 ); /* READONLY */
112605 testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
112606 testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
112607 if( ((1<<(flags&7)) & 0x46)==0 ) return SQLITE_MISUSE_BKPT;
112609 if( sqlite3GlobalConfig.bCoreMutex==0 ){
112610 isThreadsafe = 0;
112611 }else if( flags & SQLITE_OPEN_NOMUTEX ){
112612 isThreadsafe = 0;
112613 }else if( flags & SQLITE_OPEN_FULLMUTEX ){
112614 isThreadsafe = 1;
112615 }else{
112616 isThreadsafe = sqlite3GlobalConfig.bFullMutex;
112618 if( flags & SQLITE_OPEN_PRIVATECACHE ){
112619 flags &= ~SQLITE_OPEN_SHAREDCACHE;
112620 }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
112621 flags |= SQLITE_OPEN_SHAREDCACHE;
112624 /* Remove harmful bits from the flags parameter
112626 ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
112627 ** dealt with in the previous code block. Besides these, the only
112628 ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
112629 ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
112630 ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits. Silently mask
112631 ** off all other flags.
112633 flags &= ~( SQLITE_OPEN_DELETEONCLOSE |
112634 SQLITE_OPEN_EXCLUSIVE |
112635 SQLITE_OPEN_MAIN_DB |
112636 SQLITE_OPEN_TEMP_DB |
112637 SQLITE_OPEN_TRANSIENT_DB |
112638 SQLITE_OPEN_MAIN_JOURNAL |
112639 SQLITE_OPEN_TEMP_JOURNAL |
112640 SQLITE_OPEN_SUBJOURNAL |
112641 SQLITE_OPEN_MASTER_JOURNAL |
112642 SQLITE_OPEN_NOMUTEX |
112643 SQLITE_OPEN_FULLMUTEX |
112644 SQLITE_OPEN_WAL
112647 /* Allocate the sqlite data structure */
112648 db = sqlite3MallocZero( sizeof(sqlite3) );
112649 if( db==0 ) goto opendb_out;
112650 if( isThreadsafe ){
112651 db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
112652 if( db->mutex==0 ){
112653 sqlite3_free(db);
112654 db = 0;
112655 goto opendb_out;
112658 sqlite3_mutex_enter(db->mutex);
112659 db->errMask = 0xff;
112660 db->nDb = 2;
112661 db->magic = SQLITE_MAGIC_BUSY;
112662 db->aDb = db->aDbStatic;
112664 assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
112665 memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
112666 db->autoCommit = 1;
112667 db->nextAutovac = -1;
112668 db->nextPagesize = 0;
112669 db->flags |= SQLITE_ShortColNames | SQLITE_AutoIndex | SQLITE_EnableTrigger
112670 #if SQLITE_DEFAULT_FILE_FORMAT<4
112671 | SQLITE_LegacyFileFmt
112672 #endif
112673 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
112674 | SQLITE_LoadExtension
112675 #endif
112676 #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
112677 | SQLITE_RecTriggers
112678 #endif
112679 #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
112680 | SQLITE_ForeignKeys
112681 #endif
112683 sqlite3HashInit(&db->aCollSeq);
112684 #ifndef SQLITE_OMIT_VIRTUALTABLE
112685 sqlite3HashInit(&db->aModule);
112686 #endif
112688 /* Add the default collation sequence BINARY. BINARY works for both UTF-8
112689 ** and UTF-16, so add a version for each to avoid any unnecessary
112690 ** conversions. The only error that can occur here is a malloc() failure.
112692 createCollation(db, "BINARY", SQLITE_UTF8, SQLITE_COLL_BINARY, 0,
112693 binCollFunc, 0);
112694 createCollation(db, "BINARY", SQLITE_UTF16BE, SQLITE_COLL_BINARY, 0,
112695 binCollFunc, 0);
112696 createCollation(db, "BINARY", SQLITE_UTF16LE, SQLITE_COLL_BINARY, 0,
112697 binCollFunc, 0);
112698 createCollation(db, "RTRIM", SQLITE_UTF8, SQLITE_COLL_USER, (void*)1,
112699 binCollFunc, 0);
112700 if( db->mallocFailed ){
112701 goto opendb_out;
112703 db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
112704 assert( db->pDfltColl!=0 );
112706 /* Also add a UTF-8 case-insensitive collation sequence. */
112707 createCollation(db, "NOCASE", SQLITE_UTF8, SQLITE_COLL_NOCASE, 0,
112708 nocaseCollatingFunc, 0);
112710 /* Parse the filename/URI argument. */
112711 db->openFlags = flags;
112712 rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
112713 if( rc!=SQLITE_OK ){
112714 if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
112715 sqlite3Error(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
112716 sqlite3_free(zErrMsg);
112717 goto opendb_out;
112720 /* Open the backend database driver */
112721 rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
112722 flags | SQLITE_OPEN_MAIN_DB);
112723 if( rc!=SQLITE_OK ){
112724 if( rc==SQLITE_IOERR_NOMEM ){
112725 rc = SQLITE_NOMEM;
112727 sqlite3Error(db, rc, 0);
112728 goto opendb_out;
112730 db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
112731 db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
112734 /* The default safety_level for the main database is 'full'; for the temp
112735 ** database it is 'NONE'. This matches the pager layer defaults.
112737 db->aDb[0].zName = "main";
112738 db->aDb[0].safety_level = 3;
112739 db->aDb[1].zName = "temp";
112740 db->aDb[1].safety_level = 1;
112742 db->magic = SQLITE_MAGIC_OPEN;
112743 if( db->mallocFailed ){
112744 goto opendb_out;
112747 /* Register all built-in functions, but do not attempt to read the
112748 ** database schema yet. This is delayed until the first time the database
112749 ** is accessed.
112751 sqlite3Error(db, SQLITE_OK, 0);
112752 sqlite3RegisterBuiltinFunctions(db);
112754 /* Load automatic extensions - extensions that have been registered
112755 ** using the sqlite3_automatic_extension() API.
112757 sqlite3AutoLoadExtensions(db);
112758 rc = sqlite3_errcode(db);
112759 if( rc!=SQLITE_OK ){
112760 goto opendb_out;
112763 #ifdef SQLITE_ENABLE_FTS1
112764 if( !db->mallocFailed ){
112765 extern int sqlite3Fts1Init(sqlite3*);
112766 rc = sqlite3Fts1Init(db);
112768 #endif
112770 #ifdef SQLITE_ENABLE_FTS2
112771 if( !db->mallocFailed && rc==SQLITE_OK ){
112772 extern int sqlite3Fts2Init(sqlite3*);
112773 rc = sqlite3Fts2Init(db);
112775 #endif
112777 #ifdef SQLITE_ENABLE_FTS3
112778 if( !db->mallocFailed && rc==SQLITE_OK ){
112779 rc = sqlite3Fts3Init(db);
112781 #endif
112783 #ifdef SQLITE_ENABLE_ICU
112784 if( !db->mallocFailed && rc==SQLITE_OK ){
112785 rc = sqlite3IcuInit(db);
112787 #endif
112789 #ifdef SQLITE_ENABLE_RTREE
112790 if( !db->mallocFailed && rc==SQLITE_OK){
112791 rc = sqlite3RtreeInit(db);
112793 #endif
112795 sqlite3Error(db, rc, 0);
112797 /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
112798 ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
112799 ** mode. Doing nothing at all also makes NORMAL the default.
112801 #ifdef SQLITE_DEFAULT_LOCKING_MODE
112802 db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
112803 sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
112804 SQLITE_DEFAULT_LOCKING_MODE);
112805 #endif
112807 /* Enable the lookaside-malloc subsystem */
112808 setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
112809 sqlite3GlobalConfig.nLookaside);
112811 sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
112813 opendb_out:
112814 sqlite3_free(zOpen);
112815 if( db ){
112816 assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
112817 sqlite3_mutex_leave(db->mutex);
112819 rc = sqlite3_errcode(db);
112820 assert( db!=0 || rc==SQLITE_NOMEM );
112821 if( rc==SQLITE_NOMEM ){
112822 sqlite3_close(db);
112823 db = 0;
112824 }else if( rc!=SQLITE_OK ){
112825 db->magic = SQLITE_MAGIC_SICK;
112827 *ppDb = db;
112828 return sqlite3ApiExit(0, rc);
112832 ** Open a new database handle.
112834 SQLITE_API int sqlite3_open(
112835 const char *zFilename,
112836 sqlite3 **ppDb
112838 return openDatabase(zFilename, ppDb,
112839 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
112841 SQLITE_API int sqlite3_open_v2(
112842 const char *filename, /* Database filename (UTF-8) */
112843 sqlite3 **ppDb, /* OUT: SQLite db handle */
112844 int flags, /* Flags */
112845 const char *zVfs /* Name of VFS module to use */
112847 return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
112850 #ifndef SQLITE_OMIT_UTF16
112852 ** Open a new database handle.
112854 SQLITE_API int sqlite3_open16(
112855 const void *zFilename,
112856 sqlite3 **ppDb
112858 char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */
112859 sqlite3_value *pVal;
112860 int rc;
112862 assert( zFilename );
112863 assert( ppDb );
112864 *ppDb = 0;
112865 #ifndef SQLITE_OMIT_AUTOINIT
112866 rc = sqlite3_initialize();
112867 if( rc ) return rc;
112868 #endif
112869 pVal = sqlite3ValueNew(0);
112870 sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
112871 zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
112872 if( zFilename8 ){
112873 rc = openDatabase(zFilename8, ppDb,
112874 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
112875 assert( *ppDb || rc==SQLITE_NOMEM );
112876 if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
112877 ENC(*ppDb) = SQLITE_UTF16NATIVE;
112879 }else{
112880 rc = SQLITE_NOMEM;
112882 sqlite3ValueFree(pVal);
112884 return sqlite3ApiExit(0, rc);
112886 #endif /* SQLITE_OMIT_UTF16 */
112889 ** Register a new collation sequence with the database handle db.
112891 SQLITE_API int sqlite3_create_collation(
112892 sqlite3* db,
112893 const char *zName,
112894 int enc,
112895 void* pCtx,
112896 int(*xCompare)(void*,int,const void*,int,const void*)
112898 int rc;
112899 sqlite3_mutex_enter(db->mutex);
112900 assert( !db->mallocFailed );
112901 rc = createCollation(db, zName, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, 0);
112902 rc = sqlite3ApiExit(db, rc);
112903 sqlite3_mutex_leave(db->mutex);
112904 return rc;
112908 ** Register a new collation sequence with the database handle db.
112910 SQLITE_API int sqlite3_create_collation_v2(
112911 sqlite3* db,
112912 const char *zName,
112913 int enc,
112914 void* pCtx,
112915 int(*xCompare)(void*,int,const void*,int,const void*),
112916 void(*xDel)(void*)
112918 int rc;
112919 sqlite3_mutex_enter(db->mutex);
112920 assert( !db->mallocFailed );
112921 rc = createCollation(db, zName, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, xDel);
112922 rc = sqlite3ApiExit(db, rc);
112923 sqlite3_mutex_leave(db->mutex);
112924 return rc;
112927 #ifndef SQLITE_OMIT_UTF16
112929 ** Register a new collation sequence with the database handle db.
112931 SQLITE_API int sqlite3_create_collation16(
112932 sqlite3* db,
112933 const void *zName,
112934 int enc,
112935 void* pCtx,
112936 int(*xCompare)(void*,int,const void*,int,const void*)
112938 int rc = SQLITE_OK;
112939 char *zName8;
112940 sqlite3_mutex_enter(db->mutex);
112941 assert( !db->mallocFailed );
112942 zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
112943 if( zName8 ){
112944 rc = createCollation(db, zName8, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, 0);
112945 sqlite3DbFree(db, zName8);
112947 rc = sqlite3ApiExit(db, rc);
112948 sqlite3_mutex_leave(db->mutex);
112949 return rc;
112951 #endif /* SQLITE_OMIT_UTF16 */
112954 ** Register a collation sequence factory callback with the database handle
112955 ** db. Replace any previously installed collation sequence factory.
112957 SQLITE_API int sqlite3_collation_needed(
112958 sqlite3 *db,
112959 void *pCollNeededArg,
112960 void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
112962 sqlite3_mutex_enter(db->mutex);
112963 db->xCollNeeded = xCollNeeded;
112964 db->xCollNeeded16 = 0;
112965 db->pCollNeededArg = pCollNeededArg;
112966 sqlite3_mutex_leave(db->mutex);
112967 return SQLITE_OK;
112970 #ifndef SQLITE_OMIT_UTF16
112972 ** Register a collation sequence factory callback with the database handle
112973 ** db. Replace any previously installed collation sequence factory.
112975 SQLITE_API int sqlite3_collation_needed16(
112976 sqlite3 *db,
112977 void *pCollNeededArg,
112978 void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
112980 sqlite3_mutex_enter(db->mutex);
112981 db->xCollNeeded = 0;
112982 db->xCollNeeded16 = xCollNeeded16;
112983 db->pCollNeededArg = pCollNeededArg;
112984 sqlite3_mutex_leave(db->mutex);
112985 return SQLITE_OK;
112987 #endif /* SQLITE_OMIT_UTF16 */
112989 #ifndef SQLITE_OMIT_DEPRECATED
112991 ** This function is now an anachronism. It used to be used to recover from a
112992 ** malloc() failure, but SQLite now does this automatically.
112994 SQLITE_API int sqlite3_global_recover(void){
112995 return SQLITE_OK;
112997 #endif
113000 ** Test to see whether or not the database connection is in autocommit
113001 ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
113002 ** by default. Autocommit is disabled by a BEGIN statement and reenabled
113003 ** by the next COMMIT or ROLLBACK.
113005 ******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
113007 SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
113008 return db->autoCommit;
113012 ** The following routines are subtitutes for constants SQLITE_CORRUPT,
113013 ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
113014 ** constants. They server two purposes:
113016 ** 1. Serve as a convenient place to set a breakpoint in a debugger
113017 ** to detect when version error conditions occurs.
113019 ** 2. Invoke sqlite3_log() to provide the source code location where
113020 ** a low-level error is first detected.
113022 SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
113023 testcase( sqlite3GlobalConfig.xLog!=0 );
113024 sqlite3_log(SQLITE_CORRUPT,
113025 "database corruption at line %d of [%.10s]",
113026 lineno, 20+sqlite3_sourceid());
113027 return SQLITE_CORRUPT;
113029 SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
113030 testcase( sqlite3GlobalConfig.xLog!=0 );
113031 sqlite3_log(SQLITE_MISUSE,
113032 "misuse at line %d of [%.10s]",
113033 lineno, 20+sqlite3_sourceid());
113034 return SQLITE_MISUSE;
113036 SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
113037 testcase( sqlite3GlobalConfig.xLog!=0 );
113038 sqlite3_log(SQLITE_CANTOPEN,
113039 "cannot open file at line %d of [%.10s]",
113040 lineno, 20+sqlite3_sourceid());
113041 return SQLITE_CANTOPEN;
113045 #ifndef SQLITE_OMIT_DEPRECATED
113047 ** This is a convenience routine that makes sure that all thread-specific
113048 ** data for this thread has been deallocated.
113050 ** SQLite no longer uses thread-specific data so this routine is now a
113051 ** no-op. It is retained for historical compatibility.
113053 SQLITE_API void sqlite3_thread_cleanup(void){
113055 #endif
113058 ** Return meta information about a specific column of a database table.
113059 ** See comment in sqlite3.h (sqlite.h.in) for details.
113061 #ifdef SQLITE_ENABLE_COLUMN_METADATA
113062 SQLITE_API int sqlite3_table_column_metadata(
113063 sqlite3 *db, /* Connection handle */
113064 const char *zDbName, /* Database name or NULL */
113065 const char *zTableName, /* Table name */
113066 const char *zColumnName, /* Column name */
113067 char const **pzDataType, /* OUTPUT: Declared data type */
113068 char const **pzCollSeq, /* OUTPUT: Collation sequence name */
113069 int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
113070 int *pPrimaryKey, /* OUTPUT: True if column part of PK */
113071 int *pAutoinc /* OUTPUT: True if column is auto-increment */
113073 int rc;
113074 char *zErrMsg = 0;
113075 Table *pTab = 0;
113076 Column *pCol = 0;
113077 int iCol;
113079 char const *zDataType = 0;
113080 char const *zCollSeq = 0;
113081 int notnull = 0;
113082 int primarykey = 0;
113083 int autoinc = 0;
113085 /* Ensure the database schema has been loaded */
113086 sqlite3_mutex_enter(db->mutex);
113087 sqlite3BtreeEnterAll(db);
113088 rc = sqlite3Init(db, &zErrMsg);
113089 if( SQLITE_OK!=rc ){
113090 goto error_out;
113093 /* Locate the table in question */
113094 pTab = sqlite3FindTable(db, zTableName, zDbName);
113095 if( !pTab || pTab->pSelect ){
113096 pTab = 0;
113097 goto error_out;
113100 /* Find the column for which info is requested */
113101 if( sqlite3IsRowid(zColumnName) ){
113102 iCol = pTab->iPKey;
113103 if( iCol>=0 ){
113104 pCol = &pTab->aCol[iCol];
113106 }else{
113107 for(iCol=0; iCol<pTab->nCol; iCol++){
113108 pCol = &pTab->aCol[iCol];
113109 if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
113110 break;
113113 if( iCol==pTab->nCol ){
113114 pTab = 0;
113115 goto error_out;
113119 /* The following block stores the meta information that will be returned
113120 ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
113121 ** and autoinc. At this point there are two possibilities:
113123 ** 1. The specified column name was rowid", "oid" or "_rowid_"
113124 ** and there is no explicitly declared IPK column.
113126 ** 2. The table is not a view and the column name identified an
113127 ** explicitly declared column. Copy meta information from *pCol.
113129 if( pCol ){
113130 zDataType = pCol->zType;
113131 zCollSeq = pCol->zColl;
113132 notnull = pCol->notNull!=0;
113133 primarykey = pCol->isPrimKey!=0;
113134 autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
113135 }else{
113136 zDataType = "INTEGER";
113137 primarykey = 1;
113139 if( !zCollSeq ){
113140 zCollSeq = "BINARY";
113143 error_out:
113144 sqlite3BtreeLeaveAll(db);
113146 /* Whether the function call succeeded or failed, set the output parameters
113147 ** to whatever their local counterparts contain. If an error did occur,
113148 ** this has the effect of zeroing all output parameters.
113150 if( pzDataType ) *pzDataType = zDataType;
113151 if( pzCollSeq ) *pzCollSeq = zCollSeq;
113152 if( pNotNull ) *pNotNull = notnull;
113153 if( pPrimaryKey ) *pPrimaryKey = primarykey;
113154 if( pAutoinc ) *pAutoinc = autoinc;
113156 if( SQLITE_OK==rc && !pTab ){
113157 sqlite3DbFree(db, zErrMsg);
113158 zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
113159 zColumnName);
113160 rc = SQLITE_ERROR;
113162 sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
113163 sqlite3DbFree(db, zErrMsg);
113164 rc = sqlite3ApiExit(db, rc);
113165 sqlite3_mutex_leave(db->mutex);
113166 return rc;
113168 #endif
113171 ** Sleep for a little while. Return the amount of time slept.
113173 SQLITE_API int sqlite3_sleep(int ms){
113174 sqlite3_vfs *pVfs;
113175 int rc;
113176 pVfs = sqlite3_vfs_find(0);
113177 if( pVfs==0 ) return 0;
113179 /* This function works in milliseconds, but the underlying OsSleep()
113180 ** API uses microseconds. Hence the 1000's.
113182 rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
113183 return rc;
113187 ** Enable or disable the extended result codes.
113189 SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
113190 sqlite3_mutex_enter(db->mutex);
113191 db->errMask = onoff ? 0xffffffff : 0xff;
113192 sqlite3_mutex_leave(db->mutex);
113193 return SQLITE_OK;
113197 ** Invoke the xFileControl method on a particular database.
113199 SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
113200 int rc = SQLITE_ERROR;
113201 int iDb;
113202 sqlite3_mutex_enter(db->mutex);
113203 if( zDbName==0 ){
113204 iDb = 0;
113205 }else{
113206 for(iDb=0; iDb<db->nDb; iDb++){
113207 if( strcmp(db->aDb[iDb].zName, zDbName)==0 ) break;
113210 if( iDb<db->nDb ){
113211 Btree *pBtree = db->aDb[iDb].pBt;
113212 if( pBtree ){
113213 Pager *pPager;
113214 sqlite3_file *fd;
113215 sqlite3BtreeEnter(pBtree);
113216 pPager = sqlite3BtreePager(pBtree);
113217 assert( pPager!=0 );
113218 fd = sqlite3PagerFile(pPager);
113219 assert( fd!=0 );
113220 if( op==SQLITE_FCNTL_FILE_POINTER ){
113221 *(sqlite3_file**)pArg = fd;
113222 rc = SQLITE_OK;
113223 }else if( fd->pMethods ){
113224 rc = sqlite3OsFileControl(fd, op, pArg);
113225 }else{
113226 rc = SQLITE_NOTFOUND;
113228 sqlite3BtreeLeave(pBtree);
113231 sqlite3_mutex_leave(db->mutex);
113232 return rc;
113236 ** Interface to the testing logic.
113238 SQLITE_API int sqlite3_test_control(int op, ...){
113239 int rc = 0;
113240 #ifndef SQLITE_OMIT_BUILTIN_TEST
113241 va_list ap;
113242 va_start(ap, op);
113243 switch( op ){
113246 ** Save the current state of the PRNG.
113248 case SQLITE_TESTCTRL_PRNG_SAVE: {
113249 sqlite3PrngSaveState();
113250 break;
113254 ** Restore the state of the PRNG to the last state saved using
113255 ** PRNG_SAVE. If PRNG_SAVE has never before been called, then
113256 ** this verb acts like PRNG_RESET.
113258 case SQLITE_TESTCTRL_PRNG_RESTORE: {
113259 sqlite3PrngRestoreState();
113260 break;
113264 ** Reset the PRNG back to its uninitialized state. The next call
113265 ** to sqlite3_randomness() will reseed the PRNG using a single call
113266 ** to the xRandomness method of the default VFS.
113268 case SQLITE_TESTCTRL_PRNG_RESET: {
113269 sqlite3PrngResetState();
113270 break;
113274 ** sqlite3_test_control(BITVEC_TEST, size, program)
113276 ** Run a test against a Bitvec object of size. The program argument
113277 ** is an array of integers that defines the test. Return -1 on a
113278 ** memory allocation error, 0 on success, or non-zero for an error.
113279 ** See the sqlite3BitvecBuiltinTest() for additional information.
113281 case SQLITE_TESTCTRL_BITVEC_TEST: {
113282 int sz = va_arg(ap, int);
113283 int *aProg = va_arg(ap, int*);
113284 rc = sqlite3BitvecBuiltinTest(sz, aProg);
113285 break;
113289 ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
113291 ** Register hooks to call to indicate which malloc() failures
113292 ** are benign.
113294 case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
113295 typedef void (*void_function)(void);
113296 void_function xBenignBegin;
113297 void_function xBenignEnd;
113298 xBenignBegin = va_arg(ap, void_function);
113299 xBenignEnd = va_arg(ap, void_function);
113300 sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
113301 break;
113305 ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
113307 ** Set the PENDING byte to the value in the argument, if X>0.
113308 ** Make no changes if X==0. Return the value of the pending byte
113309 ** as it existing before this routine was called.
113311 ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in
113312 ** an incompatible database file format. Changing the PENDING byte
113313 ** while any database connection is open results in undefined and
113314 ** dileterious behavior.
113316 case SQLITE_TESTCTRL_PENDING_BYTE: {
113317 rc = PENDING_BYTE;
113318 #ifndef SQLITE_OMIT_WSD
113320 unsigned int newVal = va_arg(ap, unsigned int);
113321 if( newVal ) sqlite3PendingByte = newVal;
113323 #endif
113324 break;
113328 ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
113330 ** This action provides a run-time test to see whether or not
113331 ** assert() was enabled at compile-time. If X is true and assert()
113332 ** is enabled, then the return value is true. If X is true and
113333 ** assert() is disabled, then the return value is zero. If X is
113334 ** false and assert() is enabled, then the assertion fires and the
113335 ** process aborts. If X is false and assert() is disabled, then the
113336 ** return value is zero.
113338 case SQLITE_TESTCTRL_ASSERT: {
113339 volatile int x = 0;
113340 assert( (x = va_arg(ap,int))!=0 );
113341 rc = x;
113342 break;
113347 ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
113349 ** This action provides a run-time test to see how the ALWAYS and
113350 ** NEVER macros were defined at compile-time.
113352 ** The return value is ALWAYS(X).
113354 ** The recommended test is X==2. If the return value is 2, that means
113355 ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
113356 ** default setting. If the return value is 1, then ALWAYS() is either
113357 ** hard-coded to true or else it asserts if its argument is false.
113358 ** The first behavior (hard-coded to true) is the case if
113359 ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
113360 ** behavior (assert if the argument to ALWAYS() is false) is the case if
113361 ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
113363 ** The run-time test procedure might look something like this:
113365 ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
113366 ** // ALWAYS() and NEVER() are no-op pass-through macros
113367 ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
113368 ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
113369 ** }else{
113370 ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0.
113373 case SQLITE_TESTCTRL_ALWAYS: {
113374 int x = va_arg(ap,int);
113375 rc = ALWAYS(x);
113376 break;
113379 /* sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
113381 ** Set the nReserve size to N for the main database on the database
113382 ** connection db.
113384 case SQLITE_TESTCTRL_RESERVE: {
113385 sqlite3 *db = va_arg(ap, sqlite3*);
113386 int x = va_arg(ap,int);
113387 sqlite3_mutex_enter(db->mutex);
113388 sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
113389 sqlite3_mutex_leave(db->mutex);
113390 break;
113393 /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
113395 ** Enable or disable various optimizations for testing purposes. The
113396 ** argument N is a bitmask of optimizations to be disabled. For normal
113397 ** operation N should be 0. The idea is that a test program (like the
113398 ** SQL Logic Test or SLT test module) can run the same SQL multiple times
113399 ** with various optimizations disabled to verify that the same answer
113400 ** is obtained in every case.
113402 case SQLITE_TESTCTRL_OPTIMIZATIONS: {
113403 sqlite3 *db = va_arg(ap, sqlite3*);
113404 int x = va_arg(ap,int);
113405 db->flags = (x & SQLITE_OptMask) | (db->flags & ~SQLITE_OptMask);
113406 break;
113409 #ifdef SQLITE_N_KEYWORD
113410 /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
113412 ** If zWord is a keyword recognized by the parser, then return the
113413 ** number of keywords. Or if zWord is not a keyword, return 0.
113415 ** This test feature is only available in the amalgamation since
113416 ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
113417 ** is built using separate source files.
113419 case SQLITE_TESTCTRL_ISKEYWORD: {
113420 const char *zWord = va_arg(ap, const char*);
113421 int n = sqlite3Strlen30(zWord);
113422 rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
113423 break;
113425 #endif
113427 /* sqlite3_test_control(SQLITE_TESTCTRL_PGHDRSZ)
113429 ** Return the size of a pcache header in bytes.
113431 case SQLITE_TESTCTRL_PGHDRSZ: {
113432 rc = sizeof(PgHdr);
113433 break;
113436 /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
113438 ** Pass pFree into sqlite3ScratchFree().
113439 ** If sz>0 then allocate a scratch buffer into pNew.
113441 case SQLITE_TESTCTRL_SCRATCHMALLOC: {
113442 void *pFree, **ppNew;
113443 int sz;
113444 sz = va_arg(ap, int);
113445 ppNew = va_arg(ap, void**);
113446 pFree = va_arg(ap, void*);
113447 if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
113448 sqlite3ScratchFree(pFree);
113449 break;
113452 /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
113454 ** If parameter onoff is non-zero, configure the wrappers so that all
113455 ** subsequent calls to localtime() and variants fail. If onoff is zero,
113456 ** undo this setting.
113458 case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
113459 sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
113460 break;
113464 va_end(ap);
113465 #endif /* SQLITE_OMIT_BUILTIN_TEST */
113466 return rc;
113470 ** This is a utility routine, useful to VFS implementations, that checks
113471 ** to see if a database file was a URI that contained a specific query
113472 ** parameter, and if so obtains the value of the query parameter.
113474 ** The zFilename argument is the filename pointer passed into the xOpen()
113475 ** method of a VFS implementation. The zParam argument is the name of the
113476 ** query parameter we seek. This routine returns the value of the zParam
113477 ** parameter if it exists. If the parameter does not exist, this routine
113478 ** returns a NULL pointer.
113480 SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
113481 zFilename += sqlite3Strlen30(zFilename) + 1;
113482 while( zFilename[0] ){
113483 int x = strcmp(zFilename, zParam);
113484 zFilename += sqlite3Strlen30(zFilename) + 1;
113485 if( x==0 ) return zFilename;
113486 zFilename += sqlite3Strlen30(zFilename) + 1;
113488 return 0;
113491 /************** End of main.c ************************************************/
113492 /************** Begin file notify.c ******************************************/
113494 ** 2009 March 3
113496 ** The author disclaims copyright to this source code. In place of
113497 ** a legal notice, here is a blessing:
113499 ** May you do good and not evil.
113500 ** May you find forgiveness for yourself and forgive others.
113501 ** May you share freely, never taking more than you give.
113503 *************************************************************************
113505 ** This file contains the implementation of the sqlite3_unlock_notify()
113506 ** API method and its associated functionality.
113509 /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
113510 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
113513 ** Public interfaces:
113515 ** sqlite3ConnectionBlocked()
113516 ** sqlite3ConnectionUnlocked()
113517 ** sqlite3ConnectionClosed()
113518 ** sqlite3_unlock_notify()
113521 #define assertMutexHeld() \
113522 assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
113525 ** Head of a linked list of all sqlite3 objects created by this process
113526 ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
113527 ** is not NULL. This variable may only accessed while the STATIC_MASTER
113528 ** mutex is held.
113530 static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
113532 #ifndef NDEBUG
113534 ** This function is a complex assert() that verifies the following
113535 ** properties of the blocked connections list:
113537 ** 1) Each entry in the list has a non-NULL value for either
113538 ** pUnlockConnection or pBlockingConnection, or both.
113540 ** 2) All entries in the list that share a common value for
113541 ** xUnlockNotify are grouped together.
113543 ** 3) If the argument db is not NULL, then none of the entries in the
113544 ** blocked connections list have pUnlockConnection or pBlockingConnection
113545 ** set to db. This is used when closing connection db.
113547 static void checkListProperties(sqlite3 *db){
113548 sqlite3 *p;
113549 for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
113550 int seen = 0;
113551 sqlite3 *p2;
113553 /* Verify property (1) */
113554 assert( p->pUnlockConnection || p->pBlockingConnection );
113556 /* Verify property (2) */
113557 for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
113558 if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
113559 assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
113560 assert( db==0 || p->pUnlockConnection!=db );
113561 assert( db==0 || p->pBlockingConnection!=db );
113565 #else
113566 # define checkListProperties(x)
113567 #endif
113570 ** Remove connection db from the blocked connections list. If connection
113571 ** db is not currently a part of the list, this function is a no-op.
113573 static void removeFromBlockedList(sqlite3 *db){
113574 sqlite3 **pp;
113575 assertMutexHeld();
113576 for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
113577 if( *pp==db ){
113578 *pp = (*pp)->pNextBlocked;
113579 break;
113585 ** Add connection db to the blocked connections list. It is assumed
113586 ** that it is not already a part of the list.
113588 static void addToBlockedList(sqlite3 *db){
113589 sqlite3 **pp;
113590 assertMutexHeld();
113592 pp=&sqlite3BlockedList;
113593 *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
113594 pp=&(*pp)->pNextBlocked
113596 db->pNextBlocked = *pp;
113597 *pp = db;
113601 ** Obtain the STATIC_MASTER mutex.
113603 static void enterMutex(void){
113604 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
113605 checkListProperties(0);
113609 ** Release the STATIC_MASTER mutex.
113611 static void leaveMutex(void){
113612 assertMutexHeld();
113613 checkListProperties(0);
113614 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
113618 ** Register an unlock-notify callback.
113620 ** This is called after connection "db" has attempted some operation
113621 ** but has received an SQLITE_LOCKED error because another connection
113622 ** (call it pOther) in the same process was busy using the same shared
113623 ** cache. pOther is found by looking at db->pBlockingConnection.
113625 ** If there is no blocking connection, the callback is invoked immediately,
113626 ** before this routine returns.
113628 ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
113629 ** a deadlock.
113631 ** Otherwise, make arrangements to invoke xNotify when pOther drops
113632 ** its locks.
113634 ** Each call to this routine overrides any prior callbacks registered
113635 ** on the same "db". If xNotify==0 then any prior callbacks are immediately
113636 ** cancelled.
113638 SQLITE_API int sqlite3_unlock_notify(
113639 sqlite3 *db,
113640 void (*xNotify)(void **, int),
113641 void *pArg
113643 int rc = SQLITE_OK;
113645 sqlite3_mutex_enter(db->mutex);
113646 enterMutex();
113648 if( xNotify==0 ){
113649 removeFromBlockedList(db);
113650 db->pBlockingConnection = 0;
113651 db->pUnlockConnection = 0;
113652 db->xUnlockNotify = 0;
113653 db->pUnlockArg = 0;
113654 }else if( 0==db->pBlockingConnection ){
113655 /* The blocking transaction has been concluded. Or there never was a
113656 ** blocking transaction. In either case, invoke the notify callback
113657 ** immediately.
113659 xNotify(&pArg, 1);
113660 }else{
113661 sqlite3 *p;
113663 for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
113664 if( p ){
113665 rc = SQLITE_LOCKED; /* Deadlock detected. */
113666 }else{
113667 db->pUnlockConnection = db->pBlockingConnection;
113668 db->xUnlockNotify = xNotify;
113669 db->pUnlockArg = pArg;
113670 removeFromBlockedList(db);
113671 addToBlockedList(db);
113675 leaveMutex();
113676 assert( !db->mallocFailed );
113677 sqlite3Error(db, rc, (rc?"database is deadlocked":0));
113678 sqlite3_mutex_leave(db->mutex);
113679 return rc;
113683 ** This function is called while stepping or preparing a statement
113684 ** associated with connection db. The operation will return SQLITE_LOCKED
113685 ** to the user because it requires a lock that will not be available
113686 ** until connection pBlocker concludes its current transaction.
113688 SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
113689 enterMutex();
113690 if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
113691 addToBlockedList(db);
113693 db->pBlockingConnection = pBlocker;
113694 leaveMutex();
113698 ** This function is called when
113699 ** the transaction opened by database db has just finished. Locks held
113700 ** by database connection db have been released.
113702 ** This function loops through each entry in the blocked connections
113703 ** list and does the following:
113705 ** 1) If the sqlite3.pBlockingConnection member of a list entry is
113706 ** set to db, then set pBlockingConnection=0.
113708 ** 2) If the sqlite3.pUnlockConnection member of a list entry is
113709 ** set to db, then invoke the configured unlock-notify callback and
113710 ** set pUnlockConnection=0.
113712 ** 3) If the two steps above mean that pBlockingConnection==0 and
113713 ** pUnlockConnection==0, remove the entry from the blocked connections
113714 ** list.
113716 SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
113717 void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
113718 int nArg = 0; /* Number of entries in aArg[] */
113719 sqlite3 **pp; /* Iterator variable */
113720 void **aArg; /* Arguments to the unlock callback */
113721 void **aDyn = 0; /* Dynamically allocated space for aArg[] */
113722 void *aStatic[16]; /* Starter space for aArg[]. No malloc required */
113724 aArg = aStatic;
113725 enterMutex(); /* Enter STATIC_MASTER mutex */
113727 /* This loop runs once for each entry in the blocked-connections list. */
113728 for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
113729 sqlite3 *p = *pp;
113731 /* Step 1. */
113732 if( p->pBlockingConnection==db ){
113733 p->pBlockingConnection = 0;
113736 /* Step 2. */
113737 if( p->pUnlockConnection==db ){
113738 assert( p->xUnlockNotify );
113739 if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
113740 xUnlockNotify(aArg, nArg);
113741 nArg = 0;
113744 sqlite3BeginBenignMalloc();
113745 assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
113746 assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
113747 if( (!aDyn && nArg==(int)ArraySize(aStatic))
113748 || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
113750 /* The aArg[] array needs to grow. */
113751 void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
113752 if( pNew ){
113753 memcpy(pNew, aArg, nArg*sizeof(void *));
113754 sqlite3_free(aDyn);
113755 aDyn = aArg = pNew;
113756 }else{
113757 /* This occurs when the array of context pointers that need to
113758 ** be passed to the unlock-notify callback is larger than the
113759 ** aStatic[] array allocated on the stack and the attempt to
113760 ** allocate a larger array from the heap has failed.
113762 ** This is a difficult situation to handle. Returning an error
113763 ** code to the caller is insufficient, as even if an error code
113764 ** is returned the transaction on connection db will still be
113765 ** closed and the unlock-notify callbacks on blocked connections
113766 ** will go unissued. This might cause the application to wait
113767 ** indefinitely for an unlock-notify callback that will never
113768 ** arrive.
113770 ** Instead, invoke the unlock-notify callback with the context
113771 ** array already accumulated. We can then clear the array and
113772 ** begin accumulating any further context pointers without
113773 ** requiring any dynamic allocation. This is sub-optimal because
113774 ** it means that instead of one callback with a large array of
113775 ** context pointers the application will receive two or more
113776 ** callbacks with smaller arrays of context pointers, which will
113777 ** reduce the applications ability to prioritize multiple
113778 ** connections. But it is the best that can be done under the
113779 ** circumstances.
113781 xUnlockNotify(aArg, nArg);
113782 nArg = 0;
113785 sqlite3EndBenignMalloc();
113787 aArg[nArg++] = p->pUnlockArg;
113788 xUnlockNotify = p->xUnlockNotify;
113789 p->pUnlockConnection = 0;
113790 p->xUnlockNotify = 0;
113791 p->pUnlockArg = 0;
113794 /* Step 3. */
113795 if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
113796 /* Remove connection p from the blocked connections list. */
113797 *pp = p->pNextBlocked;
113798 p->pNextBlocked = 0;
113799 }else{
113800 pp = &p->pNextBlocked;
113804 if( nArg!=0 ){
113805 xUnlockNotify(aArg, nArg);
113807 sqlite3_free(aDyn);
113808 leaveMutex(); /* Leave STATIC_MASTER mutex */
113812 ** This is called when the database connection passed as an argument is
113813 ** being closed. The connection is removed from the blocked list.
113815 SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
113816 sqlite3ConnectionUnlocked(db);
113817 enterMutex();
113818 removeFromBlockedList(db);
113819 checkListProperties(db);
113820 leaveMutex();
113822 #endif
113824 /************** End of notify.c **********************************************/
113825 /************** Begin file fts3.c ********************************************/
113827 ** 2006 Oct 10
113829 ** The author disclaims copyright to this source code. In place of
113830 ** a legal notice, here is a blessing:
113832 ** May you do good and not evil.
113833 ** May you find forgiveness for yourself and forgive others.
113834 ** May you share freely, never taking more than you give.
113836 ******************************************************************************
113838 ** This is an SQLite module implementing full-text search.
113842 ** The code in this file is only compiled if:
113844 ** * The FTS3 module is being built as an extension
113845 ** (in which case SQLITE_CORE is not defined), or
113847 ** * The FTS3 module is being built into the core of
113848 ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
113851 /* The full-text index is stored in a series of b+tree (-like)
113852 ** structures called segments which map terms to doclists. The
113853 ** structures are like b+trees in layout, but are constructed from the
113854 ** bottom up in optimal fashion and are not updatable. Since trees
113855 ** are built from the bottom up, things will be described from the
113856 ** bottom up.
113859 **** Varints ****
113860 ** The basic unit of encoding is a variable-length integer called a
113861 ** varint. We encode variable-length integers in little-endian order
113862 ** using seven bits * per byte as follows:
113864 ** KEY:
113865 ** A = 0xxxxxxx 7 bits of data and one flag bit
113866 ** B = 1xxxxxxx 7 bits of data and one flag bit
113868 ** 7 bits - A
113869 ** 14 bits - BA
113870 ** 21 bits - BBA
113871 ** and so on.
113873 ** This is similar in concept to how sqlite encodes "varints" but
113874 ** the encoding is not the same. SQLite varints are big-endian
113875 ** are are limited to 9 bytes in length whereas FTS3 varints are
113876 ** little-endian and can be up to 10 bytes in length (in theory).
113878 ** Example encodings:
113880 ** 1: 0x01
113881 ** 127: 0x7f
113882 ** 128: 0x81 0x00
113885 **** Document lists ****
113886 ** A doclist (document list) holds a docid-sorted list of hits for a
113887 ** given term. Doclists hold docids and associated token positions.
113888 ** A docid is the unique integer identifier for a single document.
113889 ** A position is the index of a word within the document. The first
113890 ** word of the document has a position of 0.
113892 ** FTS3 used to optionally store character offsets using a compile-time
113893 ** option. But that functionality is no longer supported.
113895 ** A doclist is stored like this:
113897 ** array {
113898 ** varint docid;
113899 ** array { (position list for column 0)
113900 ** varint position; (2 more than the delta from previous position)
113902 ** array {
113903 ** varint POS_COLUMN; (marks start of position list for new column)
113904 ** varint column; (index of new column)
113905 ** array {
113906 ** varint position; (2 more than the delta from previous position)
113909 ** varint POS_END; (marks end of positions for this document.
113912 ** Here, array { X } means zero or more occurrences of X, adjacent in
113913 ** memory. A "position" is an index of a token in the token stream
113914 ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
113915 ** in the same logical place as the position element, and act as sentinals
113916 ** ending a position list array. POS_END is 0. POS_COLUMN is 1.
113917 ** The positions numbers are not stored literally but rather as two more
113918 ** than the difference from the prior position, or the just the position plus
113919 ** 2 for the first position. Example:
113921 ** label: A B C D E F G H I J K
113922 ** value: 123 5 9 1 1 14 35 0 234 72 0
113924 ** The 123 value is the first docid. For column zero in this document
113925 ** there are two matches at positions 3 and 10 (5-2 and 9-2+3). The 1
113926 ** at D signals the start of a new column; the 1 at E indicates that the
113927 ** new column is column number 1. There are two positions at 12 and 45
113928 ** (14-2 and 35-2+12). The 0 at H indicate the end-of-document. The
113929 ** 234 at I is the next docid. It has one position 72 (72-2) and then
113930 ** terminates with the 0 at K.
113932 ** A "position-list" is the list of positions for multiple columns for
113933 ** a single docid. A "column-list" is the set of positions for a single
113934 ** column. Hence, a position-list consists of one or more column-lists,
113935 ** a document record consists of a docid followed by a position-list and
113936 ** a doclist consists of one or more document records.
113938 ** A bare doclist omits the position information, becoming an
113939 ** array of varint-encoded docids.
113941 **** Segment leaf nodes ****
113942 ** Segment leaf nodes store terms and doclists, ordered by term. Leaf
113943 ** nodes are written using LeafWriter, and read using LeafReader (to
113944 ** iterate through a single leaf node's data) and LeavesReader (to
113945 ** iterate through a segment's entire leaf layer). Leaf nodes have
113946 ** the format:
113948 ** varint iHeight; (height from leaf level, always 0)
113949 ** varint nTerm; (length of first term)
113950 ** char pTerm[nTerm]; (content of first term)
113951 ** varint nDoclist; (length of term's associated doclist)
113952 ** char pDoclist[nDoclist]; (content of doclist)
113953 ** array {
113954 ** (further terms are delta-encoded)
113955 ** varint nPrefix; (length of prefix shared with previous term)
113956 ** varint nSuffix; (length of unshared suffix)
113957 ** char pTermSuffix[nSuffix];(unshared suffix of next term)
113958 ** varint nDoclist; (length of term's associated doclist)
113959 ** char pDoclist[nDoclist]; (content of doclist)
113962 ** Here, array { X } means zero or more occurrences of X, adjacent in
113963 ** memory.
113965 ** Leaf nodes are broken into blocks which are stored contiguously in
113966 ** the %_segments table in sorted order. This means that when the end
113967 ** of a node is reached, the next term is in the node with the next
113968 ** greater node id.
113970 ** New data is spilled to a new leaf node when the current node
113971 ** exceeds LEAF_MAX bytes (default 2048). New data which itself is
113972 ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
113973 ** node (a leaf node with a single term and doclist). The goal of
113974 ** these settings is to pack together groups of small doclists while
113975 ** making it efficient to directly access large doclists. The
113976 ** assumption is that large doclists represent terms which are more
113977 ** likely to be query targets.
113979 ** TODO(shess) It may be useful for blocking decisions to be more
113980 ** dynamic. For instance, it may make more sense to have a 2.5k leaf
113981 ** node rather than splitting into 2k and .5k nodes. My intuition is
113982 ** that this might extend through 2x or 4x the pagesize.
113985 **** Segment interior nodes ****
113986 ** Segment interior nodes store blockids for subtree nodes and terms
113987 ** to describe what data is stored by the each subtree. Interior
113988 ** nodes are written using InteriorWriter, and read using
113989 ** InteriorReader. InteriorWriters are created as needed when
113990 ** SegmentWriter creates new leaf nodes, or when an interior node
113991 ** itself grows too big and must be split. The format of interior
113992 ** nodes:
113994 ** varint iHeight; (height from leaf level, always >0)
113995 ** varint iBlockid; (block id of node's leftmost subtree)
113996 ** optional {
113997 ** varint nTerm; (length of first term)
113998 ** char pTerm[nTerm]; (content of first term)
113999 ** array {
114000 ** (further terms are delta-encoded)
114001 ** varint nPrefix; (length of shared prefix with previous term)
114002 ** varint nSuffix; (length of unshared suffix)
114003 ** char pTermSuffix[nSuffix]; (unshared suffix of next term)
114007 ** Here, optional { X } means an optional element, while array { X }
114008 ** means zero or more occurrences of X, adjacent in memory.
114010 ** An interior node encodes n terms separating n+1 subtrees. The
114011 ** subtree blocks are contiguous, so only the first subtree's blockid
114012 ** is encoded. The subtree at iBlockid will contain all terms less
114013 ** than the first term encoded (or all terms if no term is encoded).
114014 ** Otherwise, for terms greater than or equal to pTerm[i] but less
114015 ** than pTerm[i+1], the subtree for that term will be rooted at
114016 ** iBlockid+i. Interior nodes only store enough term data to
114017 ** distinguish adjacent children (if the rightmost term of the left
114018 ** child is "something", and the leftmost term of the right child is
114019 ** "wicked", only "w" is stored).
114021 ** New data is spilled to a new interior node at the same height when
114022 ** the current node exceeds INTERIOR_MAX bytes (default 2048).
114023 ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
114024 ** interior nodes and making the tree too skinny. The interior nodes
114025 ** at a given height are naturally tracked by interior nodes at
114026 ** height+1, and so on.
114029 **** Segment directory ****
114030 ** The segment directory in table %_segdir stores meta-information for
114031 ** merging and deleting segments, and also the root node of the
114032 ** segment's tree.
114034 ** The root node is the top node of the segment's tree after encoding
114035 ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
114036 ** This could be either a leaf node or an interior node. If the top
114037 ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
114038 ** and a new root interior node is generated (which should always fit
114039 ** within ROOT_MAX because it only needs space for 2 varints, the
114040 ** height and the blockid of the previous root).
114042 ** The meta-information in the segment directory is:
114043 ** level - segment level (see below)
114044 ** idx - index within level
114045 ** - (level,idx uniquely identify a segment)
114046 ** start_block - first leaf node
114047 ** leaves_end_block - last leaf node
114048 ** end_block - last block (including interior nodes)
114049 ** root - contents of root node
114051 ** If the root node is a leaf node, then start_block,
114052 ** leaves_end_block, and end_block are all 0.
114055 **** Segment merging ****
114056 ** To amortize update costs, segments are grouped into levels and
114057 ** merged in batches. Each increase in level represents exponentially
114058 ** more documents.
114060 ** New documents (actually, document updates) are tokenized and
114061 ** written individually (using LeafWriter) to a level 0 segment, with
114062 ** incrementing idx. When idx reaches MERGE_COUNT (default 16), all
114063 ** level 0 segments are merged into a single level 1 segment. Level 1
114064 ** is populated like level 0, and eventually MERGE_COUNT level 1
114065 ** segments are merged to a single level 2 segment (representing
114066 ** MERGE_COUNT^2 updates), and so on.
114068 ** A segment merge traverses all segments at a given level in
114069 ** parallel, performing a straightforward sorted merge. Since segment
114070 ** leaf nodes are written in to the %_segments table in order, this
114071 ** merge traverses the underlying sqlite disk structures efficiently.
114072 ** After the merge, all segment blocks from the merged level are
114073 ** deleted.
114075 ** MERGE_COUNT controls how often we merge segments. 16 seems to be
114076 ** somewhat of a sweet spot for insertion performance. 32 and 64 show
114077 ** very similar performance numbers to 16 on insertion, though they're
114078 ** a tiny bit slower (perhaps due to more overhead in merge-time
114079 ** sorting). 8 is about 20% slower than 16, 4 about 50% slower than
114080 ** 16, 2 about 66% slower than 16.
114082 ** At query time, high MERGE_COUNT increases the number of segments
114083 ** which need to be scanned and merged. For instance, with 100k docs
114084 ** inserted:
114086 ** MERGE_COUNT segments
114087 ** 16 25
114088 ** 8 12
114089 ** 4 10
114090 ** 2 6
114092 ** This appears to have only a moderate impact on queries for very
114093 ** frequent terms (which are somewhat dominated by segment merge
114094 ** costs), and infrequent and non-existent terms still seem to be fast
114095 ** even with many segments.
114097 ** TODO(shess) That said, it would be nice to have a better query-side
114098 ** argument for MERGE_COUNT of 16. Also, it is possible/likely that
114099 ** optimizations to things like doclist merging will swing the sweet
114100 ** spot around.
114104 **** Handling of deletions and updates ****
114105 ** Since we're using a segmented structure, with no docid-oriented
114106 ** index into the term index, we clearly cannot simply update the term
114107 ** index when a document is deleted or updated. For deletions, we
114108 ** write an empty doclist (varint(docid) varint(POS_END)), for updates
114109 ** we simply write the new doclist. Segment merges overwrite older
114110 ** data for a particular docid with newer data, so deletes or updates
114111 ** will eventually overtake the earlier data and knock it out. The
114112 ** query logic likewise merges doclists so that newer data knocks out
114113 ** older data.
114115 ** TODO(shess) Provide a VACUUM type operation to clear out all
114116 ** deletions and duplications. This would basically be a forced merge
114117 ** into a single segment.
114120 /************** Include fts3Int.h in the middle of fts3.c ********************/
114121 /************** Begin file fts3Int.h *****************************************/
114123 ** 2009 Nov 12
114125 ** The author disclaims copyright to this source code. In place of
114126 ** a legal notice, here is a blessing:
114128 ** May you do good and not evil.
114129 ** May you find forgiveness for yourself and forgive others.
114130 ** May you share freely, never taking more than you give.
114132 ******************************************************************************
114135 #ifndef _FTSINT_H
114136 #define _FTSINT_H
114138 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
114139 # define NDEBUG 1
114140 #endif
114143 ** FTS4 is really an extension for FTS3. It is enabled using the
114144 ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also all
114145 ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
114147 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
114148 # define SQLITE_ENABLE_FTS3
114149 #endif
114151 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
114153 /* If not building as part of the core, include sqlite3ext.h. */
114154 #ifndef SQLITE_CORE
114155 SQLITE_API extern const sqlite3_api_routines *sqlite3_api;
114156 #endif
114158 /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
114159 /************** Begin file fts3_tokenizer.h **********************************/
114161 ** 2006 July 10
114163 ** The author disclaims copyright to this source code.
114165 *************************************************************************
114166 ** Defines the interface to tokenizers used by fulltext-search. There
114167 ** are three basic components:
114169 ** sqlite3_tokenizer_module is a singleton defining the tokenizer
114170 ** interface functions. This is essentially the class structure for
114171 ** tokenizers.
114173 ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
114174 ** including customization information defined at creation time.
114176 ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
114177 ** tokens from a particular input.
114179 #ifndef _FTS3_TOKENIZER_H_
114180 #define _FTS3_TOKENIZER_H_
114182 /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
114183 ** If tokenizers are to be allowed to call sqlite3_*() functions, then
114184 ** we will need a way to register the API consistently.
114188 ** Structures used by the tokenizer interface. When a new tokenizer
114189 ** implementation is registered, the caller provides a pointer to
114190 ** an sqlite3_tokenizer_module containing pointers to the callback
114191 ** functions that make up an implementation.
114193 ** When an fts3 table is created, it passes any arguments passed to
114194 ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
114195 ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
114196 ** implementation. The xCreate() function in turn returns an
114197 ** sqlite3_tokenizer structure representing the specific tokenizer to
114198 ** be used for the fts3 table (customized by the tokenizer clause arguments).
114200 ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
114201 ** method is called. It returns an sqlite3_tokenizer_cursor object
114202 ** that may be used to tokenize a specific input buffer based on
114203 ** the tokenization rules supplied by a specific sqlite3_tokenizer
114204 ** object.
114206 typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
114207 typedef struct sqlite3_tokenizer sqlite3_tokenizer;
114208 typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
114210 struct sqlite3_tokenizer_module {
114213 ** Structure version. Should always be set to 0.
114215 int iVersion;
114218 ** Create a new tokenizer. The values in the argv[] array are the
114219 ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
114220 ** TABLE statement that created the fts3 table. For example, if
114221 ** the following SQL is executed:
114223 ** CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
114225 ** then argc is set to 2, and the argv[] array contains pointers
114226 ** to the strings "arg1" and "arg2".
114228 ** This method should return either SQLITE_OK (0), or an SQLite error
114229 ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
114230 ** to point at the newly created tokenizer structure. The generic
114231 ** sqlite3_tokenizer.pModule variable should not be initialised by
114232 ** this callback. The caller will do so.
114234 int (*xCreate)(
114235 int argc, /* Size of argv array */
114236 const char *const*argv, /* Tokenizer argument strings */
114237 sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
114241 ** Destroy an existing tokenizer. The fts3 module calls this method
114242 ** exactly once for each successful call to xCreate().
114244 int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
114247 ** Create a tokenizer cursor to tokenize an input buffer. The caller
114248 ** is responsible for ensuring that the input buffer remains valid
114249 ** until the cursor is closed (using the xClose() method).
114251 int (*xOpen)(
114252 sqlite3_tokenizer *pTokenizer, /* Tokenizer object */
114253 const char *pInput, int nBytes, /* Input buffer */
114254 sqlite3_tokenizer_cursor **ppCursor /* OUT: Created tokenizer cursor */
114258 ** Destroy an existing tokenizer cursor. The fts3 module calls this
114259 ** method exactly once for each successful call to xOpen().
114261 int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
114264 ** Retrieve the next token from the tokenizer cursor pCursor. This
114265 ** method should either return SQLITE_OK and set the values of the
114266 ** "OUT" variables identified below, or SQLITE_DONE to indicate that
114267 ** the end of the buffer has been reached, or an SQLite error code.
114269 ** *ppToken should be set to point at a buffer containing the
114270 ** normalized version of the token (i.e. after any case-folding and/or
114271 ** stemming has been performed). *pnBytes should be set to the length
114272 ** of this buffer in bytes. The input text that generated the token is
114273 ** identified by the byte offsets returned in *piStartOffset and
114274 ** *piEndOffset. *piStartOffset should be set to the index of the first
114275 ** byte of the token in the input buffer. *piEndOffset should be set
114276 ** to the index of the first byte just past the end of the token in
114277 ** the input buffer.
114279 ** The buffer *ppToken is set to point at is managed by the tokenizer
114280 ** implementation. It is only required to be valid until the next call
114281 ** to xNext() or xClose().
114283 /* TODO(shess) current implementation requires pInput to be
114284 ** nul-terminated. This should either be fixed, or pInput/nBytes
114285 ** should be converted to zInput.
114287 int (*xNext)(
114288 sqlite3_tokenizer_cursor *pCursor, /* Tokenizer cursor */
114289 const char **ppToken, int *pnBytes, /* OUT: Normalized text for token */
114290 int *piStartOffset, /* OUT: Byte offset of token in input buffer */
114291 int *piEndOffset, /* OUT: Byte offset of end of token in input buffer */
114292 int *piPosition /* OUT: Number of tokens returned before this one */
114296 struct sqlite3_tokenizer {
114297 const sqlite3_tokenizer_module *pModule; /* The module for this tokenizer */
114298 /* Tokenizer implementations will typically add additional fields */
114301 struct sqlite3_tokenizer_cursor {
114302 sqlite3_tokenizer *pTokenizer; /* Tokenizer for this cursor. */
114303 /* Tokenizer implementations will typically add additional fields */
114306 int fts3_global_term_cnt(int iTerm, int iCol);
114307 int fts3_term_cnt(int iTerm, int iCol);
114310 #endif /* _FTS3_TOKENIZER_H_ */
114312 /************** End of fts3_tokenizer.h **************************************/
114313 /************** Continuing where we left off in fts3Int.h ********************/
114314 /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
114315 /************** Begin file fts3_hash.h ***************************************/
114317 ** 2001 September 22
114319 ** The author disclaims copyright to this source code. In place of
114320 ** a legal notice, here is a blessing:
114322 ** May you do good and not evil.
114323 ** May you find forgiveness for yourself and forgive others.
114324 ** May you share freely, never taking more than you give.
114326 *************************************************************************
114327 ** This is the header file for the generic hash-table implemenation
114328 ** used in SQLite. We've modified it slightly to serve as a standalone
114329 ** hash table implementation for the full-text indexing module.
114332 #ifndef _FTS3_HASH_H_
114333 #define _FTS3_HASH_H_
114335 /* Forward declarations of structures. */
114336 typedef struct Fts3Hash Fts3Hash;
114337 typedef struct Fts3HashElem Fts3HashElem;
114339 /* A complete hash table is an instance of the following structure.
114340 ** The internals of this structure are intended to be opaque -- client
114341 ** code should not attempt to access or modify the fields of this structure
114342 ** directly. Change this structure only by using the routines below.
114343 ** However, many of the "procedures" and "functions" for modifying and
114344 ** accessing this structure are really macros, so we can't really make
114345 ** this structure opaque.
114347 struct Fts3Hash {
114348 char keyClass; /* HASH_INT, _POINTER, _STRING, _BINARY */
114349 char copyKey; /* True if copy of key made on insert */
114350 int count; /* Number of entries in this table */
114351 Fts3HashElem *first; /* The first element of the array */
114352 int htsize; /* Number of buckets in the hash table */
114353 struct _fts3ht { /* the hash table */
114354 int count; /* Number of entries with this hash */
114355 Fts3HashElem *chain; /* Pointer to first entry with this hash */
114356 } *ht;
114359 /* Each element in the hash table is an instance of the following
114360 ** structure. All elements are stored on a single doubly-linked list.
114362 ** Again, this structure is intended to be opaque, but it can't really
114363 ** be opaque because it is used by macros.
114365 struct Fts3HashElem {
114366 Fts3HashElem *next, *prev; /* Next and previous elements in the table */
114367 void *data; /* Data associated with this element */
114368 void *pKey; int nKey; /* Key associated with this element */
114372 ** There are 2 different modes of operation for a hash table:
114374 ** FTS3_HASH_STRING pKey points to a string that is nKey bytes long
114375 ** (including the null-terminator, if any). Case
114376 ** is respected in comparisons.
114378 ** FTS3_HASH_BINARY pKey points to binary data nKey bytes long.
114379 ** memcmp() is used to compare keys.
114381 ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
114383 #define FTS3_HASH_STRING 1
114384 #define FTS3_HASH_BINARY 2
114387 ** Access routines. To delete, insert a NULL pointer.
114389 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
114390 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
114391 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
114392 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
114393 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
114396 ** Shorthand for the functions above
114398 #define fts3HashInit sqlite3Fts3HashInit
114399 #define fts3HashInsert sqlite3Fts3HashInsert
114400 #define fts3HashFind sqlite3Fts3HashFind
114401 #define fts3HashClear sqlite3Fts3HashClear
114402 #define fts3HashFindElem sqlite3Fts3HashFindElem
114405 ** Macros for looping over all elements of a hash table. The idiom is
114406 ** like this:
114408 ** Fts3Hash h;
114409 ** Fts3HashElem *p;
114410 ** ...
114411 ** for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
114412 ** SomeStructure *pData = fts3HashData(p);
114413 ** // do something with pData
114416 #define fts3HashFirst(H) ((H)->first)
114417 #define fts3HashNext(E) ((E)->next)
114418 #define fts3HashData(E) ((E)->data)
114419 #define fts3HashKey(E) ((E)->pKey)
114420 #define fts3HashKeysize(E) ((E)->nKey)
114423 ** Number of entries in a hash table
114425 #define fts3HashCount(H) ((H)->count)
114427 #endif /* _FTS3_HASH_H_ */
114429 /************** End of fts3_hash.h *******************************************/
114430 /************** Continuing where we left off in fts3Int.h ********************/
114433 ** This constant controls how often segments are merged. Once there are
114434 ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
114435 ** segment of level N+1.
114437 #define FTS3_MERGE_COUNT 16
114440 ** This is the maximum amount of data (in bytes) to store in the
114441 ** Fts3Table.pendingTerms hash table. Normally, the hash table is
114442 ** populated as documents are inserted/updated/deleted in a transaction
114443 ** and used to create a new segment when the transaction is committed.
114444 ** However if this limit is reached midway through a transaction, a new
114445 ** segment is created and the hash table cleared immediately.
114447 #define FTS3_MAX_PENDING_DATA (1*1024*1024)
114450 ** Macro to return the number of elements in an array. SQLite has a
114451 ** similar macro called ArraySize(). Use a different name to avoid
114452 ** a collision when building an amalgamation with built-in FTS3.
114454 #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
114457 #ifndef MIN
114458 # define MIN(x,y) ((x)<(y)?(x):(y))
114459 #endif
114462 ** Maximum length of a varint encoded integer. The varint format is different
114463 ** from that used by SQLite, so the maximum length is 10, not 9.
114465 #define FTS3_VARINT_MAX 10
114468 ** FTS4 virtual tables may maintain multiple indexes - one index of all terms
114469 ** in the document set and zero or more prefix indexes. All indexes are stored
114470 ** as one or more b+-trees in the %_segments and %_segdir tables.
114472 ** It is possible to determine which index a b+-tree belongs to based on the
114473 ** value stored in the "%_segdir.level" column. Given this value L, the index
114474 ** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
114475 ** level values between 0 and 1023 (inclusive) belong to index 0, all levels
114476 ** between 1024 and 2047 to index 1, and so on.
114478 ** It is considered impossible for an index to use more than 1024 levels. In
114479 ** theory though this may happen, but only after at least
114480 ** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
114482 #define FTS3_SEGDIR_MAXLEVEL 1024
114483 #define FTS3_SEGDIR_MAXLEVEL_STR "1024"
114486 ** The testcase() macro is only used by the amalgamation. If undefined,
114487 ** make it a no-op.
114489 #ifndef testcase
114490 # define testcase(X)
114491 #endif
114494 ** Terminator values for position-lists and column-lists.
114496 #define POS_COLUMN (1) /* Column-list terminator */
114497 #define POS_END (0) /* Position-list terminator */
114500 ** This section provides definitions to allow the
114501 ** FTS3 extension to be compiled outside of the
114502 ** amalgamation.
114504 #ifndef SQLITE_AMALGAMATION
114506 ** Macros indicating that conditional expressions are always true or
114507 ** false.
114509 #ifdef SQLITE_COVERAGE_TEST
114510 # define ALWAYS(x) (1)
114511 # define NEVER(X) (0)
114512 #else
114513 # define ALWAYS(x) (x)
114514 # define NEVER(X) (x)
114515 #endif
114518 ** Internal types used by SQLite.
114520 typedef unsigned char u8; /* 1-byte (or larger) unsigned integer */
114521 typedef short int i16; /* 2-byte (or larger) signed integer */
114522 typedef unsigned int u32; /* 4-byte unsigned integer */
114523 typedef sqlite3_uint64 u64; /* 8-byte unsigned integer */
114526 ** Macro used to suppress compiler warnings for unused parameters.
114528 #define UNUSED_PARAMETER(x) (void)(x)
114531 ** Activate assert() only if SQLITE_TEST is enabled.
114533 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
114534 # define NDEBUG 1
114535 #endif
114538 ** The TESTONLY macro is used to enclose variable declarations or
114539 ** other bits of code that are needed to support the arguments
114540 ** within testcase() and assert() macros.
114542 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
114543 # define TESTONLY(X) X
114544 #else
114545 # define TESTONLY(X)
114546 #endif
114548 #endif /* SQLITE_AMALGAMATION */
114550 #ifdef SQLITE_DEBUG
114551 SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
114552 # define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
114553 #else
114554 # define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
114555 #endif
114557 typedef struct Fts3Table Fts3Table;
114558 typedef struct Fts3Cursor Fts3Cursor;
114559 typedef struct Fts3Expr Fts3Expr;
114560 typedef struct Fts3Phrase Fts3Phrase;
114561 typedef struct Fts3PhraseToken Fts3PhraseToken;
114563 typedef struct Fts3Doclist Fts3Doclist;
114564 typedef struct Fts3SegFilter Fts3SegFilter;
114565 typedef struct Fts3DeferredToken Fts3DeferredToken;
114566 typedef struct Fts3SegReader Fts3SegReader;
114567 typedef struct Fts3MultiSegReader Fts3MultiSegReader;
114570 ** A connection to a fulltext index is an instance of the following
114571 ** structure. The xCreate and xConnect methods create an instance
114572 ** of this structure and xDestroy and xDisconnect free that instance.
114573 ** All other methods receive a pointer to the structure as one of their
114574 ** arguments.
114576 struct Fts3Table {
114577 sqlite3_vtab base; /* Base class used by SQLite core */
114578 sqlite3 *db; /* The database connection */
114579 const char *zDb; /* logical database name */
114580 const char *zName; /* virtual table name */
114581 int nColumn; /* number of named columns in virtual table */
114582 char **azColumn; /* column names. malloced */
114583 sqlite3_tokenizer *pTokenizer; /* tokenizer for inserts and queries */
114584 char *zContentTbl; /* content=xxx option, or NULL */
114586 /* Precompiled statements used by the implementation. Each of these
114587 ** statements is run and reset within a single virtual table API call.
114589 sqlite3_stmt *aStmt[27];
114591 char *zReadExprlist;
114592 char *zWriteExprlist;
114594 int nNodeSize; /* Soft limit for node size */
114595 u8 bHasStat; /* True if %_stat table exists */
114596 u8 bHasDocsize; /* True if %_docsize table exists */
114597 u8 bDescIdx; /* True if doclists are in reverse order */
114598 int nPgsz; /* Page size for host database */
114599 char *zSegmentsTbl; /* Name of %_segments table */
114600 sqlite3_blob *pSegments; /* Blob handle open on %_segments table */
114602 /* TODO: Fix the first paragraph of this comment.
114604 ** The following hash table is used to buffer pending index updates during
114605 ** transactions. Variable nPendingData estimates the memory size of the
114606 ** pending data, including hash table overhead, but not malloc overhead.
114607 ** When nPendingData exceeds nMaxPendingData, the buffer is flushed
114608 ** automatically. Variable iPrevDocid is the docid of the most recently
114609 ** inserted record.
114611 ** A single FTS4 table may have multiple full-text indexes. For each index
114612 ** there is an entry in the aIndex[] array. Index 0 is an index of all the
114613 ** terms that appear in the document set. Each subsequent index in aIndex[]
114614 ** is an index of prefixes of a specific length.
114616 int nIndex; /* Size of aIndex[] */
114617 struct Fts3Index {
114618 int nPrefix; /* Prefix length (0 for main terms index) */
114619 Fts3Hash hPending; /* Pending terms table for this index */
114620 } *aIndex;
114621 int nMaxPendingData; /* Max pending data before flush to disk */
114622 int nPendingData; /* Current bytes of pending data */
114623 sqlite_int64 iPrevDocid; /* Docid of most recently inserted document */
114625 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
114626 /* State variables used for validating that the transaction control
114627 ** methods of the virtual table are called at appropriate times. These
114628 ** values do not contribution to the FTS computation; they are used for
114629 ** verifying the SQLite core.
114631 int inTransaction; /* True after xBegin but before xCommit/xRollback */
114632 int mxSavepoint; /* Largest valid xSavepoint integer */
114633 #endif
114637 ** When the core wants to read from the virtual table, it creates a
114638 ** virtual table cursor (an instance of the following structure) using
114639 ** the xOpen method. Cursors are destroyed using the xClose method.
114641 struct Fts3Cursor {
114642 sqlite3_vtab_cursor base; /* Base class used by SQLite core */
114643 i16 eSearch; /* Search strategy (see below) */
114644 u8 isEof; /* True if at End Of Results */
114645 u8 isRequireSeek; /* True if must seek pStmt to %_content row */
114646 sqlite3_stmt *pStmt; /* Prepared statement in use by the cursor */
114647 Fts3Expr *pExpr; /* Parsed MATCH query string */
114648 int nPhrase; /* Number of matchable phrases in query */
114649 Fts3DeferredToken *pDeferred; /* Deferred search tokens, if any */
114650 sqlite3_int64 iPrevId; /* Previous id read from aDoclist */
114651 char *pNextId; /* Pointer into the body of aDoclist */
114652 char *aDoclist; /* List of docids for full-text queries */
114653 int nDoclist; /* Size of buffer at aDoclist */
114654 u8 bDesc; /* True to sort in descending order */
114655 int eEvalmode; /* An FTS3_EVAL_XX constant */
114656 int nRowAvg; /* Average size of database rows, in pages */
114657 sqlite3_int64 nDoc; /* Documents in table */
114659 int isMatchinfoNeeded; /* True when aMatchinfo[] needs filling in */
114660 u32 *aMatchinfo; /* Information about most recent match */
114661 int nMatchinfo; /* Number of elements in aMatchinfo[] */
114662 char *zMatchinfo; /* Matchinfo specification */
114665 #define FTS3_EVAL_FILTER 0
114666 #define FTS3_EVAL_NEXT 1
114667 #define FTS3_EVAL_MATCHINFO 2
114670 ** The Fts3Cursor.eSearch member is always set to one of the following.
114671 ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
114672 ** FTS3_FULLTEXT_SEARCH. If so, then Fts3Cursor.eSearch - 2 is the index
114673 ** of the column to be searched. For example, in
114675 ** CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
114676 ** SELECT docid FROM ex1 WHERE b MATCH 'one two three';
114678 ** Because the LHS of the MATCH operator is 2nd column "b",
114679 ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1. (+0 for a,
114680 ** +1 for b, +2 for c, +3 for d.) If the LHS of MATCH were "ex1"
114681 ** indicating that all columns should be searched,
114682 ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
114684 #define FTS3_FULLSCAN_SEARCH 0 /* Linear scan of %_content table */
114685 #define FTS3_DOCID_SEARCH 1 /* Lookup by rowid on %_content table */
114686 #define FTS3_FULLTEXT_SEARCH 2 /* Full-text index search */
114689 struct Fts3Doclist {
114690 char *aAll; /* Array containing doclist (or NULL) */
114691 int nAll; /* Size of a[] in bytes */
114692 char *pNextDocid; /* Pointer to next docid */
114694 sqlite3_int64 iDocid; /* Current docid (if pList!=0) */
114695 int bFreeList; /* True if pList should be sqlite3_free()d */
114696 char *pList; /* Pointer to position list following iDocid */
114697 int nList; /* Length of position list */
114701 ** A "phrase" is a sequence of one or more tokens that must match in
114702 ** sequence. A single token is the base case and the most common case.
114703 ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
114704 ** nToken will be the number of tokens in the string.
114706 struct Fts3PhraseToken {
114707 char *z; /* Text of the token */
114708 int n; /* Number of bytes in buffer z */
114709 int isPrefix; /* True if token ends with a "*" character */
114710 int bFirst; /* True if token must appear at position 0 */
114712 /* Variables above this point are populated when the expression is
114713 ** parsed (by code in fts3_expr.c). Below this point the variables are
114714 ** used when evaluating the expression. */
114715 Fts3DeferredToken *pDeferred; /* Deferred token object for this token */
114716 Fts3MultiSegReader *pSegcsr; /* Segment-reader for this token */
114719 struct Fts3Phrase {
114720 /* Cache of doclist for this phrase. */
114721 Fts3Doclist doclist;
114722 int bIncr; /* True if doclist is loaded incrementally */
114723 int iDoclistToken;
114725 /* Variables below this point are populated by fts3_expr.c when parsing
114726 ** a MATCH expression. Everything above is part of the evaluation phase.
114728 int nToken; /* Number of tokens in the phrase */
114729 int iColumn; /* Index of column this phrase must match */
114730 Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
114734 ** A tree of these objects forms the RHS of a MATCH operator.
114736 ** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist
114737 ** points to a malloced buffer, size nDoclist bytes, containing the results
114738 ** of this phrase query in FTS3 doclist format. As usual, the initial
114739 ** "Length" field found in doclists stored on disk is omitted from this
114740 ** buffer.
114742 ** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
114743 ** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
114744 ** where nCol is the number of columns in the queried FTS table. The array
114745 ** is populated as follows:
114747 ** aMI[iCol*3 + 0] = Undefined
114748 ** aMI[iCol*3 + 1] = Number of occurrences
114749 ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
114751 ** The aMI array is allocated using sqlite3_malloc(). It should be freed
114752 ** when the expression node is.
114754 struct Fts3Expr {
114755 int eType; /* One of the FTSQUERY_XXX values defined below */
114756 int nNear; /* Valid if eType==FTSQUERY_NEAR */
114757 Fts3Expr *pParent; /* pParent->pLeft==this or pParent->pRight==this */
114758 Fts3Expr *pLeft; /* Left operand */
114759 Fts3Expr *pRight; /* Right operand */
114760 Fts3Phrase *pPhrase; /* Valid if eType==FTSQUERY_PHRASE */
114762 /* The following are used by the fts3_eval.c module. */
114763 sqlite3_int64 iDocid; /* Current docid */
114764 u8 bEof; /* True this expression is at EOF already */
114765 u8 bStart; /* True if iDocid is valid */
114766 u8 bDeferred; /* True if this expression is entirely deferred */
114768 u32 *aMI;
114772 ** Candidate values for Fts3Query.eType. Note that the order of the first
114773 ** four values is in order of precedence when parsing expressions. For
114774 ** example, the following:
114776 ** "a OR b AND c NOT d NEAR e"
114778 ** is equivalent to:
114780 ** "a OR (b AND (c NOT (d NEAR e)))"
114782 #define FTSQUERY_NEAR 1
114783 #define FTSQUERY_NOT 2
114784 #define FTSQUERY_AND 3
114785 #define FTSQUERY_OR 4
114786 #define FTSQUERY_PHRASE 5
114789 /* fts3_write.c */
114790 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
114791 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
114792 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
114793 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
114794 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, sqlite3_int64,
114795 sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
114796 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
114797 Fts3Table*,int,const char*,int,int,Fts3SegReader**);
114798 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
114799 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, sqlite3_stmt **);
114800 SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *);
114801 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
114803 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
114804 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
114806 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
114807 SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
114808 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
114809 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
114810 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
114812 /* Special values interpreted by sqlite3SegReaderCursor() */
114813 #define FTS3_SEGCURSOR_PENDING -1
114814 #define FTS3_SEGCURSOR_ALL -2
114816 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
114817 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
114818 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
114820 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
114821 Fts3Table *, int, int, const char *, int, int, int, Fts3MultiSegReader *);
114823 /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
114824 #define FTS3_SEGMENT_REQUIRE_POS 0x00000001
114825 #define FTS3_SEGMENT_IGNORE_EMPTY 0x00000002
114826 #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
114827 #define FTS3_SEGMENT_PREFIX 0x00000008
114828 #define FTS3_SEGMENT_SCAN 0x00000010
114829 #define FTS3_SEGMENT_FIRST 0x00000020
114831 /* Type passed as 4th argument to SegmentReaderIterate() */
114832 struct Fts3SegFilter {
114833 const char *zTerm;
114834 int nTerm;
114835 int iCol;
114836 int flags;
114839 struct Fts3MultiSegReader {
114840 /* Used internally by sqlite3Fts3SegReaderXXX() calls */
114841 Fts3SegReader **apSegment; /* Array of Fts3SegReader objects */
114842 int nSegment; /* Size of apSegment array */
114843 int nAdvance; /* How many seg-readers to advance */
114844 Fts3SegFilter *pFilter; /* Pointer to filter object */
114845 char *aBuffer; /* Buffer to merge doclists in */
114846 int nBuffer; /* Allocated size of aBuffer[] in bytes */
114848 int iColFilter; /* If >=0, filter for this column */
114849 int bRestart;
114851 /* Used by fts3.c only. */
114852 int nCost; /* Cost of running iterator */
114853 int bLookup; /* True if a lookup of a single entry. */
114855 /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
114856 char *zTerm; /* Pointer to term buffer */
114857 int nTerm; /* Size of zTerm in bytes */
114858 char *aDoclist; /* Pointer to doclist buffer */
114859 int nDoclist; /* Size of aDoclist[] in bytes */
114862 /* fts3.c */
114863 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
114864 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
114865 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
114866 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
114867 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
114868 SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
114869 SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
114870 SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
114872 /* fts3_tokenizer.c */
114873 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
114874 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
114875 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
114876 sqlite3_tokenizer **, char **
114878 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
114880 /* fts3_snippet.c */
114881 SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
114882 SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
114883 const char *, const char *, int, int
114885 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
114887 /* fts3_expr.c */
114888 SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *,
114889 char **, int, int, int, const char *, int, Fts3Expr **
114891 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
114892 #ifdef SQLITE_TEST
114893 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
114894 SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
114895 #endif
114897 /* fts3_aux.c */
114898 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
114900 SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
114902 SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
114903 Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
114904 SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
114905 Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
114906 SQLITE_PRIVATE char *sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol);
114907 SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
114908 SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
114910 SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
114912 #endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
114913 #endif /* _FTSINT_H */
114915 /************** End of fts3Int.h *********************************************/
114916 /************** Continuing where we left off in fts3.c ***********************/
114917 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
114919 #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
114920 # define SQLITE_CORE 1
114921 #endif
114923 /* #include <assert.h> */
114924 /* #include <stdlib.h> */
114925 /* #include <stddef.h> */
114926 /* #include <stdio.h> */
114927 /* #include <string.h> */
114928 /* #include <stdarg.h> */
114930 #ifndef SQLITE_CORE
114931 SQLITE_EXTENSION_INIT1
114932 #endif
114934 static int fts3EvalNext(Fts3Cursor *pCsr);
114935 static int fts3EvalStart(Fts3Cursor *pCsr);
114936 static int fts3TermSegReaderCursor(
114937 Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
114940 ** Write a 64-bit variable-length integer to memory starting at p[0].
114941 ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
114942 ** The number of bytes written is returned.
114944 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
114945 unsigned char *q = (unsigned char *) p;
114946 sqlite_uint64 vu = v;
114948 *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
114949 vu >>= 7;
114950 }while( vu!=0 );
114951 q[-1] &= 0x7f; /* turn off high bit in final byte */
114952 assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
114953 return (int) (q - (unsigned char *)p);
114957 ** Read a 64-bit variable-length integer from memory starting at p[0].
114958 ** Return the number of bytes read, or 0 on error.
114959 ** The value is stored in *v.
114961 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
114962 const unsigned char *q = (const unsigned char *) p;
114963 sqlite_uint64 x = 0, y = 1;
114964 while( (*q&0x80)==0x80 && q-(unsigned char *)p<FTS3_VARINT_MAX ){
114965 x += y * (*q++ & 0x7f);
114966 y <<= 7;
114968 x += y * (*q++);
114969 *v = (sqlite_int64) x;
114970 return (int) (q - (unsigned char *)p);
114974 ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
114975 ** 32-bit integer before it is returned.
114977 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
114978 sqlite_int64 i;
114979 int ret = sqlite3Fts3GetVarint(p, &i);
114980 *pi = (int) i;
114981 return ret;
114985 ** Return the number of bytes required to encode v as a varint
114987 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
114988 int i = 0;
114991 v >>= 7;
114992 }while( v!=0 );
114993 return i;
114997 ** Convert an SQL-style quoted string into a normal string by removing
114998 ** the quote characters. The conversion is done in-place. If the
114999 ** input does not begin with a quote character, then this routine
115000 ** is a no-op.
115002 ** Examples:
115004 ** "abc" becomes abc
115005 ** 'xyz' becomes xyz
115006 ** [pqr] becomes pqr
115007 ** `mno` becomes mno
115010 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
115011 char quote; /* Quote character (if any ) */
115013 quote = z[0];
115014 if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
115015 int iIn = 1; /* Index of next byte to read from input */
115016 int iOut = 0; /* Index of next byte to write to output */
115018 /* If the first byte was a '[', then the close-quote character is a ']' */
115019 if( quote=='[' ) quote = ']';
115021 while( ALWAYS(z[iIn]) ){
115022 if( z[iIn]==quote ){
115023 if( z[iIn+1]!=quote ) break;
115024 z[iOut++] = quote;
115025 iIn += 2;
115026 }else{
115027 z[iOut++] = z[iIn++];
115030 z[iOut] = '\0';
115035 ** Read a single varint from the doclist at *pp and advance *pp to point
115036 ** to the first byte past the end of the varint. Add the value of the varint
115037 ** to *pVal.
115039 static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
115040 sqlite3_int64 iVal;
115041 *pp += sqlite3Fts3GetVarint(*pp, &iVal);
115042 *pVal += iVal;
115046 ** When this function is called, *pp points to the first byte following a
115047 ** varint that is part of a doclist (or position-list, or any other list
115048 ** of varints). This function moves *pp to point to the start of that varint,
115049 ** and sets *pVal by the varint value.
115051 ** Argument pStart points to the first byte of the doclist that the
115052 ** varint is part of.
115054 static void fts3GetReverseVarint(
115055 char **pp,
115056 char *pStart,
115057 sqlite3_int64 *pVal
115059 sqlite3_int64 iVal;
115060 char *p;
115062 /* Pointer p now points at the first byte past the varint we are
115063 ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
115064 ** clear on character p[-1]. */
115065 for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
115067 *pp = p;
115069 sqlite3Fts3GetVarint(p, &iVal);
115070 *pVal = iVal;
115074 ** The xDisconnect() virtual table method.
115076 static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
115077 Fts3Table *p = (Fts3Table *)pVtab;
115078 int i;
115080 assert( p->nPendingData==0 );
115081 assert( p->pSegments==0 );
115083 /* Free any prepared statements held */
115084 for(i=0; i<SizeofArray(p->aStmt); i++){
115085 sqlite3_finalize(p->aStmt[i]);
115087 sqlite3_free(p->zSegmentsTbl);
115088 sqlite3_free(p->zReadExprlist);
115089 sqlite3_free(p->zWriteExprlist);
115090 sqlite3_free(p->zContentTbl);
115092 /* Invoke the tokenizer destructor to free the tokenizer. */
115093 p->pTokenizer->pModule->xDestroy(p->pTokenizer);
115095 sqlite3_free(p);
115096 return SQLITE_OK;
115100 ** Construct one or more SQL statements from the format string given
115101 ** and then evaluate those statements. The success code is written
115102 ** into *pRc.
115104 ** If *pRc is initially non-zero then this routine is a no-op.
115106 static void fts3DbExec(
115107 int *pRc, /* Success code */
115108 sqlite3 *db, /* Database in which to run SQL */
115109 const char *zFormat, /* Format string for SQL */
115110 ... /* Arguments to the format string */
115112 va_list ap;
115113 char *zSql;
115114 if( *pRc ) return;
115115 va_start(ap, zFormat);
115116 zSql = sqlite3_vmprintf(zFormat, ap);
115117 va_end(ap);
115118 if( zSql==0 ){
115119 *pRc = SQLITE_NOMEM;
115120 }else{
115121 *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
115122 sqlite3_free(zSql);
115127 ** The xDestroy() virtual table method.
115129 static int fts3DestroyMethod(sqlite3_vtab *pVtab){
115130 Fts3Table *p = (Fts3Table *)pVtab;
115131 int rc = SQLITE_OK; /* Return code */
115132 const char *zDb = p->zDb; /* Name of database (e.g. "main", "temp") */
115133 sqlite3 *db = p->db; /* Database handle */
115135 /* Drop the shadow tables */
115136 if( p->zContentTbl==0 ){
115137 fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName);
115139 fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName);
115140 fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName);
115141 fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName);
115142 fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName);
115144 /* If everything has worked, invoke fts3DisconnectMethod() to free the
115145 ** memory associated with the Fts3Table structure and return SQLITE_OK.
115146 ** Otherwise, return an SQLite error code.
115148 return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
115153 ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
115154 ** passed as the first argument. This is done as part of the xConnect()
115155 ** and xCreate() methods.
115157 ** If *pRc is non-zero when this function is called, it is a no-op.
115158 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
115159 ** before returning.
115161 static void fts3DeclareVtab(int *pRc, Fts3Table *p){
115162 if( *pRc==SQLITE_OK ){
115163 int i; /* Iterator variable */
115164 int rc; /* Return code */
115165 char *zSql; /* SQL statement passed to declare_vtab() */
115166 char *zCols; /* List of user defined columns */
115168 sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
115170 /* Create a list of user columns for the virtual table */
115171 zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
115172 for(i=1; zCols && i<p->nColumn; i++){
115173 zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
115176 /* Create the whole "CREATE TABLE" statement to pass to SQLite */
115177 zSql = sqlite3_mprintf(
115178 "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN)", zCols, p->zName
115180 if( !zCols || !zSql ){
115181 rc = SQLITE_NOMEM;
115182 }else{
115183 rc = sqlite3_declare_vtab(p->db, zSql);
115186 sqlite3_free(zSql);
115187 sqlite3_free(zCols);
115188 *pRc = rc;
115193 ** Create the backing store tables (%_content, %_segments and %_segdir)
115194 ** required by the FTS3 table passed as the only argument. This is done
115195 ** as part of the vtab xCreate() method.
115197 ** If the p->bHasDocsize boolean is true (indicating that this is an
115198 ** FTS4 table, not an FTS3 table) then also create the %_docsize and
115199 ** %_stat tables required by FTS4.
115201 static int fts3CreateTables(Fts3Table *p){
115202 int rc = SQLITE_OK; /* Return code */
115203 int i; /* Iterator variable */
115204 sqlite3 *db = p->db; /* The database connection */
115206 if( p->zContentTbl==0 ){
115207 char *zContentCols; /* Columns of %_content table */
115209 /* Create a list of user columns for the content table */
115210 zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
115211 for(i=0; zContentCols && i<p->nColumn; i++){
115212 char *z = p->azColumn[i];
115213 zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
115215 if( zContentCols==0 ) rc = SQLITE_NOMEM;
115217 /* Create the content table */
115218 fts3DbExec(&rc, db,
115219 "CREATE TABLE %Q.'%q_content'(%s)",
115220 p->zDb, p->zName, zContentCols
115222 sqlite3_free(zContentCols);
115225 /* Create other tables */
115226 fts3DbExec(&rc, db,
115227 "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
115228 p->zDb, p->zName
115230 fts3DbExec(&rc, db,
115231 "CREATE TABLE %Q.'%q_segdir'("
115232 "level INTEGER,"
115233 "idx INTEGER,"
115234 "start_block INTEGER,"
115235 "leaves_end_block INTEGER,"
115236 "end_block INTEGER,"
115237 "root BLOB,"
115238 "PRIMARY KEY(level, idx)"
115239 ");",
115240 p->zDb, p->zName
115242 if( p->bHasDocsize ){
115243 fts3DbExec(&rc, db,
115244 "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
115245 p->zDb, p->zName
115248 if( p->bHasStat ){
115249 fts3DbExec(&rc, db,
115250 "CREATE TABLE %Q.'%q_stat'(id INTEGER PRIMARY KEY, value BLOB);",
115251 p->zDb, p->zName
115254 return rc;
115258 ** Store the current database page-size in bytes in p->nPgsz.
115260 ** If *pRc is non-zero when this function is called, it is a no-op.
115261 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
115262 ** before returning.
115264 static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
115265 if( *pRc==SQLITE_OK ){
115266 int rc; /* Return code */
115267 char *zSql; /* SQL text "PRAGMA %Q.page_size" */
115268 sqlite3_stmt *pStmt; /* Compiled "PRAGMA %Q.page_size" statement */
115270 zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
115271 if( !zSql ){
115272 rc = SQLITE_NOMEM;
115273 }else{
115274 rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
115275 if( rc==SQLITE_OK ){
115276 sqlite3_step(pStmt);
115277 p->nPgsz = sqlite3_column_int(pStmt, 0);
115278 rc = sqlite3_finalize(pStmt);
115279 }else if( rc==SQLITE_AUTH ){
115280 p->nPgsz = 1024;
115281 rc = SQLITE_OK;
115284 assert( p->nPgsz>0 || rc!=SQLITE_OK );
115285 sqlite3_free(zSql);
115286 *pRc = rc;
115291 ** "Special" FTS4 arguments are column specifications of the following form:
115293 ** <key> = <value>
115295 ** There may not be whitespace surrounding the "=" character. The <value>
115296 ** term may be quoted, but the <key> may not.
115298 static int fts3IsSpecialColumn(
115299 const char *z,
115300 int *pnKey,
115301 char **pzValue
115303 char *zValue;
115304 const char *zCsr = z;
115306 while( *zCsr!='=' ){
115307 if( *zCsr=='\0' ) return 0;
115308 zCsr++;
115311 *pnKey = (int)(zCsr-z);
115312 zValue = sqlite3_mprintf("%s", &zCsr[1]);
115313 if( zValue ){
115314 sqlite3Fts3Dequote(zValue);
115316 *pzValue = zValue;
115317 return 1;
115321 ** Append the output of a printf() style formatting to an existing string.
115323 static void fts3Appendf(
115324 int *pRc, /* IN/OUT: Error code */
115325 char **pz, /* IN/OUT: Pointer to string buffer */
115326 const char *zFormat, /* Printf format string to append */
115327 ... /* Arguments for printf format string */
115329 if( *pRc==SQLITE_OK ){
115330 va_list ap;
115331 char *z;
115332 va_start(ap, zFormat);
115333 z = sqlite3_vmprintf(zFormat, ap);
115334 if( z && *pz ){
115335 char *z2 = sqlite3_mprintf("%s%s", *pz, z);
115336 sqlite3_free(z);
115337 z = z2;
115339 if( z==0 ) *pRc = SQLITE_NOMEM;
115340 sqlite3_free(*pz);
115341 *pz = z;
115346 ** Return a copy of input string zInput enclosed in double-quotes (") and
115347 ** with all double quote characters escaped. For example:
115349 ** fts3QuoteId("un \"zip\"") -> "un \"\"zip\"\""
115351 ** The pointer returned points to memory obtained from sqlite3_malloc(). It
115352 ** is the callers responsibility to call sqlite3_free() to release this
115353 ** memory.
115355 static char *fts3QuoteId(char const *zInput){
115356 int nRet;
115357 char *zRet;
115358 nRet = 2 + strlen(zInput)*2 + 1;
115359 zRet = sqlite3_malloc(nRet);
115360 if( zRet ){
115361 int i;
115362 char *z = zRet;
115363 *(z++) = '"';
115364 for(i=0; zInput[i]; i++){
115365 if( zInput[i]=='"' ) *(z++) = '"';
115366 *(z++) = zInput[i];
115368 *(z++) = '"';
115369 *(z++) = '\0';
115371 return zRet;
115375 ** Return a list of comma separated SQL expressions and a FROM clause that
115376 ** could be used in a SELECT statement such as the following:
115378 ** SELECT <list of expressions> FROM %_content AS x ...
115380 ** to return the docid, followed by each column of text data in order
115381 ** from left to write. If parameter zFunc is not NULL, then instead of
115382 ** being returned directly each column of text data is passed to an SQL
115383 ** function named zFunc first. For example, if zFunc is "unzip" and the
115384 ** table has the three user-defined columns "a", "b", and "c", the following
115385 ** string is returned:
115387 ** "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
115389 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
115390 ** is the responsibility of the caller to eventually free it.
115392 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
115393 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
115394 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
115395 ** no error occurs, *pRc is left unmodified.
115397 static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
115398 char *zRet = 0;
115399 char *zFree = 0;
115400 char *zFunction;
115401 int i;
115403 if( p->zContentTbl==0 ){
115404 if( !zFunc ){
115405 zFunction = "";
115406 }else{
115407 zFree = zFunction = fts3QuoteId(zFunc);
115409 fts3Appendf(pRc, &zRet, "docid");
115410 for(i=0; i<p->nColumn; i++){
115411 fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
115413 sqlite3_free(zFree);
115414 }else{
115415 fts3Appendf(pRc, &zRet, "rowid");
115416 for(i=0; i<p->nColumn; i++){
115417 fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
115420 fts3Appendf(pRc, &zRet, "FROM '%q'.'%q%s' AS x",
115421 p->zDb,
115422 (p->zContentTbl ? p->zContentTbl : p->zName),
115423 (p->zContentTbl ? "" : "_content")
115425 return zRet;
115429 ** Return a list of N comma separated question marks, where N is the number
115430 ** of columns in the %_content table (one for the docid plus one for each
115431 ** user-defined text column).
115433 ** If argument zFunc is not NULL, then all but the first question mark
115434 ** is preceded by zFunc and an open bracket, and followed by a closed
115435 ** bracket. For example, if zFunc is "zip" and the FTS3 table has three
115436 ** user-defined text columns, the following string is returned:
115438 ** "?, zip(?), zip(?), zip(?)"
115440 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
115441 ** is the responsibility of the caller to eventually free it.
115443 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
115444 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
115445 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
115446 ** no error occurs, *pRc is left unmodified.
115448 static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
115449 char *zRet = 0;
115450 char *zFree = 0;
115451 char *zFunction;
115452 int i;
115454 if( !zFunc ){
115455 zFunction = "";
115456 }else{
115457 zFree = zFunction = fts3QuoteId(zFunc);
115459 fts3Appendf(pRc, &zRet, "?");
115460 for(i=0; i<p->nColumn; i++){
115461 fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
115463 sqlite3_free(zFree);
115464 return zRet;
115468 ** This function interprets the string at (*pp) as a non-negative integer
115469 ** value. It reads the integer and sets *pnOut to the value read, then
115470 ** sets *pp to point to the byte immediately following the last byte of
115471 ** the integer value.
115473 ** Only decimal digits ('0'..'9') may be part of an integer value.
115475 ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
115476 ** the output value undefined. Otherwise SQLITE_OK is returned.
115478 ** This function is used when parsing the "prefix=" FTS4 parameter.
115480 static int fts3GobbleInt(const char **pp, int *pnOut){
115481 const char *p; /* Iterator pointer */
115482 int nInt = 0; /* Output value */
115484 for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
115485 nInt = nInt * 10 + (p[0] - '0');
115487 if( p==*pp ) return SQLITE_ERROR;
115488 *pnOut = nInt;
115489 *pp = p;
115490 return SQLITE_OK;
115494 ** This function is called to allocate an array of Fts3Index structures
115495 ** representing the indexes maintained by the current FTS table. FTS tables
115496 ** always maintain the main "terms" index, but may also maintain one or
115497 ** more "prefix" indexes, depending on the value of the "prefix=" parameter
115498 ** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
115500 ** Argument zParam is passed the value of the "prefix=" option if one was
115501 ** specified, or NULL otherwise.
115503 ** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
115504 ** the allocated array. *pnIndex is set to the number of elements in the
115505 ** array. If an error does occur, an SQLite error code is returned.
115507 ** Regardless of whether or not an error is returned, it is the responsibility
115508 ** of the caller to call sqlite3_free() on the output array to free it.
115510 static int fts3PrefixParameter(
115511 const char *zParam, /* ABC in prefix=ABC parameter to parse */
115512 int *pnIndex, /* OUT: size of *apIndex[] array */
115513 struct Fts3Index **apIndex /* OUT: Array of indexes for this table */
115515 struct Fts3Index *aIndex; /* Allocated array */
115516 int nIndex = 1; /* Number of entries in array */
115518 if( zParam && zParam[0] ){
115519 const char *p;
115520 nIndex++;
115521 for(p=zParam; *p; p++){
115522 if( *p==',' ) nIndex++;
115526 aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
115527 *apIndex = aIndex;
115528 *pnIndex = nIndex;
115529 if( !aIndex ){
115530 return SQLITE_NOMEM;
115533 memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
115534 if( zParam ){
115535 const char *p = zParam;
115536 int i;
115537 for(i=1; i<nIndex; i++){
115538 int nPrefix;
115539 if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
115540 aIndex[i].nPrefix = nPrefix;
115545 return SQLITE_OK;
115549 ** This function is called when initializing an FTS4 table that uses the
115550 ** content=xxx option. It determines the number of and names of the columns
115551 ** of the new FTS4 table.
115553 ** The third argument passed to this function is the value passed to the
115554 ** config=xxx option (i.e. "xxx"). This function queries the database for
115555 ** a table of that name. If found, the output variables are populated
115556 ** as follows:
115558 ** *pnCol: Set to the number of columns table xxx has,
115560 ** *pnStr: Set to the total amount of space required to store a copy
115561 ** of each columns name, including the nul-terminator.
115563 ** *pazCol: Set to point to an array of *pnCol strings. Each string is
115564 ** the name of the corresponding column in table xxx. The array
115565 ** and its contents are allocated using a single allocation. It
115566 ** is the responsibility of the caller to free this allocation
115567 ** by eventually passing the *pazCol value to sqlite3_free().
115569 ** If the table cannot be found, an error code is returned and the output
115570 ** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
115571 ** returned (and the output variables are undefined).
115573 static int fts3ContentColumns(
115574 sqlite3 *db, /* Database handle */
115575 const char *zDb, /* Name of db (i.e. "main", "temp" etc.) */
115576 const char *zTbl, /* Name of content table */
115577 const char ***pazCol, /* OUT: Malloc'd array of column names */
115578 int *pnCol, /* OUT: Size of array *pazCol */
115579 int *pnStr /* OUT: Bytes of string content */
115581 int rc = SQLITE_OK; /* Return code */
115582 char *zSql; /* "SELECT *" statement on zTbl */
115583 sqlite3_stmt *pStmt = 0; /* Compiled version of zSql */
115585 zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
115586 if( !zSql ){
115587 rc = SQLITE_NOMEM;
115588 }else{
115589 rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
115591 sqlite3_free(zSql);
115593 if( rc==SQLITE_OK ){
115594 const char **azCol; /* Output array */
115595 int nStr = 0; /* Size of all column names (incl. 0x00) */
115596 int nCol; /* Number of table columns */
115597 int i; /* Used to iterate through columns */
115599 /* Loop through the returned columns. Set nStr to the number of bytes of
115600 ** space required to store a copy of each column name, including the
115601 ** nul-terminator byte. */
115602 nCol = sqlite3_column_count(pStmt);
115603 for(i=0; i<nCol; i++){
115604 const char *zCol = sqlite3_column_name(pStmt, i);
115605 nStr += strlen(zCol) + 1;
115608 /* Allocate and populate the array to return. */
115609 azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr);
115610 if( azCol==0 ){
115611 rc = SQLITE_NOMEM;
115612 }else{
115613 char *p = (char *)&azCol[nCol];
115614 for(i=0; i<nCol; i++){
115615 const char *zCol = sqlite3_column_name(pStmt, i);
115616 int n = strlen(zCol)+1;
115617 memcpy(p, zCol, n);
115618 azCol[i] = p;
115619 p += n;
115622 sqlite3_finalize(pStmt);
115624 /* Set the output variables. */
115625 *pnCol = nCol;
115626 *pnStr = nStr;
115627 *pazCol = azCol;
115630 return rc;
115634 ** This function is the implementation of both the xConnect and xCreate
115635 ** methods of the FTS3 virtual table.
115637 ** The argv[] array contains the following:
115639 ** argv[0] -> module name ("fts3" or "fts4")
115640 ** argv[1] -> database name
115641 ** argv[2] -> table name
115642 ** argv[...] -> "column name" and other module argument fields.
115644 static int fts3InitVtab(
115645 int isCreate, /* True for xCreate, false for xConnect */
115646 sqlite3 *db, /* The SQLite database connection */
115647 void *pAux, /* Hash table containing tokenizers */
115648 int argc, /* Number of elements in argv array */
115649 const char * const *argv, /* xCreate/xConnect argument array */
115650 sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
115651 char **pzErr /* Write any error message here */
115653 Fts3Hash *pHash = (Fts3Hash *)pAux;
115654 Fts3Table *p = 0; /* Pointer to allocated vtab */
115655 int rc = SQLITE_OK; /* Return code */
115656 int i; /* Iterator variable */
115657 int nByte; /* Size of allocation used for *p */
115658 int iCol; /* Column index */
115659 int nString = 0; /* Bytes required to hold all column names */
115660 int nCol = 0; /* Number of columns in the FTS table */
115661 char *zCsr; /* Space for holding column names */
115662 int nDb; /* Bytes required to hold database name */
115663 int nName; /* Bytes required to hold table name */
115664 int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
115665 const char **aCol; /* Array of column names */
115666 sqlite3_tokenizer *pTokenizer = 0; /* Tokenizer for this table */
115668 int nIndex; /* Size of aIndex[] array */
115669 struct Fts3Index *aIndex = 0; /* Array of indexes for this table */
115671 /* The results of parsing supported FTS4 key=value options: */
115672 int bNoDocsize = 0; /* True to omit %_docsize table */
115673 int bDescIdx = 0; /* True to store descending indexes */
115674 char *zPrefix = 0; /* Prefix parameter value (or NULL) */
115675 char *zCompress = 0; /* compress=? parameter (or NULL) */
115676 char *zUncompress = 0; /* uncompress=? parameter (or NULL) */
115677 char *zContent = 0; /* content=? parameter (or NULL) */
115679 assert( strlen(argv[0])==4 );
115680 assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
115681 || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
115684 nDb = (int)strlen(argv[1]) + 1;
115685 nName = (int)strlen(argv[2]) + 1;
115687 aCol = (const char **)sqlite3_malloc(sizeof(const char *) * (argc-2) );
115688 if( !aCol ) return SQLITE_NOMEM;
115689 memset((void *)aCol, 0, sizeof(const char *) * (argc-2));
115691 /* Loop through all of the arguments passed by the user to the FTS3/4
115692 ** module (i.e. all the column names and special arguments). This loop
115693 ** does the following:
115695 ** + Figures out the number of columns the FTSX table will have, and
115696 ** the number of bytes of space that must be allocated to store copies
115697 ** of the column names.
115699 ** + If there is a tokenizer specification included in the arguments,
115700 ** initializes the tokenizer pTokenizer.
115702 for(i=3; rc==SQLITE_OK && i<argc; i++){
115703 char const *z = argv[i];
115704 int nKey;
115705 char *zVal;
115707 /* Check if this is a tokenizer specification */
115708 if( !pTokenizer
115709 && strlen(z)>8
115710 && 0==sqlite3_strnicmp(z, "tokenize", 8)
115711 && 0==sqlite3Fts3IsIdChar(z[8])
115713 rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
115716 /* Check if it is an FTS4 special argument. */
115717 else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
115718 struct Fts4Option {
115719 const char *zOpt;
115720 int nOpt;
115721 } aFts4Opt[] = {
115722 { "matchinfo", 9 }, /* 0 -> MATCHINFO */
115723 { "prefix", 6 }, /* 1 -> PREFIX */
115724 { "compress", 8 }, /* 2 -> COMPRESS */
115725 { "uncompress", 10 }, /* 3 -> UNCOMPRESS */
115726 { "order", 5 }, /* 4 -> ORDER */
115727 { "content", 7 } /* 5 -> CONTENT */
115730 int iOpt;
115731 if( !zVal ){
115732 rc = SQLITE_NOMEM;
115733 }else{
115734 for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
115735 struct Fts4Option *pOp = &aFts4Opt[iOpt];
115736 if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
115737 break;
115740 if( iOpt==SizeofArray(aFts4Opt) ){
115741 *pzErr = sqlite3_mprintf("unrecognized parameter: %s", z);
115742 rc = SQLITE_ERROR;
115743 }else{
115744 switch( iOpt ){
115745 case 0: /* MATCHINFO */
115746 if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
115747 *pzErr = sqlite3_mprintf("unrecognized matchinfo: %s", zVal);
115748 rc = SQLITE_ERROR;
115750 bNoDocsize = 1;
115751 break;
115753 case 1: /* PREFIX */
115754 sqlite3_free(zPrefix);
115755 zPrefix = zVal;
115756 zVal = 0;
115757 break;
115759 case 2: /* COMPRESS */
115760 sqlite3_free(zCompress);
115761 zCompress = zVal;
115762 zVal = 0;
115763 break;
115765 case 3: /* UNCOMPRESS */
115766 sqlite3_free(zUncompress);
115767 zUncompress = zVal;
115768 zVal = 0;
115769 break;
115771 case 4: /* ORDER */
115772 if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3))
115773 && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4))
115775 *pzErr = sqlite3_mprintf("unrecognized order: %s", zVal);
115776 rc = SQLITE_ERROR;
115778 bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
115779 break;
115781 default: /* CONTENT */
115782 assert( iOpt==5 );
115783 sqlite3_free(zUncompress);
115784 zContent = zVal;
115785 zVal = 0;
115786 break;
115789 sqlite3_free(zVal);
115793 /* Otherwise, the argument is a column name. */
115794 else {
115795 nString += (int)(strlen(z) + 1);
115796 aCol[nCol++] = z;
115800 /* If a content=xxx option was specified, the following:
115802 ** 1. Ignore any compress= and uncompress= options.
115804 ** 2. If no column names were specified as part of the CREATE VIRTUAL
115805 ** TABLE statement, use all columns from the content table.
115807 if( rc==SQLITE_OK && zContent ){
115808 sqlite3_free(zCompress);
115809 sqlite3_free(zUncompress);
115810 zCompress = 0;
115811 zUncompress = 0;
115812 if( nCol==0 ){
115813 sqlite3_free((void*)aCol);
115814 aCol = 0;
115815 rc = fts3ContentColumns(db, argv[1], zContent, &aCol, &nCol, &nString);
115817 assert( rc!=SQLITE_OK || nCol>0 );
115819 if( rc!=SQLITE_OK ) goto fts3_init_out;
115821 if( nCol==0 ){
115822 assert( nString==0 );
115823 aCol[0] = "content";
115824 nString = 8;
115825 nCol = 1;
115828 if( pTokenizer==0 ){
115829 rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
115830 if( rc!=SQLITE_OK ) goto fts3_init_out;
115832 assert( pTokenizer );
115834 rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
115835 if( rc==SQLITE_ERROR ){
115836 assert( zPrefix );
115837 *pzErr = sqlite3_mprintf("error parsing prefix parameter: %s", zPrefix);
115839 if( rc!=SQLITE_OK ) goto fts3_init_out;
115841 /* Allocate and populate the Fts3Table structure. */
115842 nByte = sizeof(Fts3Table) + /* Fts3Table */
115843 nCol * sizeof(char *) + /* azColumn */
115844 nIndex * sizeof(struct Fts3Index) + /* aIndex */
115845 nName + /* zName */
115846 nDb + /* zDb */
115847 nString; /* Space for azColumn strings */
115848 p = (Fts3Table*)sqlite3_malloc(nByte);
115849 if( p==0 ){
115850 rc = SQLITE_NOMEM;
115851 goto fts3_init_out;
115853 memset(p, 0, nByte);
115854 p->db = db;
115855 p->nColumn = nCol;
115856 p->nPendingData = 0;
115857 p->azColumn = (char **)&p[1];
115858 p->pTokenizer = pTokenizer;
115859 p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
115860 p->bHasDocsize = (isFts4 && bNoDocsize==0);
115861 p->bHasStat = isFts4;
115862 p->bDescIdx = bDescIdx;
115863 p->zContentTbl = zContent;
115864 zContent = 0;
115865 TESTONLY( p->inTransaction = -1 );
115866 TESTONLY( p->mxSavepoint = -1 );
115868 p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
115869 memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
115870 p->nIndex = nIndex;
115871 for(i=0; i<nIndex; i++){
115872 fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
115875 /* Fill in the zName and zDb fields of the vtab structure. */
115876 zCsr = (char *)&p->aIndex[nIndex];
115877 p->zName = zCsr;
115878 memcpy(zCsr, argv[2], nName);
115879 zCsr += nName;
115880 p->zDb = zCsr;
115881 memcpy(zCsr, argv[1], nDb);
115882 zCsr += nDb;
115884 /* Fill in the azColumn array */
115885 for(iCol=0; iCol<nCol; iCol++){
115886 char *z;
115887 int n = 0;
115888 z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
115889 memcpy(zCsr, z, n);
115890 zCsr[n] = '\0';
115891 sqlite3Fts3Dequote(zCsr);
115892 p->azColumn[iCol] = zCsr;
115893 zCsr += n+1;
115894 assert( zCsr <= &((char *)p)[nByte] );
115897 if( (zCompress==0)!=(zUncompress==0) ){
115898 char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
115899 rc = SQLITE_ERROR;
115900 *pzErr = sqlite3_mprintf("missing %s parameter in fts4 constructor", zMiss);
115902 p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
115903 p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
115904 if( rc!=SQLITE_OK ) goto fts3_init_out;
115906 /* If this is an xCreate call, create the underlying tables in the
115907 ** database. TODO: For xConnect(), it could verify that said tables exist.
115909 if( isCreate ){
115910 rc = fts3CreateTables(p);
115913 /* Figure out the page-size for the database. This is required in order to
115914 ** estimate the cost of loading large doclists from the database. */
115915 fts3DatabasePageSize(&rc, p);
115916 p->nNodeSize = p->nPgsz-35;
115918 /* Declare the table schema to SQLite. */
115919 fts3DeclareVtab(&rc, p);
115921 fts3_init_out:
115922 sqlite3_free(zPrefix);
115923 sqlite3_free(aIndex);
115924 sqlite3_free(zCompress);
115925 sqlite3_free(zUncompress);
115926 sqlite3_free(zContent);
115927 sqlite3_free((void *)aCol);
115928 if( rc!=SQLITE_OK ){
115929 if( p ){
115930 fts3DisconnectMethod((sqlite3_vtab *)p);
115931 }else if( pTokenizer ){
115932 pTokenizer->pModule->xDestroy(pTokenizer);
115934 }else{
115935 assert( p->pSegments==0 );
115936 *ppVTab = &p->base;
115938 return rc;
115942 ** The xConnect() and xCreate() methods for the virtual table. All the
115943 ** work is done in function fts3InitVtab().
115945 static int fts3ConnectMethod(
115946 sqlite3 *db, /* Database connection */
115947 void *pAux, /* Pointer to tokenizer hash table */
115948 int argc, /* Number of elements in argv array */
115949 const char * const *argv, /* xCreate/xConnect argument array */
115950 sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
115951 char **pzErr /* OUT: sqlite3_malloc'd error message */
115953 return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
115955 static int fts3CreateMethod(
115956 sqlite3 *db, /* Database connection */
115957 void *pAux, /* Pointer to tokenizer hash table */
115958 int argc, /* Number of elements in argv array */
115959 const char * const *argv, /* xCreate/xConnect argument array */
115960 sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
115961 char **pzErr /* OUT: sqlite3_malloc'd error message */
115963 return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
115967 ** Implementation of the xBestIndex method for FTS3 tables. There
115968 ** are three possible strategies, in order of preference:
115970 ** 1. Direct lookup by rowid or docid.
115971 ** 2. Full-text search using a MATCH operator on a non-docid column.
115972 ** 3. Linear scan of %_content table.
115974 static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
115975 Fts3Table *p = (Fts3Table *)pVTab;
115976 int i; /* Iterator variable */
115977 int iCons = -1; /* Index of constraint to use */
115979 /* By default use a full table scan. This is an expensive option,
115980 ** so search through the constraints to see if a more efficient
115981 ** strategy is possible.
115983 pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
115984 pInfo->estimatedCost = 500000;
115985 for(i=0; i<pInfo->nConstraint; i++){
115986 struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
115987 if( pCons->usable==0 ) continue;
115989 /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
115990 if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
115991 && (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1 )
115993 pInfo->idxNum = FTS3_DOCID_SEARCH;
115994 pInfo->estimatedCost = 1.0;
115995 iCons = i;
115998 /* A MATCH constraint. Use a full-text search.
116000 ** If there is more than one MATCH constraint available, use the first
116001 ** one encountered. If there is both a MATCH constraint and a direct
116002 ** rowid/docid lookup, prefer the MATCH strategy. This is done even
116003 ** though the rowid/docid lookup is faster than a MATCH query, selecting
116004 ** it would lead to an "unable to use function MATCH in the requested
116005 ** context" error.
116007 if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
116008 && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
116010 pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
116011 pInfo->estimatedCost = 2.0;
116012 iCons = i;
116013 break;
116017 if( iCons>=0 ){
116018 pInfo->aConstraintUsage[iCons].argvIndex = 1;
116019 pInfo->aConstraintUsage[iCons].omit = 1;
116022 /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
116023 ** docid) order. Both ascending and descending are possible.
116025 if( pInfo->nOrderBy==1 ){
116026 struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
116027 if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
116028 if( pOrder->desc ){
116029 pInfo->idxStr = "DESC";
116030 }else{
116031 pInfo->idxStr = "ASC";
116033 pInfo->orderByConsumed = 1;
116037 assert( p->pSegments==0 );
116038 return SQLITE_OK;
116042 ** Implementation of xOpen method.
116044 static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
116045 sqlite3_vtab_cursor *pCsr; /* Allocated cursor */
116047 UNUSED_PARAMETER(pVTab);
116049 /* Allocate a buffer large enough for an Fts3Cursor structure. If the
116050 ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
116051 ** if the allocation fails, return SQLITE_NOMEM.
116053 *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
116054 if( !pCsr ){
116055 return SQLITE_NOMEM;
116057 memset(pCsr, 0, sizeof(Fts3Cursor));
116058 return SQLITE_OK;
116062 ** Close the cursor. For additional information see the documentation
116063 ** on the xClose method of the virtual table interface.
116065 static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
116066 Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
116067 assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
116068 sqlite3_finalize(pCsr->pStmt);
116069 sqlite3Fts3ExprFree(pCsr->pExpr);
116070 sqlite3Fts3FreeDeferredTokens(pCsr);
116071 sqlite3_free(pCsr->aDoclist);
116072 sqlite3_free(pCsr->aMatchinfo);
116073 assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
116074 sqlite3_free(pCsr);
116075 return SQLITE_OK;
116079 ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
116080 ** compose and prepare an SQL statement of the form:
116082 ** "SELECT <columns> FROM %_content WHERE rowid = ?"
116084 ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
116085 ** it. If an error occurs, return an SQLite error code.
116087 ** Otherwise, set *ppStmt to point to pCsr->pStmt and return SQLITE_OK.
116089 static int fts3CursorSeekStmt(Fts3Cursor *pCsr, sqlite3_stmt **ppStmt){
116090 int rc = SQLITE_OK;
116091 if( pCsr->pStmt==0 ){
116092 Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
116093 char *zSql;
116094 zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
116095 if( !zSql ) return SQLITE_NOMEM;
116096 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
116097 sqlite3_free(zSql);
116099 *ppStmt = pCsr->pStmt;
116100 return rc;
116104 ** Position the pCsr->pStmt statement so that it is on the row
116105 ** of the %_content table that contains the last match. Return
116106 ** SQLITE_OK on success.
116108 static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
116109 int rc = SQLITE_OK;
116110 if( pCsr->isRequireSeek ){
116111 sqlite3_stmt *pStmt = 0;
116113 rc = fts3CursorSeekStmt(pCsr, &pStmt);
116114 if( rc==SQLITE_OK ){
116115 sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
116116 pCsr->isRequireSeek = 0;
116117 if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
116118 return SQLITE_OK;
116119 }else{
116120 rc = sqlite3_reset(pCsr->pStmt);
116121 if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
116122 /* If no row was found and no error has occured, then the %_content
116123 ** table is missing a row that is present in the full-text index.
116124 ** The data structures are corrupt. */
116125 rc = FTS_CORRUPT_VTAB;
116126 pCsr->isEof = 1;
116132 if( rc!=SQLITE_OK && pContext ){
116133 sqlite3_result_error_code(pContext, rc);
116135 return rc;
116139 ** This function is used to process a single interior node when searching
116140 ** a b-tree for a term or term prefix. The node data is passed to this
116141 ** function via the zNode/nNode parameters. The term to search for is
116142 ** passed in zTerm/nTerm.
116144 ** If piFirst is not NULL, then this function sets *piFirst to the blockid
116145 ** of the child node that heads the sub-tree that may contain the term.
116147 ** If piLast is not NULL, then *piLast is set to the right-most child node
116148 ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
116149 ** a prefix.
116151 ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
116153 static int fts3ScanInteriorNode(
116154 const char *zTerm, /* Term to select leaves for */
116155 int nTerm, /* Size of term zTerm in bytes */
116156 const char *zNode, /* Buffer containing segment interior node */
116157 int nNode, /* Size of buffer at zNode */
116158 sqlite3_int64 *piFirst, /* OUT: Selected child node */
116159 sqlite3_int64 *piLast /* OUT: Selected child node */
116161 int rc = SQLITE_OK; /* Return code */
116162 const char *zCsr = zNode; /* Cursor to iterate through node */
116163 const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
116164 char *zBuffer = 0; /* Buffer to load terms into */
116165 int nAlloc = 0; /* Size of allocated buffer */
116166 int isFirstTerm = 1; /* True when processing first term on page */
116167 sqlite3_int64 iChild; /* Block id of child node to descend to */
116169 /* Skip over the 'height' varint that occurs at the start of every
116170 ** interior node. Then load the blockid of the left-child of the b-tree
116171 ** node into variable iChild.
116173 ** Even if the data structure on disk is corrupted, this (reading two
116174 ** varints from the buffer) does not risk an overread. If zNode is a
116175 ** root node, then the buffer comes from a SELECT statement. SQLite does
116176 ** not make this guarantee explicitly, but in practice there are always
116177 ** either more than 20 bytes of allocated space following the nNode bytes of
116178 ** contents, or two zero bytes. Or, if the node is read from the %_segments
116179 ** table, then there are always 20 bytes of zeroed padding following the
116180 ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
116182 zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
116183 zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
116184 if( zCsr>zEnd ){
116185 return FTS_CORRUPT_VTAB;
116188 while( zCsr<zEnd && (piFirst || piLast) ){
116189 int cmp; /* memcmp() result */
116190 int nSuffix; /* Size of term suffix */
116191 int nPrefix = 0; /* Size of term prefix */
116192 int nBuffer; /* Total term size */
116194 /* Load the next term on the node into zBuffer. Use realloc() to expand
116195 ** the size of zBuffer if required. */
116196 if( !isFirstTerm ){
116197 zCsr += sqlite3Fts3GetVarint32(zCsr, &nPrefix);
116199 isFirstTerm = 0;
116200 zCsr += sqlite3Fts3GetVarint32(zCsr, &nSuffix);
116202 if( nPrefix<0 || nSuffix<0 || &zCsr[nSuffix]>zEnd ){
116203 rc = FTS_CORRUPT_VTAB;
116204 goto finish_scan;
116206 if( nPrefix+nSuffix>nAlloc ){
116207 char *zNew;
116208 nAlloc = (nPrefix+nSuffix) * 2;
116209 zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
116210 if( !zNew ){
116211 rc = SQLITE_NOMEM;
116212 goto finish_scan;
116214 zBuffer = zNew;
116216 assert( zBuffer );
116217 memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
116218 nBuffer = nPrefix + nSuffix;
116219 zCsr += nSuffix;
116221 /* Compare the term we are searching for with the term just loaded from
116222 ** the interior node. If the specified term is greater than or equal
116223 ** to the term from the interior node, then all terms on the sub-tree
116224 ** headed by node iChild are smaller than zTerm. No need to search
116225 ** iChild.
116227 ** If the interior node term is larger than the specified term, then
116228 ** the tree headed by iChild may contain the specified term.
116230 cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
116231 if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
116232 *piFirst = iChild;
116233 piFirst = 0;
116236 if( piLast && cmp<0 ){
116237 *piLast = iChild;
116238 piLast = 0;
116241 iChild++;
116244 if( piFirst ) *piFirst = iChild;
116245 if( piLast ) *piLast = iChild;
116247 finish_scan:
116248 sqlite3_free(zBuffer);
116249 return rc;
116254 ** The buffer pointed to by argument zNode (size nNode bytes) contains an
116255 ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
116256 ** contains a term. This function searches the sub-tree headed by the zNode
116257 ** node for the range of leaf nodes that may contain the specified term
116258 ** or terms for which the specified term is a prefix.
116260 ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
116261 ** left-most leaf node in the tree that may contain the specified term.
116262 ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
116263 ** right-most leaf node that may contain a term for which the specified
116264 ** term is a prefix.
116266 ** It is possible that the range of returned leaf nodes does not contain
116267 ** the specified term or any terms for which it is a prefix. However, if the
116268 ** segment does contain any such terms, they are stored within the identified
116269 ** range. Because this function only inspects interior segment nodes (and
116270 ** never loads leaf nodes into memory), it is not possible to be sure.
116272 ** If an error occurs, an error code other than SQLITE_OK is returned.
116274 static int fts3SelectLeaf(
116275 Fts3Table *p, /* Virtual table handle */
116276 const char *zTerm, /* Term to select leaves for */
116277 int nTerm, /* Size of term zTerm in bytes */
116278 const char *zNode, /* Buffer containing segment interior node */
116279 int nNode, /* Size of buffer at zNode */
116280 sqlite3_int64 *piLeaf, /* Selected leaf node */
116281 sqlite3_int64 *piLeaf2 /* Selected leaf node */
116283 int rc; /* Return code */
116284 int iHeight; /* Height of this node in tree */
116286 assert( piLeaf || piLeaf2 );
116288 sqlite3Fts3GetVarint32(zNode, &iHeight);
116289 rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
116290 assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
116292 if( rc==SQLITE_OK && iHeight>1 ){
116293 char *zBlob = 0; /* Blob read from %_segments table */
116294 int nBlob; /* Size of zBlob in bytes */
116296 if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
116297 rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
116298 if( rc==SQLITE_OK ){
116299 rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
116301 sqlite3_free(zBlob);
116302 piLeaf = 0;
116303 zBlob = 0;
116306 if( rc==SQLITE_OK ){
116307 rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
116309 if( rc==SQLITE_OK ){
116310 rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
116312 sqlite3_free(zBlob);
116315 return rc;
116319 ** This function is used to create delta-encoded serialized lists of FTS3
116320 ** varints. Each call to this function appends a single varint to a list.
116322 static void fts3PutDeltaVarint(
116323 char **pp, /* IN/OUT: Output pointer */
116324 sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
116325 sqlite3_int64 iVal /* Write this value to the list */
116327 assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
116328 *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
116329 *piPrev = iVal;
116333 ** When this function is called, *ppPoslist is assumed to point to the
116334 ** start of a position-list. After it returns, *ppPoslist points to the
116335 ** first byte after the position-list.
116337 ** A position list is list of positions (delta encoded) and columns for
116338 ** a single document record of a doclist. So, in other words, this
116339 ** routine advances *ppPoslist so that it points to the next docid in
116340 ** the doclist, or to the first byte past the end of the doclist.
116342 ** If pp is not NULL, then the contents of the position list are copied
116343 ** to *pp. *pp is set to point to the first byte past the last byte copied
116344 ** before this function returns.
116346 static void fts3PoslistCopy(char **pp, char **ppPoslist){
116347 char *pEnd = *ppPoslist;
116348 char c = 0;
116350 /* The end of a position list is marked by a zero encoded as an FTS3
116351 ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
116352 ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
116353 ** of some other, multi-byte, value.
116355 ** The following while-loop moves pEnd to point to the first byte that is not
116356 ** immediately preceded by a byte with the 0x80 bit set. Then increments
116357 ** pEnd once more so that it points to the byte immediately following the
116358 ** last byte in the position-list.
116360 while( *pEnd | c ){
116361 c = *pEnd++ & 0x80;
116362 testcase( c!=0 && (*pEnd)==0 );
116364 pEnd++; /* Advance past the POS_END terminator byte */
116366 if( pp ){
116367 int n = (int)(pEnd - *ppPoslist);
116368 char *p = *pp;
116369 memcpy(p, *ppPoslist, n);
116370 p += n;
116371 *pp = p;
116373 *ppPoslist = pEnd;
116377 ** When this function is called, *ppPoslist is assumed to point to the
116378 ** start of a column-list. After it returns, *ppPoslist points to the
116379 ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
116381 ** A column-list is list of delta-encoded positions for a single column
116382 ** within a single document within a doclist.
116384 ** The column-list is terminated either by a POS_COLUMN varint (1) or
116385 ** a POS_END varint (0). This routine leaves *ppPoslist pointing to
116386 ** the POS_COLUMN or POS_END that terminates the column-list.
116388 ** If pp is not NULL, then the contents of the column-list are copied
116389 ** to *pp. *pp is set to point to the first byte past the last byte copied
116390 ** before this function returns. The POS_COLUMN or POS_END terminator
116391 ** is not copied into *pp.
116393 static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
116394 char *pEnd = *ppPoslist;
116395 char c = 0;
116397 /* A column-list is terminated by either a 0x01 or 0x00 byte that is
116398 ** not part of a multi-byte varint.
116400 while( 0xFE & (*pEnd | c) ){
116401 c = *pEnd++ & 0x80;
116402 testcase( c!=0 && ((*pEnd)&0xfe)==0 );
116404 if( pp ){
116405 int n = (int)(pEnd - *ppPoslist);
116406 char *p = *pp;
116407 memcpy(p, *ppPoslist, n);
116408 p += n;
116409 *pp = p;
116411 *ppPoslist = pEnd;
116415 ** Value used to signify the end of an position-list. This is safe because
116416 ** it is not possible to have a document with 2^31 terms.
116418 #define POSITION_LIST_END 0x7fffffff
116421 ** This function is used to help parse position-lists. When this function is
116422 ** called, *pp may point to the start of the next varint in the position-list
116423 ** being parsed, or it may point to 1 byte past the end of the position-list
116424 ** (in which case **pp will be a terminator bytes POS_END (0) or
116425 ** (1)).
116427 ** If *pp points past the end of the current position-list, set *pi to
116428 ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
116429 ** increment the current value of *pi by the value read, and set *pp to
116430 ** point to the next value before returning.
116432 ** Before calling this routine *pi must be initialized to the value of
116433 ** the previous position, or zero if we are reading the first position
116434 ** in the position-list. Because positions are delta-encoded, the value
116435 ** of the previous position is needed in order to compute the value of
116436 ** the next position.
116438 static void fts3ReadNextPos(
116439 char **pp, /* IN/OUT: Pointer into position-list buffer */
116440 sqlite3_int64 *pi /* IN/OUT: Value read from position-list */
116442 if( (**pp)&0xFE ){
116443 fts3GetDeltaVarint(pp, pi);
116444 *pi -= 2;
116445 }else{
116446 *pi = POSITION_LIST_END;
116451 ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
116452 ** the value of iCol encoded as a varint to *pp. This will start a new
116453 ** column list.
116455 ** Set *pp to point to the byte just after the last byte written before
116456 ** returning (do not modify it if iCol==0). Return the total number of bytes
116457 ** written (0 if iCol==0).
116459 static int fts3PutColNumber(char **pp, int iCol){
116460 int n = 0; /* Number of bytes written */
116461 if( iCol ){
116462 char *p = *pp; /* Output pointer */
116463 n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
116464 *p = 0x01;
116465 *pp = &p[n];
116467 return n;
116471 ** Compute the union of two position lists. The output written
116472 ** into *pp contains all positions of both *pp1 and *pp2 in sorted
116473 ** order and with any duplicates removed. All pointers are
116474 ** updated appropriately. The caller is responsible for insuring
116475 ** that there is enough space in *pp to hold the complete output.
116477 static void fts3PoslistMerge(
116478 char **pp, /* Output buffer */
116479 char **pp1, /* Left input list */
116480 char **pp2 /* Right input list */
116482 char *p = *pp;
116483 char *p1 = *pp1;
116484 char *p2 = *pp2;
116486 while( *p1 || *p2 ){
116487 int iCol1; /* The current column index in pp1 */
116488 int iCol2; /* The current column index in pp2 */
116490 if( *p1==POS_COLUMN ) sqlite3Fts3GetVarint32(&p1[1], &iCol1);
116491 else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
116492 else iCol1 = 0;
116494 if( *p2==POS_COLUMN ) sqlite3Fts3GetVarint32(&p2[1], &iCol2);
116495 else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
116496 else iCol2 = 0;
116498 if( iCol1==iCol2 ){
116499 sqlite3_int64 i1 = 0; /* Last position from pp1 */
116500 sqlite3_int64 i2 = 0; /* Last position from pp2 */
116501 sqlite3_int64 iPrev = 0;
116502 int n = fts3PutColNumber(&p, iCol1);
116503 p1 += n;
116504 p2 += n;
116506 /* At this point, both p1 and p2 point to the start of column-lists
116507 ** for the same column (the column with index iCol1 and iCol2).
116508 ** A column-list is a list of non-negative delta-encoded varints, each
116509 ** incremented by 2 before being stored. Each list is terminated by a
116510 ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
116511 ** and writes the results to buffer p. p is left pointing to the byte
116512 ** after the list written. No terminator (POS_END or POS_COLUMN) is
116513 ** written to the output.
116515 fts3GetDeltaVarint(&p1, &i1);
116516 fts3GetDeltaVarint(&p2, &i2);
116518 fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
116519 iPrev -= 2;
116520 if( i1==i2 ){
116521 fts3ReadNextPos(&p1, &i1);
116522 fts3ReadNextPos(&p2, &i2);
116523 }else if( i1<i2 ){
116524 fts3ReadNextPos(&p1, &i1);
116525 }else{
116526 fts3ReadNextPos(&p2, &i2);
116528 }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
116529 }else if( iCol1<iCol2 ){
116530 p1 += fts3PutColNumber(&p, iCol1);
116531 fts3ColumnlistCopy(&p, &p1);
116532 }else{
116533 p2 += fts3PutColNumber(&p, iCol2);
116534 fts3ColumnlistCopy(&p, &p2);
116538 *p++ = POS_END;
116539 *pp = p;
116540 *pp1 = p1 + 1;
116541 *pp2 = p2 + 1;
116545 ** This function is used to merge two position lists into one. When it is
116546 ** called, *pp1 and *pp2 must both point to position lists. A position-list is
116547 ** the part of a doclist that follows each document id. For example, if a row
116548 ** contains:
116550 ** 'a b c'|'x y z'|'a b b a'
116552 ** Then the position list for this row for token 'b' would consist of:
116554 ** 0x02 0x01 0x02 0x03 0x03 0x00
116556 ** When this function returns, both *pp1 and *pp2 are left pointing to the
116557 ** byte following the 0x00 terminator of their respective position lists.
116559 ** If isSaveLeft is 0, an entry is added to the output position list for
116560 ** each position in *pp2 for which there exists one or more positions in
116561 ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
116562 ** when the *pp1 token appears before the *pp2 token, but not more than nToken
116563 ** slots before it.
116565 ** e.g. nToken==1 searches for adjacent positions.
116567 static int fts3PoslistPhraseMerge(
116568 char **pp, /* IN/OUT: Preallocated output buffer */
116569 int nToken, /* Maximum difference in token positions */
116570 int isSaveLeft, /* Save the left position */
116571 int isExact, /* If *pp1 is exactly nTokens before *pp2 */
116572 char **pp1, /* IN/OUT: Left input list */
116573 char **pp2 /* IN/OUT: Right input list */
116575 char *p = *pp;
116576 char *p1 = *pp1;
116577 char *p2 = *pp2;
116578 int iCol1 = 0;
116579 int iCol2 = 0;
116581 /* Never set both isSaveLeft and isExact for the same invocation. */
116582 assert( isSaveLeft==0 || isExact==0 );
116584 assert( p!=0 && *p1!=0 && *p2!=0 );
116585 if( *p1==POS_COLUMN ){
116586 p1++;
116587 p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
116589 if( *p2==POS_COLUMN ){
116590 p2++;
116591 p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
116594 while( 1 ){
116595 if( iCol1==iCol2 ){
116596 char *pSave = p;
116597 sqlite3_int64 iPrev = 0;
116598 sqlite3_int64 iPos1 = 0;
116599 sqlite3_int64 iPos2 = 0;
116601 if( iCol1 ){
116602 *p++ = POS_COLUMN;
116603 p += sqlite3Fts3PutVarint(p, iCol1);
116606 assert( *p1!=POS_END && *p1!=POS_COLUMN );
116607 assert( *p2!=POS_END && *p2!=POS_COLUMN );
116608 fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
116609 fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
116611 while( 1 ){
116612 if( iPos2==iPos1+nToken
116613 || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
116615 sqlite3_int64 iSave;
116616 iSave = isSaveLeft ? iPos1 : iPos2;
116617 fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
116618 pSave = 0;
116619 assert( p );
116621 if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
116622 if( (*p2&0xFE)==0 ) break;
116623 fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
116624 }else{
116625 if( (*p1&0xFE)==0 ) break;
116626 fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
116630 if( pSave ){
116631 assert( pp && p );
116632 p = pSave;
116635 fts3ColumnlistCopy(0, &p1);
116636 fts3ColumnlistCopy(0, &p2);
116637 assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
116638 if( 0==*p1 || 0==*p2 ) break;
116640 p1++;
116641 p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
116642 p2++;
116643 p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
116646 /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
116647 ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
116648 ** end of the position list, or the 0x01 that precedes the next
116649 ** column-number in the position list.
116651 else if( iCol1<iCol2 ){
116652 fts3ColumnlistCopy(0, &p1);
116653 if( 0==*p1 ) break;
116654 p1++;
116655 p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
116656 }else{
116657 fts3ColumnlistCopy(0, &p2);
116658 if( 0==*p2 ) break;
116659 p2++;
116660 p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
116664 fts3PoslistCopy(0, &p2);
116665 fts3PoslistCopy(0, &p1);
116666 *pp1 = p1;
116667 *pp2 = p2;
116668 if( *pp==p ){
116669 return 0;
116671 *p++ = 0x00;
116672 *pp = p;
116673 return 1;
116677 ** Merge two position-lists as required by the NEAR operator. The argument
116678 ** position lists correspond to the left and right phrases of an expression
116679 ** like:
116681 ** "phrase 1" NEAR "phrase number 2"
116683 ** Position list *pp1 corresponds to the left-hand side of the NEAR
116684 ** expression and *pp2 to the right. As usual, the indexes in the position
116685 ** lists are the offsets of the last token in each phrase (tokens "1" and "2"
116686 ** in the example above).
116688 ** The output position list - written to *pp - is a copy of *pp2 with those
116689 ** entries that are not sufficiently NEAR entries in *pp1 removed.
116691 static int fts3PoslistNearMerge(
116692 char **pp, /* Output buffer */
116693 char *aTmp, /* Temporary buffer space */
116694 int nRight, /* Maximum difference in token positions */
116695 int nLeft, /* Maximum difference in token positions */
116696 char **pp1, /* IN/OUT: Left input list */
116697 char **pp2 /* IN/OUT: Right input list */
116699 char *p1 = *pp1;
116700 char *p2 = *pp2;
116702 char *pTmp1 = aTmp;
116703 char *pTmp2;
116704 char *aTmp2;
116705 int res = 1;
116707 fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
116708 aTmp2 = pTmp2 = pTmp1;
116709 *pp1 = p1;
116710 *pp2 = p2;
116711 fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
116712 if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
116713 fts3PoslistMerge(pp, &aTmp, &aTmp2);
116714 }else if( pTmp1!=aTmp ){
116715 fts3PoslistCopy(pp, &aTmp);
116716 }else if( pTmp2!=aTmp2 ){
116717 fts3PoslistCopy(pp, &aTmp2);
116718 }else{
116719 res = 0;
116722 return res;
116726 ** An instance of this function is used to merge together the (potentially
116727 ** large number of) doclists for each term that matches a prefix query.
116728 ** See function fts3TermSelectMerge() for details.
116730 typedef struct TermSelect TermSelect;
116731 struct TermSelect {
116732 char *aaOutput[16]; /* Malloc'd output buffers */
116733 int anOutput[16]; /* Size each output buffer in bytes */
116737 ** This function is used to read a single varint from a buffer. Parameter
116738 ** pEnd points 1 byte past the end of the buffer. When this function is
116739 ** called, if *pp points to pEnd or greater, then the end of the buffer
116740 ** has been reached. In this case *pp is set to 0 and the function returns.
116742 ** If *pp does not point to or past pEnd, then a single varint is read
116743 ** from *pp. *pp is then set to point 1 byte past the end of the read varint.
116745 ** If bDescIdx is false, the value read is added to *pVal before returning.
116746 ** If it is true, the value read is subtracted from *pVal before this
116747 ** function returns.
116749 static void fts3GetDeltaVarint3(
116750 char **pp, /* IN/OUT: Point to read varint from */
116751 char *pEnd, /* End of buffer */
116752 int bDescIdx, /* True if docids are descending */
116753 sqlite3_int64 *pVal /* IN/OUT: Integer value */
116755 if( *pp>=pEnd ){
116756 *pp = 0;
116757 }else{
116758 sqlite3_int64 iVal;
116759 *pp += sqlite3Fts3GetVarint(*pp, &iVal);
116760 if( bDescIdx ){
116761 *pVal -= iVal;
116762 }else{
116763 *pVal += iVal;
116769 ** This function is used to write a single varint to a buffer. The varint
116770 ** is written to *pp. Before returning, *pp is set to point 1 byte past the
116771 ** end of the value written.
116773 ** If *pbFirst is zero when this function is called, the value written to
116774 ** the buffer is that of parameter iVal.
116776 ** If *pbFirst is non-zero when this function is called, then the value
116777 ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
116778 ** (if bDescIdx is non-zero).
116780 ** Before returning, this function always sets *pbFirst to 1 and *piPrev
116781 ** to the value of parameter iVal.
116783 static void fts3PutDeltaVarint3(
116784 char **pp, /* IN/OUT: Output pointer */
116785 int bDescIdx, /* True for descending docids */
116786 sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
116787 int *pbFirst, /* IN/OUT: True after first int written */
116788 sqlite3_int64 iVal /* Write this value to the list */
116790 sqlite3_int64 iWrite;
116791 if( bDescIdx==0 || *pbFirst==0 ){
116792 iWrite = iVal - *piPrev;
116793 }else{
116794 iWrite = *piPrev - iVal;
116796 assert( *pbFirst || *piPrev==0 );
116797 assert( *pbFirst==0 || iWrite>0 );
116798 *pp += sqlite3Fts3PutVarint(*pp, iWrite);
116799 *piPrev = iVal;
116800 *pbFirst = 1;
116805 ** This macro is used by various functions that merge doclists. The two
116806 ** arguments are 64-bit docid values. If the value of the stack variable
116807 ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
116808 ** Otherwise, (i2-i1).
116810 ** Using this makes it easier to write code that can merge doclists that are
116811 ** sorted in either ascending or descending order.
116813 #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
116816 ** This function does an "OR" merge of two doclists (output contains all
116817 ** positions contained in either argument doclist). If the docids in the
116818 ** input doclists are sorted in ascending order, parameter bDescDoclist
116819 ** should be false. If they are sorted in ascending order, it should be
116820 ** passed a non-zero value.
116822 ** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
116823 ** containing the output doclist and SQLITE_OK is returned. In this case
116824 ** *pnOut is set to the number of bytes in the output doclist.
116826 ** If an error occurs, an SQLite error code is returned. The output values
116827 ** are undefined in this case.
116829 static int fts3DoclistOrMerge(
116830 int bDescDoclist, /* True if arguments are desc */
116831 char *a1, int n1, /* First doclist */
116832 char *a2, int n2, /* Second doclist */
116833 char **paOut, int *pnOut /* OUT: Malloc'd doclist */
116835 sqlite3_int64 i1 = 0;
116836 sqlite3_int64 i2 = 0;
116837 sqlite3_int64 iPrev = 0;
116838 char *pEnd1 = &a1[n1];
116839 char *pEnd2 = &a2[n2];
116840 char *p1 = a1;
116841 char *p2 = a2;
116842 char *p;
116843 char *aOut;
116844 int bFirstOut = 0;
116846 *paOut = 0;
116847 *pnOut = 0;
116849 /* Allocate space for the output. Both the input and output doclists
116850 ** are delta encoded. If they are in ascending order (bDescDoclist==0),
116851 ** then the first docid in each list is simply encoded as a varint. For
116852 ** each subsequent docid, the varint stored is the difference between the
116853 ** current and previous docid (a positive number - since the list is in
116854 ** ascending order).
116856 ** The first docid written to the output is therefore encoded using the
116857 ** same number of bytes as it is in whichever of the input lists it is
116858 ** read from. And each subsequent docid read from the same input list
116859 ** consumes either the same or less bytes as it did in the input (since
116860 ** the difference between it and the previous value in the output must
116861 ** be a positive value less than or equal to the delta value read from
116862 ** the input list). The same argument applies to all but the first docid
116863 ** read from the 'other' list. And to the contents of all position lists
116864 ** that will be copied and merged from the input to the output.
116866 ** However, if the first docid copied to the output is a negative number,
116867 ** then the encoding of the first docid from the 'other' input list may
116868 ** be larger in the output than it was in the input (since the delta value
116869 ** may be a larger positive integer than the actual docid).
116871 ** The space required to store the output is therefore the sum of the
116872 ** sizes of the two inputs, plus enough space for exactly one of the input
116873 ** docids to grow.
116875 ** A symetric argument may be made if the doclists are in descending
116876 ** order.
116878 aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1);
116879 if( !aOut ) return SQLITE_NOMEM;
116881 p = aOut;
116882 fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
116883 fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
116884 while( p1 || p2 ){
116885 sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
116887 if( p2 && p1 && iDiff==0 ){
116888 fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
116889 fts3PoslistMerge(&p, &p1, &p2);
116890 fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
116891 fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
116892 }else if( !p2 || (p1 && iDiff<0) ){
116893 fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
116894 fts3PoslistCopy(&p, &p1);
116895 fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
116896 }else{
116897 fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
116898 fts3PoslistCopy(&p, &p2);
116899 fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
116903 *paOut = aOut;
116904 *pnOut = (p-aOut);
116905 assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
116906 return SQLITE_OK;
116910 ** This function does a "phrase" merge of two doclists. In a phrase merge,
116911 ** the output contains a copy of each position from the right-hand input
116912 ** doclist for which there is a position in the left-hand input doclist
116913 ** exactly nDist tokens before it.
116915 ** If the docids in the input doclists are sorted in ascending order,
116916 ** parameter bDescDoclist should be false. If they are sorted in ascending
116917 ** order, it should be passed a non-zero value.
116919 ** The right-hand input doclist is overwritten by this function.
116921 static void fts3DoclistPhraseMerge(
116922 int bDescDoclist, /* True if arguments are desc */
116923 int nDist, /* Distance from left to right (1=adjacent) */
116924 char *aLeft, int nLeft, /* Left doclist */
116925 char *aRight, int *pnRight /* IN/OUT: Right/output doclist */
116927 sqlite3_int64 i1 = 0;
116928 sqlite3_int64 i2 = 0;
116929 sqlite3_int64 iPrev = 0;
116930 char *pEnd1 = &aLeft[nLeft];
116931 char *pEnd2 = &aRight[*pnRight];
116932 char *p1 = aLeft;
116933 char *p2 = aRight;
116934 char *p;
116935 int bFirstOut = 0;
116936 char *aOut = aRight;
116938 assert( nDist>0 );
116940 p = aOut;
116941 fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
116942 fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
116944 while( p1 && p2 ){
116945 sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
116946 if( iDiff==0 ){
116947 char *pSave = p;
116948 sqlite3_int64 iPrevSave = iPrev;
116949 int bFirstOutSave = bFirstOut;
116951 fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
116952 if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
116953 p = pSave;
116954 iPrev = iPrevSave;
116955 bFirstOut = bFirstOutSave;
116957 fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
116958 fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
116959 }else if( iDiff<0 ){
116960 fts3PoslistCopy(0, &p1);
116961 fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
116962 }else{
116963 fts3PoslistCopy(0, &p2);
116964 fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
116968 *pnRight = p - aOut;
116972 ** Argument pList points to a position list nList bytes in size. This
116973 ** function checks to see if the position list contains any entries for
116974 ** a token in position 0 (of any column). If so, it writes argument iDelta
116975 ** to the output buffer pOut, followed by a position list consisting only
116976 ** of the entries from pList at position 0, and terminated by an 0x00 byte.
116977 ** The value returned is the number of bytes written to pOut (if any).
116979 SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
116980 sqlite3_int64 iDelta, /* Varint that may be written to pOut */
116981 char *pList, /* Position list (no 0x00 term) */
116982 int nList, /* Size of pList in bytes */
116983 char *pOut /* Write output here */
116985 int nOut = 0;
116986 int bWritten = 0; /* True once iDelta has been written */
116987 char *p = pList;
116988 char *pEnd = &pList[nList];
116990 if( *p!=0x01 ){
116991 if( *p==0x02 ){
116992 nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
116993 pOut[nOut++] = 0x02;
116994 bWritten = 1;
116996 fts3ColumnlistCopy(0, &p);
116999 while( p<pEnd && *p==0x01 ){
117000 sqlite3_int64 iCol;
117002 p += sqlite3Fts3GetVarint(p, &iCol);
117003 if( *p==0x02 ){
117004 if( bWritten==0 ){
117005 nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
117006 bWritten = 1;
117008 pOut[nOut++] = 0x01;
117009 nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
117010 pOut[nOut++] = 0x02;
117012 fts3ColumnlistCopy(0, &p);
117014 if( bWritten ){
117015 pOut[nOut++] = 0x00;
117018 return nOut;
117023 ** Merge all doclists in the TermSelect.aaOutput[] array into a single
117024 ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
117025 ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
117027 ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
117028 ** the responsibility of the caller to free any doclists left in the
117029 ** TermSelect.aaOutput[] array.
117031 static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
117032 char *aOut = 0;
117033 int nOut = 0;
117034 int i;
117036 /* Loop through the doclists in the aaOutput[] array. Merge them all
117037 ** into a single doclist.
117039 for(i=0; i<SizeofArray(pTS->aaOutput); i++){
117040 if( pTS->aaOutput[i] ){
117041 if( !aOut ){
117042 aOut = pTS->aaOutput[i];
117043 nOut = pTS->anOutput[i];
117044 pTS->aaOutput[i] = 0;
117045 }else{
117046 int nNew;
117047 char *aNew;
117049 int rc = fts3DoclistOrMerge(p->bDescIdx,
117050 pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
117052 if( rc!=SQLITE_OK ){
117053 sqlite3_free(aOut);
117054 return rc;
117057 sqlite3_free(pTS->aaOutput[i]);
117058 sqlite3_free(aOut);
117059 pTS->aaOutput[i] = 0;
117060 aOut = aNew;
117061 nOut = nNew;
117066 pTS->aaOutput[0] = aOut;
117067 pTS->anOutput[0] = nOut;
117068 return SQLITE_OK;
117072 ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
117073 ** as the first argument. The merge is an "OR" merge (see function
117074 ** fts3DoclistOrMerge() for details).
117076 ** This function is called with the doclist for each term that matches
117077 ** a queried prefix. It merges all these doclists into one, the doclist
117078 ** for the specified prefix. Since there can be a very large number of
117079 ** doclists to merge, the merging is done pair-wise using the TermSelect
117080 ** object.
117082 ** This function returns SQLITE_OK if the merge is successful, or an
117083 ** SQLite error code (SQLITE_NOMEM) if an error occurs.
117085 static int fts3TermSelectMerge(
117086 Fts3Table *p, /* FTS table handle */
117087 TermSelect *pTS, /* TermSelect object to merge into */
117088 char *aDoclist, /* Pointer to doclist */
117089 int nDoclist /* Size of aDoclist in bytes */
117091 if( pTS->aaOutput[0]==0 ){
117092 /* If this is the first term selected, copy the doclist to the output
117093 ** buffer using memcpy(). */
117094 pTS->aaOutput[0] = sqlite3_malloc(nDoclist);
117095 pTS->anOutput[0] = nDoclist;
117096 if( pTS->aaOutput[0] ){
117097 memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
117098 }else{
117099 return SQLITE_NOMEM;
117101 }else{
117102 char *aMerge = aDoclist;
117103 int nMerge = nDoclist;
117104 int iOut;
117106 for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
117107 if( pTS->aaOutput[iOut]==0 ){
117108 assert( iOut>0 );
117109 pTS->aaOutput[iOut] = aMerge;
117110 pTS->anOutput[iOut] = nMerge;
117111 break;
117112 }else{
117113 char *aNew;
117114 int nNew;
117116 int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge,
117117 pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
117119 if( rc!=SQLITE_OK ){
117120 if( aMerge!=aDoclist ) sqlite3_free(aMerge);
117121 return rc;
117124 if( aMerge!=aDoclist ) sqlite3_free(aMerge);
117125 sqlite3_free(pTS->aaOutput[iOut]);
117126 pTS->aaOutput[iOut] = 0;
117128 aMerge = aNew;
117129 nMerge = nNew;
117130 if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
117131 pTS->aaOutput[iOut] = aMerge;
117132 pTS->anOutput[iOut] = nMerge;
117137 return SQLITE_OK;
117141 ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
117143 static int fts3SegReaderCursorAppend(
117144 Fts3MultiSegReader *pCsr,
117145 Fts3SegReader *pNew
117147 if( (pCsr->nSegment%16)==0 ){
117148 Fts3SegReader **apNew;
117149 int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
117150 apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
117151 if( !apNew ){
117152 sqlite3Fts3SegReaderFree(pNew);
117153 return SQLITE_NOMEM;
117155 pCsr->apSegment = apNew;
117157 pCsr->apSegment[pCsr->nSegment++] = pNew;
117158 return SQLITE_OK;
117162 ** Add seg-reader objects to the Fts3MultiSegReader object passed as the
117163 ** 8th argument.
117165 ** This function returns SQLITE_OK if successful, or an SQLite error code
117166 ** otherwise.
117168 static int fts3SegReaderCursor(
117169 Fts3Table *p, /* FTS3 table handle */
117170 int iIndex, /* Index to search (from 0 to p->nIndex-1) */
117171 int iLevel, /* Level of segments to scan */
117172 const char *zTerm, /* Term to query for */
117173 int nTerm, /* Size of zTerm in bytes */
117174 int isPrefix, /* True for a prefix search */
117175 int isScan, /* True to scan from zTerm to EOF */
117176 Fts3MultiSegReader *pCsr /* Cursor object to populate */
117178 int rc = SQLITE_OK; /* Error code */
117179 sqlite3_stmt *pStmt = 0; /* Statement to iterate through segments */
117180 int rc2; /* Result of sqlite3_reset() */
117182 /* If iLevel is less than 0 and this is not a scan, include a seg-reader
117183 ** for the pending-terms. If this is a scan, then this call must be being
117184 ** made by an fts4aux module, not an FTS table. In this case calling
117185 ** Fts3SegReaderPending might segfault, as the data structures used by
117186 ** fts4aux are not completely populated. So it's easiest to filter these
117187 ** calls out here. */
117188 if( iLevel<0 && p->aIndex ){
117189 Fts3SegReader *pSeg = 0;
117190 rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix, &pSeg);
117191 if( rc==SQLITE_OK && pSeg ){
117192 rc = fts3SegReaderCursorAppend(pCsr, pSeg);
117196 if( iLevel!=FTS3_SEGCURSOR_PENDING ){
117197 if( rc==SQLITE_OK ){
117198 rc = sqlite3Fts3AllSegdirs(p, iIndex, iLevel, &pStmt);
117201 while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
117202 Fts3SegReader *pSeg = 0;
117204 /* Read the values returned by the SELECT into local variables. */
117205 sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
117206 sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
117207 sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
117208 int nRoot = sqlite3_column_bytes(pStmt, 4);
117209 char const *zRoot = sqlite3_column_blob(pStmt, 4);
117211 /* If zTerm is not NULL, and this segment is not stored entirely on its
117212 ** root node, the range of leaves scanned can be reduced. Do this. */
117213 if( iStartBlock && zTerm ){
117214 sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
117215 rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
117216 if( rc!=SQLITE_OK ) goto finished;
117217 if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
117220 rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1,
117221 iStartBlock, iLeavesEndBlock, iEndBlock, zRoot, nRoot, &pSeg
117223 if( rc!=SQLITE_OK ) goto finished;
117224 rc = fts3SegReaderCursorAppend(pCsr, pSeg);
117228 finished:
117229 rc2 = sqlite3_reset(pStmt);
117230 if( rc==SQLITE_DONE ) rc = rc2;
117232 return rc;
117236 ** Set up a cursor object for iterating through a full-text index or a
117237 ** single level therein.
117239 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
117240 Fts3Table *p, /* FTS3 table handle */
117241 int iIndex, /* Index to search (from 0 to p->nIndex-1) */
117242 int iLevel, /* Level of segments to scan */
117243 const char *zTerm, /* Term to query for */
117244 int nTerm, /* Size of zTerm in bytes */
117245 int isPrefix, /* True for a prefix search */
117246 int isScan, /* True to scan from zTerm to EOF */
117247 Fts3MultiSegReader *pCsr /* Cursor object to populate */
117249 assert( iIndex>=0 && iIndex<p->nIndex );
117250 assert( iLevel==FTS3_SEGCURSOR_ALL
117251 || iLevel==FTS3_SEGCURSOR_PENDING
117252 || iLevel>=0
117254 assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
117255 assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
117256 assert( isPrefix==0 || isScan==0 );
117258 /* "isScan" is only set to true by the ft4aux module, an ordinary
117259 ** full-text tables. */
117260 assert( isScan==0 || p->aIndex==0 );
117262 memset(pCsr, 0, sizeof(Fts3MultiSegReader));
117264 return fts3SegReaderCursor(
117265 p, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
117270 ** In addition to its current configuration, have the Fts3MultiSegReader
117271 ** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
117273 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
117275 static int fts3SegReaderCursorAddZero(
117276 Fts3Table *p, /* FTS virtual table handle */
117277 const char *zTerm, /* Term to scan doclist of */
117278 int nTerm, /* Number of bytes in zTerm */
117279 Fts3MultiSegReader *pCsr /* Fts3MultiSegReader to modify */
117281 return fts3SegReaderCursor(p, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr);
117285 ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
117286 ** if isPrefix is true, to scan the doclist for all terms for which
117287 ** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
117288 ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
117289 ** an SQLite error code.
117291 ** It is the responsibility of the caller to free this object by eventually
117292 ** passing it to fts3SegReaderCursorFree()
117294 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
117295 ** Output parameter *ppSegcsr is set to 0 if an error occurs.
117297 static int fts3TermSegReaderCursor(
117298 Fts3Cursor *pCsr, /* Virtual table cursor handle */
117299 const char *zTerm, /* Term to query for */
117300 int nTerm, /* Size of zTerm in bytes */
117301 int isPrefix, /* True for a prefix search */
117302 Fts3MultiSegReader **ppSegcsr /* OUT: Allocated seg-reader cursor */
117304 Fts3MultiSegReader *pSegcsr; /* Object to allocate and return */
117305 int rc = SQLITE_NOMEM; /* Return code */
117307 pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
117308 if( pSegcsr ){
117309 int i;
117310 int bFound = 0; /* True once an index has been found */
117311 Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
117313 if( isPrefix ){
117314 for(i=1; bFound==0 && i<p->nIndex; i++){
117315 if( p->aIndex[i].nPrefix==nTerm ){
117316 bFound = 1;
117317 rc = sqlite3Fts3SegReaderCursor(
117318 p, i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr);
117319 pSegcsr->bLookup = 1;
117323 for(i=1; bFound==0 && i<p->nIndex; i++){
117324 if( p->aIndex[i].nPrefix==nTerm+1 ){
117325 bFound = 1;
117326 rc = sqlite3Fts3SegReaderCursor(
117327 p, i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
117329 if( rc==SQLITE_OK ){
117330 rc = fts3SegReaderCursorAddZero(p, zTerm, nTerm, pSegcsr);
117336 if( bFound==0 ){
117337 rc = sqlite3Fts3SegReaderCursor(
117338 p, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
117340 pSegcsr->bLookup = !isPrefix;
117344 *ppSegcsr = pSegcsr;
117345 return rc;
117349 ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
117351 static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
117352 sqlite3Fts3SegReaderFinish(pSegcsr);
117353 sqlite3_free(pSegcsr);
117357 ** This function retreives the doclist for the specified term (or term
117358 ** prefix) from the database.
117360 static int fts3TermSelect(
117361 Fts3Table *p, /* Virtual table handle */
117362 Fts3PhraseToken *pTok, /* Token to query for */
117363 int iColumn, /* Column to query (or -ve for all columns) */
117364 int *pnOut, /* OUT: Size of buffer at *ppOut */
117365 char **ppOut /* OUT: Malloced result buffer */
117367 int rc; /* Return code */
117368 Fts3MultiSegReader *pSegcsr; /* Seg-reader cursor for this term */
117369 TermSelect tsc; /* Object for pair-wise doclist merging */
117370 Fts3SegFilter filter; /* Segment term filter configuration */
117372 pSegcsr = pTok->pSegcsr;
117373 memset(&tsc, 0, sizeof(TermSelect));
117375 filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
117376 | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
117377 | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
117378 | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
117379 filter.iCol = iColumn;
117380 filter.zTerm = pTok->z;
117381 filter.nTerm = pTok->n;
117383 rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
117384 while( SQLITE_OK==rc
117385 && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
117387 rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
117390 if( rc==SQLITE_OK ){
117391 rc = fts3TermSelectFinishMerge(p, &tsc);
117393 if( rc==SQLITE_OK ){
117394 *ppOut = tsc.aaOutput[0];
117395 *pnOut = tsc.anOutput[0];
117396 }else{
117397 int i;
117398 for(i=0; i<SizeofArray(tsc.aaOutput); i++){
117399 sqlite3_free(tsc.aaOutput[i]);
117403 fts3SegReaderCursorFree(pSegcsr);
117404 pTok->pSegcsr = 0;
117405 return rc;
117409 ** This function counts the total number of docids in the doclist stored
117410 ** in buffer aList[], size nList bytes.
117412 ** If the isPoslist argument is true, then it is assumed that the doclist
117413 ** contains a position-list following each docid. Otherwise, it is assumed
117414 ** that the doclist is simply a list of docids stored as delta encoded
117415 ** varints.
117417 static int fts3DoclistCountDocids(char *aList, int nList){
117418 int nDoc = 0; /* Return value */
117419 if( aList ){
117420 char *aEnd = &aList[nList]; /* Pointer to one byte after EOF */
117421 char *p = aList; /* Cursor */
117422 while( p<aEnd ){
117423 nDoc++;
117424 while( (*p++)&0x80 ); /* Skip docid varint */
117425 fts3PoslistCopy(0, &p); /* Skip over position list */
117429 return nDoc;
117433 ** Advance the cursor to the next row in the %_content table that
117434 ** matches the search criteria. For a MATCH search, this will be
117435 ** the next row that matches. For a full-table scan, this will be
117436 ** simply the next row in the %_content table. For a docid lookup,
117437 ** this routine simply sets the EOF flag.
117439 ** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned
117440 ** even if we reach end-of-file. The fts3EofMethod() will be called
117441 ** subsequently to determine whether or not an EOF was hit.
117443 static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
117444 int rc;
117445 Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
117446 if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
117447 if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
117448 pCsr->isEof = 1;
117449 rc = sqlite3_reset(pCsr->pStmt);
117450 }else{
117451 pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
117452 rc = SQLITE_OK;
117454 }else{
117455 rc = fts3EvalNext((Fts3Cursor *)pCursor);
117457 assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
117458 return rc;
117462 ** This is the xFilter interface for the virtual table. See
117463 ** the virtual table xFilter method documentation for additional
117464 ** information.
117466 ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
117467 ** the %_content table.
117469 ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
117470 ** in the %_content table.
117472 ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index. The
117473 ** column on the left-hand side of the MATCH operator is column
117474 ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed. argv[0] is the right-hand
117475 ** side of the MATCH operator.
117477 static int fts3FilterMethod(
117478 sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
117479 int idxNum, /* Strategy index */
117480 const char *idxStr, /* Unused */
117481 int nVal, /* Number of elements in apVal */
117482 sqlite3_value **apVal /* Arguments for the indexing scheme */
117484 int rc;
117485 char *zSql; /* SQL statement used to access %_content */
117486 Fts3Table *p = (Fts3Table *)pCursor->pVtab;
117487 Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
117489 UNUSED_PARAMETER(idxStr);
117490 UNUSED_PARAMETER(nVal);
117492 assert( idxNum>=0 && idxNum<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
117493 assert( nVal==0 || nVal==1 );
117494 assert( (nVal==0)==(idxNum==FTS3_FULLSCAN_SEARCH) );
117495 assert( p->pSegments==0 );
117497 /* In case the cursor has been used before, clear it now. */
117498 sqlite3_finalize(pCsr->pStmt);
117499 sqlite3_free(pCsr->aDoclist);
117500 sqlite3Fts3ExprFree(pCsr->pExpr);
117501 memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
117503 if( idxStr ){
117504 pCsr->bDesc = (idxStr[0]=='D');
117505 }else{
117506 pCsr->bDesc = p->bDescIdx;
117508 pCsr->eSearch = (i16)idxNum;
117510 if( idxNum!=FTS3_DOCID_SEARCH && idxNum!=FTS3_FULLSCAN_SEARCH ){
117511 int iCol = idxNum-FTS3_FULLTEXT_SEARCH;
117512 const char *zQuery = (const char *)sqlite3_value_text(apVal[0]);
117514 if( zQuery==0 && sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
117515 return SQLITE_NOMEM;
117518 rc = sqlite3Fts3ExprParse(p->pTokenizer, p->azColumn, p->bHasStat,
117519 p->nColumn, iCol, zQuery, -1, &pCsr->pExpr
117521 if( rc!=SQLITE_OK ){
117522 if( rc==SQLITE_ERROR ){
117523 static const char *zErr = "malformed MATCH expression: [%s]";
117524 p->base.zErrMsg = sqlite3_mprintf(zErr, zQuery);
117526 return rc;
117529 rc = sqlite3Fts3ReadLock(p);
117530 if( rc!=SQLITE_OK ) return rc;
117532 rc = fts3EvalStart(pCsr);
117534 sqlite3Fts3SegmentsClose(p);
117535 if( rc!=SQLITE_OK ) return rc;
117536 pCsr->pNextId = pCsr->aDoclist;
117537 pCsr->iPrevId = 0;
117540 /* Compile a SELECT statement for this cursor. For a full-table-scan, the
117541 ** statement loops through all rows of the %_content table. For a
117542 ** full-text query or docid lookup, the statement retrieves a single
117543 ** row by docid.
117545 if( idxNum==FTS3_FULLSCAN_SEARCH ){
117546 zSql = sqlite3_mprintf(
117547 "SELECT %s ORDER BY rowid %s",
117548 p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
117550 if( zSql ){
117551 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
117552 sqlite3_free(zSql);
117553 }else{
117554 rc = SQLITE_NOMEM;
117556 }else if( idxNum==FTS3_DOCID_SEARCH ){
117557 rc = fts3CursorSeekStmt(pCsr, &pCsr->pStmt);
117558 if( rc==SQLITE_OK ){
117559 rc = sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
117562 if( rc!=SQLITE_OK ) return rc;
117564 return fts3NextMethod(pCursor);
117568 ** This is the xEof method of the virtual table. SQLite calls this
117569 ** routine to find out if it has reached the end of a result set.
117571 static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
117572 return ((Fts3Cursor *)pCursor)->isEof;
117576 ** This is the xRowid method. The SQLite core calls this routine to
117577 ** retrieve the rowid for the current row of the result set. fts3
117578 ** exposes %_content.docid as the rowid for the virtual table. The
117579 ** rowid should be written to *pRowid.
117581 static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
117582 Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
117583 *pRowid = pCsr->iPrevId;
117584 return SQLITE_OK;
117588 ** This is the xColumn method, called by SQLite to request a value from
117589 ** the row that the supplied cursor currently points to.
117591 static int fts3ColumnMethod(
117592 sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
117593 sqlite3_context *pContext, /* Context for sqlite3_result_xxx() calls */
117594 int iCol /* Index of column to read value from */
117596 int rc = SQLITE_OK; /* Return Code */
117597 Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
117598 Fts3Table *p = (Fts3Table *)pCursor->pVtab;
117600 /* The column value supplied by SQLite must be in range. */
117601 assert( iCol>=0 && iCol<=p->nColumn+1 );
117603 if( iCol==p->nColumn+1 ){
117604 /* This call is a request for the "docid" column. Since "docid" is an
117605 ** alias for "rowid", use the xRowid() method to obtain the value.
117607 sqlite3_result_int64(pContext, pCsr->iPrevId);
117608 }else if( iCol==p->nColumn ){
117609 /* The extra column whose name is the same as the table.
117610 ** Return a blob which is a pointer to the cursor.
117612 sqlite3_result_blob(pContext, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
117613 }else{
117614 rc = fts3CursorSeek(0, pCsr);
117615 if( rc==SQLITE_OK && sqlite3_data_count(pCsr->pStmt)>(iCol+1) ){
117616 sqlite3_result_value(pContext, sqlite3_column_value(pCsr->pStmt, iCol+1));
117620 assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
117621 return rc;
117625 ** This function is the implementation of the xUpdate callback used by
117626 ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
117627 ** inserted, updated or deleted.
117629 static int fts3UpdateMethod(
117630 sqlite3_vtab *pVtab, /* Virtual table handle */
117631 int nArg, /* Size of argument array */
117632 sqlite3_value **apVal, /* Array of arguments */
117633 sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
117635 return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
117639 ** Implementation of xSync() method. Flush the contents of the pending-terms
117640 ** hash-table to the database.
117642 static int fts3SyncMethod(sqlite3_vtab *pVtab){
117643 int rc = sqlite3Fts3PendingTermsFlush((Fts3Table *)pVtab);
117644 sqlite3Fts3SegmentsClose((Fts3Table *)pVtab);
117645 return rc;
117649 ** Implementation of xBegin() method. This is a no-op.
117651 static int fts3BeginMethod(sqlite3_vtab *pVtab){
117652 TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
117653 UNUSED_PARAMETER(pVtab);
117654 assert( p->pSegments==0 );
117655 assert( p->nPendingData==0 );
117656 assert( p->inTransaction!=1 );
117657 TESTONLY( p->inTransaction = 1 );
117658 TESTONLY( p->mxSavepoint = -1; );
117659 return SQLITE_OK;
117663 ** Implementation of xCommit() method. This is a no-op. The contents of
117664 ** the pending-terms hash-table have already been flushed into the database
117665 ** by fts3SyncMethod().
117667 static int fts3CommitMethod(sqlite3_vtab *pVtab){
117668 TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
117669 UNUSED_PARAMETER(pVtab);
117670 assert( p->nPendingData==0 );
117671 assert( p->inTransaction!=0 );
117672 assert( p->pSegments==0 );
117673 TESTONLY( p->inTransaction = 0 );
117674 TESTONLY( p->mxSavepoint = -1; );
117675 return SQLITE_OK;
117679 ** Implementation of xRollback(). Discard the contents of the pending-terms
117680 ** hash-table. Any changes made to the database are reverted by SQLite.
117682 static int fts3RollbackMethod(sqlite3_vtab *pVtab){
117683 Fts3Table *p = (Fts3Table*)pVtab;
117684 sqlite3Fts3PendingTermsClear(p);
117685 assert( p->inTransaction!=0 );
117686 TESTONLY( p->inTransaction = 0 );
117687 TESTONLY( p->mxSavepoint = -1; );
117688 return SQLITE_OK;
117692 ** When called, *ppPoslist must point to the byte immediately following the
117693 ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
117694 ** moves *ppPoslist so that it instead points to the first byte of the
117695 ** same position list.
117697 static void fts3ReversePoslist(char *pStart, char **ppPoslist){
117698 char *p = &(*ppPoslist)[-2];
117699 char c = 0;
117701 while( p>pStart && (c=*p--)==0 );
117702 while( p>pStart && (*p & 0x80) | c ){
117703 c = *p--;
117705 if( p>pStart ){ p = &p[2]; }
117706 while( *p++&0x80 );
117707 *ppPoslist = p;
117711 ** Helper function used by the implementation of the overloaded snippet(),
117712 ** offsets() and optimize() SQL functions.
117714 ** If the value passed as the third argument is a blob of size
117715 ** sizeof(Fts3Cursor*), then the blob contents are copied to the
117716 ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
117717 ** message is written to context pContext and SQLITE_ERROR returned. The
117718 ** string passed via zFunc is used as part of the error message.
117720 static int fts3FunctionArg(
117721 sqlite3_context *pContext, /* SQL function call context */
117722 const char *zFunc, /* Function name */
117723 sqlite3_value *pVal, /* argv[0] passed to function */
117724 Fts3Cursor **ppCsr /* OUT: Store cursor handle here */
117726 Fts3Cursor *pRet;
117727 if( sqlite3_value_type(pVal)!=SQLITE_BLOB
117728 || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
117730 char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
117731 sqlite3_result_error(pContext, zErr, -1);
117732 sqlite3_free(zErr);
117733 return SQLITE_ERROR;
117735 memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
117736 *ppCsr = pRet;
117737 return SQLITE_OK;
117741 ** Implementation of the snippet() function for FTS3
117743 static void fts3SnippetFunc(
117744 sqlite3_context *pContext, /* SQLite function call context */
117745 int nVal, /* Size of apVal[] array */
117746 sqlite3_value **apVal /* Array of arguments */
117748 Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
117749 const char *zStart = "<b>";
117750 const char *zEnd = "</b>";
117751 const char *zEllipsis = "<b>...</b>";
117752 int iCol = -1;
117753 int nToken = 15; /* Default number of tokens in snippet */
117755 /* There must be at least one argument passed to this function (otherwise
117756 ** the non-overloaded version would have been called instead of this one).
117758 assert( nVal>=1 );
117760 if( nVal>6 ){
117761 sqlite3_result_error(pContext,
117762 "wrong number of arguments to function snippet()", -1);
117763 return;
117765 if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
117767 switch( nVal ){
117768 case 6: nToken = sqlite3_value_int(apVal[5]);
117769 case 5: iCol = sqlite3_value_int(apVal[4]);
117770 case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
117771 case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
117772 case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
117774 if( !zEllipsis || !zEnd || !zStart ){
117775 sqlite3_result_error_nomem(pContext);
117776 }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
117777 sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
117782 ** Implementation of the offsets() function for FTS3
117784 static void fts3OffsetsFunc(
117785 sqlite3_context *pContext, /* SQLite function call context */
117786 int nVal, /* Size of argument array */
117787 sqlite3_value **apVal /* Array of arguments */
117789 Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
117791 UNUSED_PARAMETER(nVal);
117793 assert( nVal==1 );
117794 if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
117795 assert( pCsr );
117796 if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
117797 sqlite3Fts3Offsets(pContext, pCsr);
117802 ** Implementation of the special optimize() function for FTS3. This
117803 ** function merges all segments in the database to a single segment.
117804 ** Example usage is:
117806 ** SELECT optimize(t) FROM t LIMIT 1;
117808 ** where 't' is the name of an FTS3 table.
117810 static void fts3OptimizeFunc(
117811 sqlite3_context *pContext, /* SQLite function call context */
117812 int nVal, /* Size of argument array */
117813 sqlite3_value **apVal /* Array of arguments */
117815 int rc; /* Return code */
117816 Fts3Table *p; /* Virtual table handle */
117817 Fts3Cursor *pCursor; /* Cursor handle passed through apVal[0] */
117819 UNUSED_PARAMETER(nVal);
117821 assert( nVal==1 );
117822 if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
117823 p = (Fts3Table *)pCursor->base.pVtab;
117824 assert( p );
117826 rc = sqlite3Fts3Optimize(p);
117828 switch( rc ){
117829 case SQLITE_OK:
117830 sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
117831 break;
117832 case SQLITE_DONE:
117833 sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
117834 break;
117835 default:
117836 sqlite3_result_error_code(pContext, rc);
117837 break;
117842 ** Implementation of the matchinfo() function for FTS3
117844 static void fts3MatchinfoFunc(
117845 sqlite3_context *pContext, /* SQLite function call context */
117846 int nVal, /* Size of argument array */
117847 sqlite3_value **apVal /* Array of arguments */
117849 Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
117850 assert( nVal==1 || nVal==2 );
117851 if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
117852 const char *zArg = 0;
117853 if( nVal>1 ){
117854 zArg = (const char *)sqlite3_value_text(apVal[1]);
117856 sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
117861 ** This routine implements the xFindFunction method for the FTS3
117862 ** virtual table.
117864 static int fts3FindFunctionMethod(
117865 sqlite3_vtab *pVtab, /* Virtual table handle */
117866 int nArg, /* Number of SQL function arguments */
117867 const char *zName, /* Name of SQL function */
117868 void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
117869 void **ppArg /* Unused */
117871 struct Overloaded {
117872 const char *zName;
117873 void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
117874 } aOverload[] = {
117875 { "snippet", fts3SnippetFunc },
117876 { "offsets", fts3OffsetsFunc },
117877 { "optimize", fts3OptimizeFunc },
117878 { "matchinfo", fts3MatchinfoFunc },
117880 int i; /* Iterator variable */
117882 UNUSED_PARAMETER(pVtab);
117883 UNUSED_PARAMETER(nArg);
117884 UNUSED_PARAMETER(ppArg);
117886 for(i=0; i<SizeofArray(aOverload); i++){
117887 if( strcmp(zName, aOverload[i].zName)==0 ){
117888 *pxFunc = aOverload[i].xFunc;
117889 return 1;
117893 /* No function of the specified name was found. Return 0. */
117894 return 0;
117898 ** Implementation of FTS3 xRename method. Rename an fts3 table.
117900 static int fts3RenameMethod(
117901 sqlite3_vtab *pVtab, /* Virtual table handle */
117902 const char *zName /* New name of table */
117904 Fts3Table *p = (Fts3Table *)pVtab;
117905 sqlite3 *db = p->db; /* Database connection */
117906 int rc; /* Return Code */
117908 /* As it happens, the pending terms table is always empty here. This is
117909 ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction
117910 ** always opens a savepoint transaction. And the xSavepoint() method
117911 ** flushes the pending terms table. But leave the (no-op) call to
117912 ** PendingTermsFlush() in in case that changes.
117914 assert( p->nPendingData==0 );
117915 rc = sqlite3Fts3PendingTermsFlush(p);
117917 if( p->zContentTbl==0 ){
117918 fts3DbExec(&rc, db,
117919 "ALTER TABLE %Q.'%q_content' RENAME TO '%q_content';",
117920 p->zDb, p->zName, zName
117924 if( p->bHasDocsize ){
117925 fts3DbExec(&rc, db,
117926 "ALTER TABLE %Q.'%q_docsize' RENAME TO '%q_docsize';",
117927 p->zDb, p->zName, zName
117930 if( p->bHasStat ){
117931 fts3DbExec(&rc, db,
117932 "ALTER TABLE %Q.'%q_stat' RENAME TO '%q_stat';",
117933 p->zDb, p->zName, zName
117936 fts3DbExec(&rc, db,
117937 "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
117938 p->zDb, p->zName, zName
117940 fts3DbExec(&rc, db,
117941 "ALTER TABLE %Q.'%q_segdir' RENAME TO '%q_segdir';",
117942 p->zDb, p->zName, zName
117944 return rc;
117948 ** The xSavepoint() method.
117950 ** Flush the contents of the pending-terms table to disk.
117952 static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
117953 UNUSED_PARAMETER(iSavepoint);
117954 assert( ((Fts3Table *)pVtab)->inTransaction );
117955 assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
117956 TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
117957 return fts3SyncMethod(pVtab);
117961 ** The xRelease() method.
117963 ** This is a no-op.
117965 static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
117966 TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
117967 UNUSED_PARAMETER(iSavepoint);
117968 UNUSED_PARAMETER(pVtab);
117969 assert( p->inTransaction );
117970 assert( p->mxSavepoint >= iSavepoint );
117971 TESTONLY( p->mxSavepoint = iSavepoint-1 );
117972 return SQLITE_OK;
117976 ** The xRollbackTo() method.
117978 ** Discard the contents of the pending terms table.
117980 static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
117981 Fts3Table *p = (Fts3Table*)pVtab;
117982 UNUSED_PARAMETER(iSavepoint);
117983 assert( p->inTransaction );
117984 assert( p->mxSavepoint >= iSavepoint );
117985 TESTONLY( p->mxSavepoint = iSavepoint );
117986 sqlite3Fts3PendingTermsClear(p);
117987 return SQLITE_OK;
117990 static const sqlite3_module fts3Module = {
117991 /* iVersion */ 2,
117992 /* xCreate */ fts3CreateMethod,
117993 /* xConnect */ fts3ConnectMethod,
117994 /* xBestIndex */ fts3BestIndexMethod,
117995 /* xDisconnect */ fts3DisconnectMethod,
117996 /* xDestroy */ fts3DestroyMethod,
117997 /* xOpen */ fts3OpenMethod,
117998 /* xClose */ fts3CloseMethod,
117999 /* xFilter */ fts3FilterMethod,
118000 /* xNext */ fts3NextMethod,
118001 /* xEof */ fts3EofMethod,
118002 /* xColumn */ fts3ColumnMethod,
118003 /* xRowid */ fts3RowidMethod,
118004 /* xUpdate */ fts3UpdateMethod,
118005 /* xBegin */ fts3BeginMethod,
118006 /* xSync */ fts3SyncMethod,
118007 /* xCommit */ fts3CommitMethod,
118008 /* xRollback */ fts3RollbackMethod,
118009 /* xFindFunction */ fts3FindFunctionMethod,
118010 /* xRename */ fts3RenameMethod,
118011 /* xSavepoint */ fts3SavepointMethod,
118012 /* xRelease */ fts3ReleaseMethod,
118013 /* xRollbackTo */ fts3RollbackToMethod,
118017 ** This function is registered as the module destructor (called when an
118018 ** FTS3 enabled database connection is closed). It frees the memory
118019 ** allocated for the tokenizer hash table.
118021 static void hashDestroy(void *p){
118022 Fts3Hash *pHash = (Fts3Hash *)p;
118023 sqlite3Fts3HashClear(pHash);
118024 sqlite3_free(pHash);
118028 ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
118029 ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
118030 ** respectively. The following three forward declarations are for functions
118031 ** declared in these files used to retrieve the respective implementations.
118033 ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
118034 ** to by the argument to point to the "simple" tokenizer implementation.
118035 ** And so on.
118037 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
118038 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
118039 #ifdef SQLITE_ENABLE_ICU
118040 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
118041 #endif
118044 ** Initialise the fts3 extension. If this extension is built as part
118045 ** of the sqlite library, then this function is called directly by
118046 ** SQLite. If fts3 is built as a dynamically loadable extension, this
118047 ** function is called by the sqlite3_extension_init() entry point.
118049 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
118050 int rc = SQLITE_OK;
118051 Fts3Hash *pHash = 0;
118052 const sqlite3_tokenizer_module *pSimple = 0;
118053 const sqlite3_tokenizer_module *pPorter = 0;
118055 #ifdef SQLITE_ENABLE_ICU
118056 const sqlite3_tokenizer_module *pIcu = 0;
118057 sqlite3Fts3IcuTokenizerModule(&pIcu);
118058 #endif
118060 #ifdef SQLITE_TEST
118061 rc = sqlite3Fts3InitTerm(db);
118062 if( rc!=SQLITE_OK ) return rc;
118063 #endif
118065 rc = sqlite3Fts3InitAux(db);
118066 if( rc!=SQLITE_OK ) return rc;
118068 sqlite3Fts3SimpleTokenizerModule(&pSimple);
118069 sqlite3Fts3PorterTokenizerModule(&pPorter);
118071 /* Allocate and initialise the hash-table used to store tokenizers. */
118072 pHash = sqlite3_malloc(sizeof(Fts3Hash));
118073 if( !pHash ){
118074 rc = SQLITE_NOMEM;
118075 }else{
118076 sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
118079 /* Load the built-in tokenizers into the hash table */
118080 if( rc==SQLITE_OK ){
118081 if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
118082 || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
118083 #ifdef SQLITE_ENABLE_ICU
118084 || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
118085 #endif
118087 rc = SQLITE_NOMEM;
118091 #ifdef SQLITE_TEST
118092 if( rc==SQLITE_OK ){
118093 rc = sqlite3Fts3ExprInitTestInterface(db);
118095 #endif
118097 /* Create the virtual table wrapper around the hash-table and overload
118098 ** the two scalar functions. If this is successful, register the
118099 ** module with sqlite.
118101 if( SQLITE_OK==rc
118102 && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
118103 && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
118104 && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
118105 && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
118106 && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
118107 && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
118109 rc = sqlite3_create_module_v2(
118110 db, "fts3", &fts3Module, (void *)pHash, hashDestroy
118112 if( rc==SQLITE_OK ){
118113 rc = sqlite3_create_module_v2(
118114 db, "fts4", &fts3Module, (void *)pHash, 0
118117 return rc;
118120 /* An error has occurred. Delete the hash table and return the error code. */
118121 assert( rc!=SQLITE_OK );
118122 if( pHash ){
118123 sqlite3Fts3HashClear(pHash);
118124 sqlite3_free(pHash);
118126 return rc;
118130 ** Allocate an Fts3MultiSegReader for each token in the expression headed
118131 ** by pExpr.
118133 ** An Fts3SegReader object is a cursor that can seek or scan a range of
118134 ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
118135 ** Fts3SegReader objects internally to provide an interface to seek or scan
118136 ** within the union of all segments of a b-tree. Hence the name.
118138 ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
118139 ** segment b-tree (if the term is not a prefix or it is a prefix for which
118140 ** there exists prefix b-tree of the right length) then it may be traversed
118141 ** and merged incrementally. Otherwise, it has to be merged into an in-memory
118142 ** doclist and then traversed.
118144 static void fts3EvalAllocateReaders(
118145 Fts3Cursor *pCsr, /* FTS cursor handle */
118146 Fts3Expr *pExpr, /* Allocate readers for this expression */
118147 int *pnToken, /* OUT: Total number of tokens in phrase. */
118148 int *pnOr, /* OUT: Total number of OR nodes in expr. */
118149 int *pRc /* IN/OUT: Error code */
118151 if( pExpr && SQLITE_OK==*pRc ){
118152 if( pExpr->eType==FTSQUERY_PHRASE ){
118153 int i;
118154 int nToken = pExpr->pPhrase->nToken;
118155 *pnToken += nToken;
118156 for(i=0; i<nToken; i++){
118157 Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
118158 int rc = fts3TermSegReaderCursor(pCsr,
118159 pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
118161 if( rc!=SQLITE_OK ){
118162 *pRc = rc;
118163 return;
118166 assert( pExpr->pPhrase->iDoclistToken==0 );
118167 pExpr->pPhrase->iDoclistToken = -1;
118168 }else{
118169 *pnOr += (pExpr->eType==FTSQUERY_OR);
118170 fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
118171 fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
118177 ** Arguments pList/nList contain the doclist for token iToken of phrase p.
118178 ** It is merged into the main doclist stored in p->doclist.aAll/nAll.
118180 ** This function assumes that pList points to a buffer allocated using
118181 ** sqlite3_malloc(). This function takes responsibility for eventually
118182 ** freeing the buffer.
118184 static void fts3EvalPhraseMergeToken(
118185 Fts3Table *pTab, /* FTS Table pointer */
118186 Fts3Phrase *p, /* Phrase to merge pList/nList into */
118187 int iToken, /* Token pList/nList corresponds to */
118188 char *pList, /* Pointer to doclist */
118189 int nList /* Number of bytes in pList */
118191 assert( iToken!=p->iDoclistToken );
118193 if( pList==0 ){
118194 sqlite3_free(p->doclist.aAll);
118195 p->doclist.aAll = 0;
118196 p->doclist.nAll = 0;
118199 else if( p->iDoclistToken<0 ){
118200 p->doclist.aAll = pList;
118201 p->doclist.nAll = nList;
118204 else if( p->doclist.aAll==0 ){
118205 sqlite3_free(pList);
118208 else {
118209 char *pLeft;
118210 char *pRight;
118211 int nLeft;
118212 int nRight;
118213 int nDiff;
118215 if( p->iDoclistToken<iToken ){
118216 pLeft = p->doclist.aAll;
118217 nLeft = p->doclist.nAll;
118218 pRight = pList;
118219 nRight = nList;
118220 nDiff = iToken - p->iDoclistToken;
118221 }else{
118222 pRight = p->doclist.aAll;
118223 nRight = p->doclist.nAll;
118224 pLeft = pList;
118225 nLeft = nList;
118226 nDiff = p->iDoclistToken - iToken;
118229 fts3DoclistPhraseMerge(pTab->bDescIdx, nDiff, pLeft, nLeft, pRight,&nRight);
118230 sqlite3_free(pLeft);
118231 p->doclist.aAll = pRight;
118232 p->doclist.nAll = nRight;
118235 if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
118239 ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
118240 ** does not take deferred tokens into account.
118242 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
118244 static int fts3EvalPhraseLoad(
118245 Fts3Cursor *pCsr, /* FTS Cursor handle */
118246 Fts3Phrase *p /* Phrase object */
118248 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
118249 int iToken;
118250 int rc = SQLITE_OK;
118252 for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
118253 Fts3PhraseToken *pToken = &p->aToken[iToken];
118254 assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
118256 if( pToken->pSegcsr ){
118257 int nThis = 0;
118258 char *pThis = 0;
118259 rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
118260 if( rc==SQLITE_OK ){
118261 fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
118264 assert( pToken->pSegcsr==0 );
118267 return rc;
118271 ** This function is called on each phrase after the position lists for
118272 ** any deferred tokens have been loaded into memory. It updates the phrases
118273 ** current position list to include only those positions that are really
118274 ** instances of the phrase (after considering deferred tokens). If this
118275 ** means that the phrase does not appear in the current row, doclist.pList
118276 ** and doclist.nList are both zeroed.
118278 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
118280 static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
118281 int iToken; /* Used to iterate through phrase tokens */
118282 char *aPoslist = 0; /* Position list for deferred tokens */
118283 int nPoslist = 0; /* Number of bytes in aPoslist */
118284 int iPrev = -1; /* Token number of previous deferred token */
118286 assert( pPhrase->doclist.bFreeList==0 );
118288 for(iToken=0; iToken<pPhrase->nToken; iToken++){
118289 Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
118290 Fts3DeferredToken *pDeferred = pToken->pDeferred;
118292 if( pDeferred ){
118293 char *pList;
118294 int nList;
118295 int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
118296 if( rc!=SQLITE_OK ) return rc;
118298 if( pList==0 ){
118299 sqlite3_free(aPoslist);
118300 pPhrase->doclist.pList = 0;
118301 pPhrase->doclist.nList = 0;
118302 return SQLITE_OK;
118304 }else if( aPoslist==0 ){
118305 aPoslist = pList;
118306 nPoslist = nList;
118308 }else{
118309 char *aOut = pList;
118310 char *p1 = aPoslist;
118311 char *p2 = aOut;
118313 assert( iPrev>=0 );
118314 fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
118315 sqlite3_free(aPoslist);
118316 aPoslist = pList;
118317 nPoslist = aOut - aPoslist;
118318 if( nPoslist==0 ){
118319 sqlite3_free(aPoslist);
118320 pPhrase->doclist.pList = 0;
118321 pPhrase->doclist.nList = 0;
118322 return SQLITE_OK;
118325 iPrev = iToken;
118329 if( iPrev>=0 ){
118330 int nMaxUndeferred = pPhrase->iDoclistToken;
118331 if( nMaxUndeferred<0 ){
118332 pPhrase->doclist.pList = aPoslist;
118333 pPhrase->doclist.nList = nPoslist;
118334 pPhrase->doclist.iDocid = pCsr->iPrevId;
118335 pPhrase->doclist.bFreeList = 1;
118336 }else{
118337 int nDistance;
118338 char *p1;
118339 char *p2;
118340 char *aOut;
118342 if( nMaxUndeferred>iPrev ){
118343 p1 = aPoslist;
118344 p2 = pPhrase->doclist.pList;
118345 nDistance = nMaxUndeferred - iPrev;
118346 }else{
118347 p1 = pPhrase->doclist.pList;
118348 p2 = aPoslist;
118349 nDistance = iPrev - nMaxUndeferred;
118352 aOut = (char *)sqlite3_malloc(nPoslist+8);
118353 if( !aOut ){
118354 sqlite3_free(aPoslist);
118355 return SQLITE_NOMEM;
118358 pPhrase->doclist.pList = aOut;
118359 if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
118360 pPhrase->doclist.bFreeList = 1;
118361 pPhrase->doclist.nList = (aOut - pPhrase->doclist.pList);
118362 }else{
118363 sqlite3_free(aOut);
118364 pPhrase->doclist.pList = 0;
118365 pPhrase->doclist.nList = 0;
118367 sqlite3_free(aPoslist);
118371 return SQLITE_OK;
118375 ** This function is called for each Fts3Phrase in a full-text query
118376 ** expression to initialize the mechanism for returning rows. Once this
118377 ** function has been called successfully on an Fts3Phrase, it may be
118378 ** used with fts3EvalPhraseNext() to iterate through the matching docids.
118380 ** If parameter bOptOk is true, then the phrase may (or may not) use the
118381 ** incremental loading strategy. Otherwise, the entire doclist is loaded into
118382 ** memory within this call.
118384 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
118386 static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
118387 int rc; /* Error code */
118388 Fts3PhraseToken *pFirst = &p->aToken[0];
118389 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
118391 if( pCsr->bDesc==pTab->bDescIdx
118392 && bOptOk==1
118393 && p->nToken==1
118394 && pFirst->pSegcsr
118395 && pFirst->pSegcsr->bLookup
118396 && pFirst->bFirst==0
118398 /* Use the incremental approach. */
118399 int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
118400 rc = sqlite3Fts3MsrIncrStart(
118401 pTab, pFirst->pSegcsr, iCol, pFirst->z, pFirst->n);
118402 p->bIncr = 1;
118404 }else{
118405 /* Load the full doclist for the phrase into memory. */
118406 rc = fts3EvalPhraseLoad(pCsr, p);
118407 p->bIncr = 0;
118410 assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
118411 return rc;
118415 ** This function is used to iterate backwards (from the end to start)
118416 ** through doclists. It is used by this module to iterate through phrase
118417 ** doclists in reverse and by the fts3_write.c module to iterate through
118418 ** pending-terms lists when writing to databases with "order=desc".
118420 ** The doclist may be sorted in ascending (parameter bDescIdx==0) or
118421 ** descending (parameter bDescIdx==1) order of docid. Regardless, this
118422 ** function iterates from the end of the doclist to the beginning.
118424 SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
118425 int bDescIdx, /* True if the doclist is desc */
118426 char *aDoclist, /* Pointer to entire doclist */
118427 int nDoclist, /* Length of aDoclist in bytes */
118428 char **ppIter, /* IN/OUT: Iterator pointer */
118429 sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
118430 int *pnList, /* IN/OUT: List length pointer */
118431 u8 *pbEof /* OUT: End-of-file flag */
118433 char *p = *ppIter;
118435 assert( nDoclist>0 );
118436 assert( *pbEof==0 );
118437 assert( p || *piDocid==0 );
118438 assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
118440 if( p==0 ){
118441 sqlite3_int64 iDocid = 0;
118442 char *pNext = 0;
118443 char *pDocid = aDoclist;
118444 char *pEnd = &aDoclist[nDoclist];
118445 int iMul = 1;
118447 while( pDocid<pEnd ){
118448 sqlite3_int64 iDelta;
118449 pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
118450 iDocid += (iMul * iDelta);
118451 pNext = pDocid;
118452 fts3PoslistCopy(0, &pDocid);
118453 while( pDocid<pEnd && *pDocid==0 ) pDocid++;
118454 iMul = (bDescIdx ? -1 : 1);
118457 *pnList = pEnd - pNext;
118458 *ppIter = pNext;
118459 *piDocid = iDocid;
118460 }else{
118461 int iMul = (bDescIdx ? -1 : 1);
118462 sqlite3_int64 iDelta;
118463 fts3GetReverseVarint(&p, aDoclist, &iDelta);
118464 *piDocid -= (iMul * iDelta);
118466 if( p==aDoclist ){
118467 *pbEof = 1;
118468 }else{
118469 char *pSave = p;
118470 fts3ReversePoslist(aDoclist, &p);
118471 *pnList = (pSave - p);
118473 *ppIter = p;
118478 ** Attempt to move the phrase iterator to point to the next matching docid.
118479 ** If an error occurs, return an SQLite error code. Otherwise, return
118480 ** SQLITE_OK.
118482 ** If there is no "next" entry and no error occurs, then *pbEof is set to
118483 ** 1 before returning. Otherwise, if no error occurs and the iterator is
118484 ** successfully advanced, *pbEof is set to 0.
118486 static int fts3EvalPhraseNext(
118487 Fts3Cursor *pCsr, /* FTS Cursor handle */
118488 Fts3Phrase *p, /* Phrase object to advance to next docid */
118489 u8 *pbEof /* OUT: Set to 1 if EOF */
118491 int rc = SQLITE_OK;
118492 Fts3Doclist *pDL = &p->doclist;
118493 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
118495 if( p->bIncr ){
118496 assert( p->nToken==1 );
118497 assert( pDL->pNextDocid==0 );
118498 rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr,
118499 &pDL->iDocid, &pDL->pList, &pDL->nList
118501 if( rc==SQLITE_OK && !pDL->pList ){
118502 *pbEof = 1;
118504 }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
118505 sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll,
118506 &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
118508 pDL->pList = pDL->pNextDocid;
118509 }else{
118510 char *pIter; /* Used to iterate through aAll */
118511 char *pEnd = &pDL->aAll[pDL->nAll]; /* 1 byte past end of aAll */
118512 if( pDL->pNextDocid ){
118513 pIter = pDL->pNextDocid;
118514 }else{
118515 pIter = pDL->aAll;
118518 if( pIter>=pEnd ){
118519 /* We have already reached the end of this doclist. EOF. */
118520 *pbEof = 1;
118521 }else{
118522 sqlite3_int64 iDelta;
118523 pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
118524 if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
118525 pDL->iDocid += iDelta;
118526 }else{
118527 pDL->iDocid -= iDelta;
118529 pDL->pList = pIter;
118530 fts3PoslistCopy(0, &pIter);
118531 pDL->nList = (pIter - pDL->pList);
118533 /* pIter now points just past the 0x00 that terminates the position-
118534 ** list for document pDL->iDocid. However, if this position-list was
118535 ** edited in place by fts3EvalNearTrim(), then pIter may not actually
118536 ** point to the start of the next docid value. The following line deals
118537 ** with this case by advancing pIter past the zero-padding added by
118538 ** fts3EvalNearTrim(). */
118539 while( pIter<pEnd && *pIter==0 ) pIter++;
118541 pDL->pNextDocid = pIter;
118542 assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
118543 *pbEof = 0;
118547 return rc;
118552 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
118553 ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
118554 ** expression. Also the Fts3Expr.bDeferred variable is set to true for any
118555 ** expressions for which all descendent tokens are deferred.
118557 ** If parameter bOptOk is zero, then it is guaranteed that the
118558 ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
118559 ** each phrase in the expression (subject to deferred token processing).
118560 ** Or, if bOptOk is non-zero, then one or more tokens within the expression
118561 ** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
118563 ** If an error occurs within this function, *pRc is set to an SQLite error
118564 ** code before returning.
118566 static void fts3EvalStartReaders(
118567 Fts3Cursor *pCsr, /* FTS Cursor handle */
118568 Fts3Expr *pExpr, /* Expression to initialize phrases in */
118569 int bOptOk, /* True to enable incremental loading */
118570 int *pRc /* IN/OUT: Error code */
118572 if( pExpr && SQLITE_OK==*pRc ){
118573 if( pExpr->eType==FTSQUERY_PHRASE ){
118574 int i;
118575 int nToken = pExpr->pPhrase->nToken;
118576 for(i=0; i<nToken; i++){
118577 if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
118579 pExpr->bDeferred = (i==nToken);
118580 *pRc = fts3EvalPhraseStart(pCsr, bOptOk, pExpr->pPhrase);
118581 }else{
118582 fts3EvalStartReaders(pCsr, pExpr->pLeft, bOptOk, pRc);
118583 fts3EvalStartReaders(pCsr, pExpr->pRight, bOptOk, pRc);
118584 pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
118590 ** An array of the following structures is assembled as part of the process
118591 ** of selecting tokens to defer before the query starts executing (as part
118592 ** of the xFilter() method). There is one element in the array for each
118593 ** token in the FTS expression.
118595 ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
118596 ** to phrases that are connected only by AND and NEAR operators (not OR or
118597 ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
118598 ** separately. The root of a tokens AND/NEAR cluster is stored in
118599 ** Fts3TokenAndCost.pRoot.
118601 typedef struct Fts3TokenAndCost Fts3TokenAndCost;
118602 struct Fts3TokenAndCost {
118603 Fts3Phrase *pPhrase; /* The phrase the token belongs to */
118604 int iToken; /* Position of token in phrase */
118605 Fts3PhraseToken *pToken; /* The token itself */
118606 Fts3Expr *pRoot; /* Root of NEAR/AND cluster */
118607 int nOvfl; /* Number of overflow pages to load doclist */
118608 int iCol; /* The column the token must match */
118612 ** This function is used to populate an allocated Fts3TokenAndCost array.
118614 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
118615 ** Otherwise, if an error occurs during execution, *pRc is set to an
118616 ** SQLite error code.
118618 static void fts3EvalTokenCosts(
118619 Fts3Cursor *pCsr, /* FTS Cursor handle */
118620 Fts3Expr *pRoot, /* Root of current AND/NEAR cluster */
118621 Fts3Expr *pExpr, /* Expression to consider */
118622 Fts3TokenAndCost **ppTC, /* Write new entries to *(*ppTC)++ */
118623 Fts3Expr ***ppOr, /* Write new OR root to *(*ppOr)++ */
118624 int *pRc /* IN/OUT: Error code */
118626 if( *pRc==SQLITE_OK ){
118627 if( pExpr->eType==FTSQUERY_PHRASE ){
118628 Fts3Phrase *pPhrase = pExpr->pPhrase;
118629 int i;
118630 for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
118631 Fts3TokenAndCost *pTC = (*ppTC)++;
118632 pTC->pPhrase = pPhrase;
118633 pTC->iToken = i;
118634 pTC->pRoot = pRoot;
118635 pTC->pToken = &pPhrase->aToken[i];
118636 pTC->iCol = pPhrase->iColumn;
118637 *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
118639 }else if( pExpr->eType!=FTSQUERY_NOT ){
118640 assert( pExpr->eType==FTSQUERY_OR
118641 || pExpr->eType==FTSQUERY_AND
118642 || pExpr->eType==FTSQUERY_NEAR
118644 assert( pExpr->pLeft && pExpr->pRight );
118645 if( pExpr->eType==FTSQUERY_OR ){
118646 pRoot = pExpr->pLeft;
118647 **ppOr = pRoot;
118648 (*ppOr)++;
118650 fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
118651 if( pExpr->eType==FTSQUERY_OR ){
118652 pRoot = pExpr->pRight;
118653 **ppOr = pRoot;
118654 (*ppOr)++;
118656 fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
118662 ** Determine the average document (row) size in pages. If successful,
118663 ** write this value to *pnPage and return SQLITE_OK. Otherwise, return
118664 ** an SQLite error code.
118666 ** The average document size in pages is calculated by first calculating
118667 ** determining the average size in bytes, B. If B is less than the amount
118668 ** of data that will fit on a single leaf page of an intkey table in
118669 ** this database, then the average docsize is 1. Otherwise, it is 1 plus
118670 ** the number of overflow pages consumed by a record B bytes in size.
118672 static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
118673 if( pCsr->nRowAvg==0 ){
118674 /* The average document size, which is required to calculate the cost
118675 ** of each doclist, has not yet been determined. Read the required
118676 ** data from the %_stat table to calculate it.
118678 ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
118679 ** varints, where nCol is the number of columns in the FTS3 table.
118680 ** The first varint is the number of documents currently stored in
118681 ** the table. The following nCol varints contain the total amount of
118682 ** data stored in all rows of each column of the table, from left
118683 ** to right.
118685 int rc;
118686 Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
118687 sqlite3_stmt *pStmt;
118688 sqlite3_int64 nDoc = 0;
118689 sqlite3_int64 nByte = 0;
118690 const char *pEnd;
118691 const char *a;
118693 rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
118694 if( rc!=SQLITE_OK ) return rc;
118695 a = sqlite3_column_blob(pStmt, 0);
118696 assert( a );
118698 pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
118699 a += sqlite3Fts3GetVarint(a, &nDoc);
118700 while( a<pEnd ){
118701 a += sqlite3Fts3GetVarint(a, &nByte);
118703 if( nDoc==0 || nByte==0 ){
118704 sqlite3_reset(pStmt);
118705 return FTS_CORRUPT_VTAB;
118708 pCsr->nDoc = nDoc;
118709 pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
118710 assert( pCsr->nRowAvg>0 );
118711 rc = sqlite3_reset(pStmt);
118712 if( rc!=SQLITE_OK ) return rc;
118715 *pnPage = pCsr->nRowAvg;
118716 return SQLITE_OK;
118720 ** This function is called to select the tokens (if any) that will be
118721 ** deferred. The array aTC[] has already been populated when this is
118722 ** called.
118724 ** This function is called once for each AND/NEAR cluster in the
118725 ** expression. Each invocation determines which tokens to defer within
118726 ** the cluster with root node pRoot. See comments above the definition
118727 ** of struct Fts3TokenAndCost for more details.
118729 ** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
118730 ** called on each token to defer. Otherwise, an SQLite error code is
118731 ** returned.
118733 static int fts3EvalSelectDeferred(
118734 Fts3Cursor *pCsr, /* FTS Cursor handle */
118735 Fts3Expr *pRoot, /* Consider tokens with this root node */
118736 Fts3TokenAndCost *aTC, /* Array of expression tokens and costs */
118737 int nTC /* Number of entries in aTC[] */
118739 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
118740 int nDocSize = 0; /* Number of pages per doc loaded */
118741 int rc = SQLITE_OK; /* Return code */
118742 int ii; /* Iterator variable for various purposes */
118743 int nOvfl = 0; /* Total overflow pages used by doclists */
118744 int nToken = 0; /* Total number of tokens in cluster */
118746 int nMinEst = 0; /* The minimum count for any phrase so far. */
118747 int nLoad4 = 1; /* (Phrases that will be loaded)^4. */
118749 /* Tokens are never deferred for FTS tables created using the content=xxx
118750 ** option. The reason being that it is not guaranteed that the content
118751 ** table actually contains the same data as the index. To prevent this from
118752 ** causing any problems, the deferred token optimization is completely
118753 ** disabled for content=xxx tables. */
118754 if( pTab->zContentTbl ){
118755 return SQLITE_OK;
118758 /* Count the tokens in this AND/NEAR cluster. If none of the doclists
118759 ** associated with the tokens spill onto overflow pages, or if there is
118760 ** only 1 token, exit early. No tokens to defer in this case. */
118761 for(ii=0; ii<nTC; ii++){
118762 if( aTC[ii].pRoot==pRoot ){
118763 nOvfl += aTC[ii].nOvfl;
118764 nToken++;
118767 if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
118769 /* Obtain the average docsize (in pages). */
118770 rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
118771 assert( rc!=SQLITE_OK || nDocSize>0 );
118774 /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
118775 ** of the number of overflow pages that will be loaded by the pager layer
118776 ** to retrieve the entire doclist for the token from the full-text index.
118777 ** Load the doclists for tokens that are either:
118779 ** a. The cheapest token in the entire query (i.e. the one visited by the
118780 ** first iteration of this loop), or
118782 ** b. Part of a multi-token phrase.
118784 ** After each token doclist is loaded, merge it with the others from the
118785 ** same phrase and count the number of documents that the merged doclist
118786 ** contains. Set variable "nMinEst" to the smallest number of documents in
118787 ** any phrase doclist for which 1 or more token doclists have been loaded.
118788 ** Let nOther be the number of other phrases for which it is certain that
118789 ** one or more tokens will not be deferred.
118791 ** Then, for each token, defer it if loading the doclist would result in
118792 ** loading N or more overflow pages into memory, where N is computed as:
118794 ** (nMinEst + 4^nOther - 1) / (4^nOther)
118796 for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
118797 int iTC; /* Used to iterate through aTC[] array. */
118798 Fts3TokenAndCost *pTC = 0; /* Set to cheapest remaining token. */
118800 /* Set pTC to point to the cheapest remaining token. */
118801 for(iTC=0; iTC<nTC; iTC++){
118802 if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot
118803 && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl)
118805 pTC = &aTC[iTC];
118808 assert( pTC );
118810 if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
118811 /* The number of overflow pages to load for this (and therefore all
118812 ** subsequent) tokens is greater than the estimated number of pages
118813 ** that will be loaded if all subsequent tokens are deferred.
118815 Fts3PhraseToken *pToken = pTC->pToken;
118816 rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
118817 fts3SegReaderCursorFree(pToken->pSegcsr);
118818 pToken->pSegcsr = 0;
118819 }else{
118820 /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
118821 ** for-loop. Except, limit the value to 2^24 to prevent it from
118822 ** overflowing the 32-bit integer it is stored in. */
118823 if( ii<12 ) nLoad4 = nLoad4*4;
118825 if( ii==0 || pTC->pPhrase->nToken>1 ){
118826 /* Either this is the cheapest token in the entire query, or it is
118827 ** part of a multi-token phrase. Either way, the entire doclist will
118828 ** (eventually) be loaded into memory. It may as well be now. */
118829 Fts3PhraseToken *pToken = pTC->pToken;
118830 int nList = 0;
118831 char *pList = 0;
118832 rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
118833 assert( rc==SQLITE_OK || pList==0 );
118834 if( rc==SQLITE_OK ){
118835 int nCount;
118836 fts3EvalPhraseMergeToken(pTab, pTC->pPhrase, pTC->iToken,pList,nList);
118837 nCount = fts3DoclistCountDocids(
118838 pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
118840 if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
118844 pTC->pToken = 0;
118847 return rc;
118851 ** This function is called from within the xFilter method. It initializes
118852 ** the full-text query currently stored in pCsr->pExpr. To iterate through
118853 ** the results of a query, the caller does:
118855 ** fts3EvalStart(pCsr);
118856 ** while( 1 ){
118857 ** fts3EvalNext(pCsr);
118858 ** if( pCsr->bEof ) break;
118859 ** ... return row pCsr->iPrevId to the caller ...
118862 static int fts3EvalStart(Fts3Cursor *pCsr){
118863 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
118864 int rc = SQLITE_OK;
118865 int nToken = 0;
118866 int nOr = 0;
118868 /* Allocate a MultiSegReader for each token in the expression. */
118869 fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
118871 /* Determine which, if any, tokens in the expression should be deferred. */
118872 if( rc==SQLITE_OK && nToken>1 && pTab->bHasStat ){
118873 Fts3TokenAndCost *aTC;
118874 Fts3Expr **apOr;
118875 aTC = (Fts3TokenAndCost *)sqlite3_malloc(
118876 sizeof(Fts3TokenAndCost) * nToken
118877 + sizeof(Fts3Expr *) * nOr * 2
118879 apOr = (Fts3Expr **)&aTC[nToken];
118881 if( !aTC ){
118882 rc = SQLITE_NOMEM;
118883 }else{
118884 int ii;
118885 Fts3TokenAndCost *pTC = aTC;
118886 Fts3Expr **ppOr = apOr;
118888 fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
118889 nToken = pTC-aTC;
118890 nOr = ppOr-apOr;
118892 if( rc==SQLITE_OK ){
118893 rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
118894 for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
118895 rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
118899 sqlite3_free(aTC);
118903 fts3EvalStartReaders(pCsr, pCsr->pExpr, 1, &rc);
118904 return rc;
118908 ** Invalidate the current position list for phrase pPhrase.
118910 static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
118911 if( pPhrase->doclist.bFreeList ){
118912 sqlite3_free(pPhrase->doclist.pList);
118914 pPhrase->doclist.pList = 0;
118915 pPhrase->doclist.nList = 0;
118916 pPhrase->doclist.bFreeList = 0;
118920 ** This function is called to edit the position list associated with
118921 ** the phrase object passed as the fifth argument according to a NEAR
118922 ** condition. For example:
118924 ** abc NEAR/5 "def ghi"
118926 ** Parameter nNear is passed the NEAR distance of the expression (5 in
118927 ** the example above). When this function is called, *paPoslist points to
118928 ** the position list, and *pnToken is the number of phrase tokens in, the
118929 ** phrase on the other side of the NEAR operator to pPhrase. For example,
118930 ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
118931 ** the position list associated with phrase "abc".
118933 ** All positions in the pPhrase position list that are not sufficiently
118934 ** close to a position in the *paPoslist position list are removed. If this
118935 ** leaves 0 positions, zero is returned. Otherwise, non-zero.
118937 ** Before returning, *paPoslist is set to point to the position lsit
118938 ** associated with pPhrase. And *pnToken is set to the number of tokens in
118939 ** pPhrase.
118941 static int fts3EvalNearTrim(
118942 int nNear, /* NEAR distance. As in "NEAR/nNear". */
118943 char *aTmp, /* Temporary space to use */
118944 char **paPoslist, /* IN/OUT: Position list */
118945 int *pnToken, /* IN/OUT: Tokens in phrase of *paPoslist */
118946 Fts3Phrase *pPhrase /* The phrase object to trim the doclist of */
118948 int nParam1 = nNear + pPhrase->nToken;
118949 int nParam2 = nNear + *pnToken;
118950 int nNew;
118951 char *p2;
118952 char *pOut;
118953 int res;
118955 assert( pPhrase->doclist.pList );
118957 p2 = pOut = pPhrase->doclist.pList;
118958 res = fts3PoslistNearMerge(
118959 &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
118961 if( res ){
118962 nNew = (pOut - pPhrase->doclist.pList) - 1;
118963 assert( pPhrase->doclist.pList[nNew]=='\0' );
118964 assert( nNew<=pPhrase->doclist.nList && nNew>0 );
118965 memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
118966 pPhrase->doclist.nList = nNew;
118967 *paPoslist = pPhrase->doclist.pList;
118968 *pnToken = pPhrase->nToken;
118971 return res;
118975 ** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
118976 ** Otherwise, it advances the expression passed as the second argument to
118977 ** point to the next matching row in the database. Expressions iterate through
118978 ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
118979 ** or descending if it is non-zero.
118981 ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
118982 ** successful, the following variables in pExpr are set:
118984 ** Fts3Expr.bEof (non-zero if EOF - there is no next row)
118985 ** Fts3Expr.iDocid (valid if bEof==0. The docid of the next row)
118987 ** If the expression is of type FTSQUERY_PHRASE, and the expression is not
118988 ** at EOF, then the following variables are populated with the position list
118989 ** for the phrase for the visited row:
118991 ** FTs3Expr.pPhrase->doclist.nList (length of pList in bytes)
118992 ** FTs3Expr.pPhrase->doclist.pList (pointer to position list)
118994 ** It says above that this function advances the expression to the next
118995 ** matching row. This is usually true, but there are the following exceptions:
118997 ** 1. Deferred tokens are not taken into account. If a phrase consists
118998 ** entirely of deferred tokens, it is assumed to match every row in
118999 ** the db. In this case the position-list is not populated at all.
119001 ** Or, if a phrase contains one or more deferred tokens and one or
119002 ** more non-deferred tokens, then the expression is advanced to the
119003 ** next possible match, considering only non-deferred tokens. In other
119004 ** words, if the phrase is "A B C", and "B" is deferred, the expression
119005 ** is advanced to the next row that contains an instance of "A * C",
119006 ** where "*" may match any single token. The position list in this case
119007 ** is populated as for "A * C" before returning.
119009 ** 2. NEAR is treated as AND. If the expression is "x NEAR y", it is
119010 ** advanced to point to the next row that matches "x AND y".
119012 ** See fts3EvalTestDeferredAndNear() for details on testing if a row is
119013 ** really a match, taking into account deferred tokens and NEAR operators.
119015 static void fts3EvalNextRow(
119016 Fts3Cursor *pCsr, /* FTS Cursor handle */
119017 Fts3Expr *pExpr, /* Expr. to advance to next matching row */
119018 int *pRc /* IN/OUT: Error code */
119020 if( *pRc==SQLITE_OK ){
119021 int bDescDoclist = pCsr->bDesc; /* Used by DOCID_CMP() macro */
119022 assert( pExpr->bEof==0 );
119023 pExpr->bStart = 1;
119025 switch( pExpr->eType ){
119026 case FTSQUERY_NEAR:
119027 case FTSQUERY_AND: {
119028 Fts3Expr *pLeft = pExpr->pLeft;
119029 Fts3Expr *pRight = pExpr->pRight;
119030 assert( !pLeft->bDeferred || !pRight->bDeferred );
119032 if( pLeft->bDeferred ){
119033 /* LHS is entirely deferred. So we assume it matches every row.
119034 ** Advance the RHS iterator to find the next row visited. */
119035 fts3EvalNextRow(pCsr, pRight, pRc);
119036 pExpr->iDocid = pRight->iDocid;
119037 pExpr->bEof = pRight->bEof;
119038 }else if( pRight->bDeferred ){
119039 /* RHS is entirely deferred. So we assume it matches every row.
119040 ** Advance the LHS iterator to find the next row visited. */
119041 fts3EvalNextRow(pCsr, pLeft, pRc);
119042 pExpr->iDocid = pLeft->iDocid;
119043 pExpr->bEof = pLeft->bEof;
119044 }else{
119045 /* Neither the RHS or LHS are deferred. */
119046 fts3EvalNextRow(pCsr, pLeft, pRc);
119047 fts3EvalNextRow(pCsr, pRight, pRc);
119048 while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
119049 sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
119050 if( iDiff==0 ) break;
119051 if( iDiff<0 ){
119052 fts3EvalNextRow(pCsr, pLeft, pRc);
119053 }else{
119054 fts3EvalNextRow(pCsr, pRight, pRc);
119057 pExpr->iDocid = pLeft->iDocid;
119058 pExpr->bEof = (pLeft->bEof || pRight->bEof);
119060 break;
119063 case FTSQUERY_OR: {
119064 Fts3Expr *pLeft = pExpr->pLeft;
119065 Fts3Expr *pRight = pExpr->pRight;
119066 sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
119068 assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
119069 assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
119071 if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
119072 fts3EvalNextRow(pCsr, pLeft, pRc);
119073 }else if( pLeft->bEof || (pRight->bEof==0 && iCmp>0) ){
119074 fts3EvalNextRow(pCsr, pRight, pRc);
119075 }else{
119076 fts3EvalNextRow(pCsr, pLeft, pRc);
119077 fts3EvalNextRow(pCsr, pRight, pRc);
119080 pExpr->bEof = (pLeft->bEof && pRight->bEof);
119081 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
119082 if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
119083 pExpr->iDocid = pLeft->iDocid;
119084 }else{
119085 pExpr->iDocid = pRight->iDocid;
119088 break;
119091 case FTSQUERY_NOT: {
119092 Fts3Expr *pLeft = pExpr->pLeft;
119093 Fts3Expr *pRight = pExpr->pRight;
119095 if( pRight->bStart==0 ){
119096 fts3EvalNextRow(pCsr, pRight, pRc);
119097 assert( *pRc!=SQLITE_OK || pRight->bStart );
119100 fts3EvalNextRow(pCsr, pLeft, pRc);
119101 if( pLeft->bEof==0 ){
119102 while( !*pRc
119103 && !pRight->bEof
119104 && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0
119106 fts3EvalNextRow(pCsr, pRight, pRc);
119109 pExpr->iDocid = pLeft->iDocid;
119110 pExpr->bEof = pLeft->bEof;
119111 break;
119114 default: {
119115 Fts3Phrase *pPhrase = pExpr->pPhrase;
119116 fts3EvalInvalidatePoslist(pPhrase);
119117 *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
119118 pExpr->iDocid = pPhrase->doclist.iDocid;
119119 break;
119126 ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
119127 ** cluster, then this function returns 1 immediately.
119129 ** Otherwise, it checks if the current row really does match the NEAR
119130 ** expression, using the data currently stored in the position lists
119131 ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
119133 ** If the current row is a match, the position list associated with each
119134 ** phrase in the NEAR expression is edited in place to contain only those
119135 ** phrase instances sufficiently close to their peers to satisfy all NEAR
119136 ** constraints. In this case it returns 1. If the NEAR expression does not
119137 ** match the current row, 0 is returned. The position lists may or may not
119138 ** be edited if 0 is returned.
119140 static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
119141 int res = 1;
119143 /* The following block runs if pExpr is the root of a NEAR query.
119144 ** For example, the query:
119146 ** "w" NEAR "x" NEAR "y" NEAR "z"
119148 ** which is represented in tree form as:
119151 ** +--NEAR--+ <-- root of NEAR query
119152 ** | |
119153 ** +--NEAR--+ "z"
119154 ** | |
119155 ** +--NEAR--+ "y"
119156 ** | |
119157 ** "w" "x"
119159 ** The right-hand child of a NEAR node is always a phrase. The
119160 ** left-hand child may be either a phrase or a NEAR node. There are
119161 ** no exceptions to this - it's the way the parser in fts3_expr.c works.
119163 if( *pRc==SQLITE_OK
119164 && pExpr->eType==FTSQUERY_NEAR
119165 && pExpr->bEof==0
119166 && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
119168 Fts3Expr *p;
119169 int nTmp = 0; /* Bytes of temp space */
119170 char *aTmp; /* Temp space for PoslistNearMerge() */
119172 /* Allocate temporary working space. */
119173 for(p=pExpr; p->pLeft; p=p->pLeft){
119174 nTmp += p->pRight->pPhrase->doclist.nList;
119176 nTmp += p->pPhrase->doclist.nList;
119177 aTmp = sqlite3_malloc(nTmp*2);
119178 if( !aTmp ){
119179 *pRc = SQLITE_NOMEM;
119180 res = 0;
119181 }else{
119182 char *aPoslist = p->pPhrase->doclist.pList;
119183 int nToken = p->pPhrase->nToken;
119185 for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
119186 Fts3Phrase *pPhrase = p->pRight->pPhrase;
119187 int nNear = p->nNear;
119188 res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
119191 aPoslist = pExpr->pRight->pPhrase->doclist.pList;
119192 nToken = pExpr->pRight->pPhrase->nToken;
119193 for(p=pExpr->pLeft; p && res; p=p->pLeft){
119194 int nNear;
119195 Fts3Phrase *pPhrase;
119196 assert( p->pParent && p->pParent->pLeft==p );
119197 nNear = p->pParent->nNear;
119198 pPhrase = (
119199 p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
119201 res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
119205 sqlite3_free(aTmp);
119208 return res;
119212 ** This function is a helper function for fts3EvalTestDeferredAndNear().
119213 ** Assuming no error occurs or has occurred, It returns non-zero if the
119214 ** expression passed as the second argument matches the row that pCsr
119215 ** currently points to, or zero if it does not.
119217 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
119218 ** If an error occurs during execution of this function, *pRc is set to
119219 ** the appropriate SQLite error code. In this case the returned value is
119220 ** undefined.
119222 static int fts3EvalTestExpr(
119223 Fts3Cursor *pCsr, /* FTS cursor handle */
119224 Fts3Expr *pExpr, /* Expr to test. May or may not be root. */
119225 int *pRc /* IN/OUT: Error code */
119227 int bHit = 1; /* Return value */
119228 if( *pRc==SQLITE_OK ){
119229 switch( pExpr->eType ){
119230 case FTSQUERY_NEAR:
119231 case FTSQUERY_AND:
119232 bHit = (
119233 fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
119234 && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
119235 && fts3EvalNearTest(pExpr, pRc)
119238 /* If the NEAR expression does not match any rows, zero the doclist for
119239 ** all phrases involved in the NEAR. This is because the snippet(),
119240 ** offsets() and matchinfo() functions are not supposed to recognize
119241 ** any instances of phrases that are part of unmatched NEAR queries.
119242 ** For example if this expression:
119244 ** ... MATCH 'a OR (b NEAR c)'
119246 ** is matched against a row containing:
119248 ** 'a b d e'
119250 ** then any snippet() should ony highlight the "a" term, not the "b"
119251 ** (as "b" is part of a non-matching NEAR clause).
119253 if( bHit==0
119254 && pExpr->eType==FTSQUERY_NEAR
119255 && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
119257 Fts3Expr *p;
119258 for(p=pExpr; p->pPhrase==0; p=p->pLeft){
119259 if( p->pRight->iDocid==pCsr->iPrevId ){
119260 fts3EvalInvalidatePoslist(p->pRight->pPhrase);
119263 if( p->iDocid==pCsr->iPrevId ){
119264 fts3EvalInvalidatePoslist(p->pPhrase);
119268 break;
119270 case FTSQUERY_OR: {
119271 int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
119272 int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
119273 bHit = bHit1 || bHit2;
119274 break;
119277 case FTSQUERY_NOT:
119278 bHit = (
119279 fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
119280 && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
119282 break;
119284 default: {
119285 if( pCsr->pDeferred
119286 && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
119288 Fts3Phrase *pPhrase = pExpr->pPhrase;
119289 assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
119290 if( pExpr->bDeferred ){
119291 fts3EvalInvalidatePoslist(pPhrase);
119293 *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
119294 bHit = (pPhrase->doclist.pList!=0);
119295 pExpr->iDocid = pCsr->iPrevId;
119296 }else{
119297 bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
119299 break;
119303 return bHit;
119307 ** This function is called as the second part of each xNext operation when
119308 ** iterating through the results of a full-text query. At this point the
119309 ** cursor points to a row that matches the query expression, with the
119310 ** following caveats:
119312 ** * Up until this point, "NEAR" operators in the expression have been
119313 ** treated as "AND".
119315 ** * Deferred tokens have not yet been considered.
119317 ** If *pRc is not SQLITE_OK when this function is called, it immediately
119318 ** returns 0. Otherwise, it tests whether or not after considering NEAR
119319 ** operators and deferred tokens the current row is still a match for the
119320 ** expression. It returns 1 if both of the following are true:
119322 ** 1. *pRc is SQLITE_OK when this function returns, and
119324 ** 2. After scanning the current FTS table row for the deferred tokens,
119325 ** it is determined that the row does *not* match the query.
119327 ** Or, if no error occurs and it seems the current row does match the FTS
119328 ** query, return 0.
119330 static int fts3EvalTestDeferredAndNear(Fts3Cursor *pCsr, int *pRc){
119331 int rc = *pRc;
119332 int bMiss = 0;
119333 if( rc==SQLITE_OK ){
119335 /* If there are one or more deferred tokens, load the current row into
119336 ** memory and scan it to determine the position list for each deferred
119337 ** token. Then, see if this row is really a match, considering deferred
119338 ** tokens and NEAR operators (neither of which were taken into account
119339 ** earlier, by fts3EvalNextRow()).
119341 if( pCsr->pDeferred ){
119342 rc = fts3CursorSeek(0, pCsr);
119343 if( rc==SQLITE_OK ){
119344 rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
119347 bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
119349 /* Free the position-lists accumulated for each deferred token above. */
119350 sqlite3Fts3FreeDeferredDoclists(pCsr);
119351 *pRc = rc;
119353 return (rc==SQLITE_OK && bMiss);
119357 ** Advance to the next document that matches the FTS expression in
119358 ** Fts3Cursor.pExpr.
119360 static int fts3EvalNext(Fts3Cursor *pCsr){
119361 int rc = SQLITE_OK; /* Return Code */
119362 Fts3Expr *pExpr = pCsr->pExpr;
119363 assert( pCsr->isEof==0 );
119364 if( pExpr==0 ){
119365 pCsr->isEof = 1;
119366 }else{
119368 if( pCsr->isRequireSeek==0 ){
119369 sqlite3_reset(pCsr->pStmt);
119371 assert( sqlite3_data_count(pCsr->pStmt)==0 );
119372 fts3EvalNextRow(pCsr, pExpr, &rc);
119373 pCsr->isEof = pExpr->bEof;
119374 pCsr->isRequireSeek = 1;
119375 pCsr->isMatchinfoNeeded = 1;
119376 pCsr->iPrevId = pExpr->iDocid;
119377 }while( pCsr->isEof==0 && fts3EvalTestDeferredAndNear(pCsr, &rc) );
119379 return rc;
119383 ** Restart interation for expression pExpr so that the next call to
119384 ** fts3EvalNext() visits the first row. Do not allow incremental
119385 ** loading or merging of phrase doclists for this iteration.
119387 ** If *pRc is other than SQLITE_OK when this function is called, it is
119388 ** a no-op. If an error occurs within this function, *pRc is set to an
119389 ** SQLite error code before returning.
119391 static void fts3EvalRestart(
119392 Fts3Cursor *pCsr,
119393 Fts3Expr *pExpr,
119394 int *pRc
119396 if( pExpr && *pRc==SQLITE_OK ){
119397 Fts3Phrase *pPhrase = pExpr->pPhrase;
119399 if( pPhrase ){
119400 fts3EvalInvalidatePoslist(pPhrase);
119401 if( pPhrase->bIncr ){
119402 assert( pPhrase->nToken==1 );
119403 assert( pPhrase->aToken[0].pSegcsr );
119404 sqlite3Fts3MsrIncrRestart(pPhrase->aToken[0].pSegcsr);
119405 *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
119408 pPhrase->doclist.pNextDocid = 0;
119409 pPhrase->doclist.iDocid = 0;
119412 pExpr->iDocid = 0;
119413 pExpr->bEof = 0;
119414 pExpr->bStart = 0;
119416 fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
119417 fts3EvalRestart(pCsr, pExpr->pRight, pRc);
119422 ** After allocating the Fts3Expr.aMI[] array for each phrase in the
119423 ** expression rooted at pExpr, the cursor iterates through all rows matched
119424 ** by pExpr, calling this function for each row. This function increments
119425 ** the values in Fts3Expr.aMI[] according to the position-list currently
119426 ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
119427 ** expression nodes.
119429 static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
119430 if( pExpr ){
119431 Fts3Phrase *pPhrase = pExpr->pPhrase;
119432 if( pPhrase && pPhrase->doclist.pList ){
119433 int iCol = 0;
119434 char *p = pPhrase->doclist.pList;
119436 assert( *p );
119437 while( 1 ){
119438 u8 c = 0;
119439 int iCnt = 0;
119440 while( 0xFE & (*p | c) ){
119441 if( (c&0x80)==0 ) iCnt++;
119442 c = *p++ & 0x80;
119445 /* aMI[iCol*3 + 1] = Number of occurrences
119446 ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
119448 pExpr->aMI[iCol*3 + 1] += iCnt;
119449 pExpr->aMI[iCol*3 + 2] += (iCnt>0);
119450 if( *p==0x00 ) break;
119452 p += sqlite3Fts3GetVarint32(p, &iCol);
119456 fts3EvalUpdateCounts(pExpr->pLeft);
119457 fts3EvalUpdateCounts(pExpr->pRight);
119462 ** Expression pExpr must be of type FTSQUERY_PHRASE.
119464 ** If it is not already allocated and populated, this function allocates and
119465 ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
119466 ** of a NEAR expression, then it also allocates and populates the same array
119467 ** for all other phrases that are part of the NEAR expression.
119469 ** SQLITE_OK is returned if the aMI[] array is successfully allocated and
119470 ** populated. Otherwise, if an error occurs, an SQLite error code is returned.
119472 static int fts3EvalGatherStats(
119473 Fts3Cursor *pCsr, /* Cursor object */
119474 Fts3Expr *pExpr /* FTSQUERY_PHRASE expression */
119476 int rc = SQLITE_OK; /* Return code */
119478 assert( pExpr->eType==FTSQUERY_PHRASE );
119479 if( pExpr->aMI==0 ){
119480 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
119481 Fts3Expr *pRoot; /* Root of NEAR expression */
119482 Fts3Expr *p; /* Iterator used for several purposes */
119484 sqlite3_int64 iPrevId = pCsr->iPrevId;
119485 sqlite3_int64 iDocid;
119486 u8 bEof;
119488 /* Find the root of the NEAR expression */
119489 pRoot = pExpr;
119490 while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
119491 pRoot = pRoot->pParent;
119493 iDocid = pRoot->iDocid;
119494 bEof = pRoot->bEof;
119495 assert( pRoot->bStart );
119497 /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
119498 for(p=pRoot; p; p=p->pLeft){
119499 Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
119500 assert( pE->aMI==0 );
119501 pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));
119502 if( !pE->aMI ) return SQLITE_NOMEM;
119503 memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
119506 fts3EvalRestart(pCsr, pRoot, &rc);
119508 while( pCsr->isEof==0 && rc==SQLITE_OK ){
119511 /* Ensure the %_content statement is reset. */
119512 if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
119513 assert( sqlite3_data_count(pCsr->pStmt)==0 );
119515 /* Advance to the next document */
119516 fts3EvalNextRow(pCsr, pRoot, &rc);
119517 pCsr->isEof = pRoot->bEof;
119518 pCsr->isRequireSeek = 1;
119519 pCsr->isMatchinfoNeeded = 1;
119520 pCsr->iPrevId = pRoot->iDocid;
119521 }while( pCsr->isEof==0
119522 && pRoot->eType==FTSQUERY_NEAR
119523 && fts3EvalTestDeferredAndNear(pCsr, &rc)
119526 if( rc==SQLITE_OK && pCsr->isEof==0 ){
119527 fts3EvalUpdateCounts(pRoot);
119531 pCsr->isEof = 0;
119532 pCsr->iPrevId = iPrevId;
119534 if( bEof ){
119535 pRoot->bEof = bEof;
119536 }else{
119537 /* Caution: pRoot may iterate through docids in ascending or descending
119538 ** order. For this reason, even though it seems more defensive, the
119539 ** do loop can not be written:
119541 ** do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
119543 fts3EvalRestart(pCsr, pRoot, &rc);
119545 fts3EvalNextRow(pCsr, pRoot, &rc);
119546 assert( pRoot->bEof==0 );
119547 }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
119548 fts3EvalTestDeferredAndNear(pCsr, &rc);
119551 return rc;
119555 ** This function is used by the matchinfo() module to query a phrase
119556 ** expression node for the following information:
119558 ** 1. The total number of occurrences of the phrase in each column of
119559 ** the FTS table (considering all rows), and
119561 ** 2. For each column, the number of rows in the table for which the
119562 ** column contains at least one instance of the phrase.
119564 ** If no error occurs, SQLITE_OK is returned and the values for each column
119565 ** written into the array aiOut as follows:
119567 ** aiOut[iCol*3 + 1] = Number of occurrences
119568 ** aiOut[iCol*3 + 2] = Number of rows containing at least one instance
119570 ** Caveats:
119572 ** * If a phrase consists entirely of deferred tokens, then all output
119573 ** values are set to the number of documents in the table. In other
119574 ** words we assume that very common tokens occur exactly once in each
119575 ** column of each row of the table.
119577 ** * If a phrase contains some deferred tokens (and some non-deferred
119578 ** tokens), count the potential occurrence identified by considering
119579 ** the non-deferred tokens instead of actual phrase occurrences.
119581 ** * If the phrase is part of a NEAR expression, then only phrase instances
119582 ** that meet the NEAR constraint are included in the counts.
119584 SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
119585 Fts3Cursor *pCsr, /* FTS cursor handle */
119586 Fts3Expr *pExpr, /* Phrase expression */
119587 u32 *aiOut /* Array to write results into (see above) */
119589 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
119590 int rc = SQLITE_OK;
119591 int iCol;
119593 if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
119594 assert( pCsr->nDoc>0 );
119595 for(iCol=0; iCol<pTab->nColumn; iCol++){
119596 aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
119597 aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
119599 }else{
119600 rc = fts3EvalGatherStats(pCsr, pExpr);
119601 if( rc==SQLITE_OK ){
119602 assert( pExpr->aMI );
119603 for(iCol=0; iCol<pTab->nColumn; iCol++){
119604 aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
119605 aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
119610 return rc;
119614 ** The expression pExpr passed as the second argument to this function
119615 ** must be of type FTSQUERY_PHRASE.
119617 ** The returned value is either NULL or a pointer to a buffer containing
119618 ** a position-list indicating the occurrences of the phrase in column iCol
119619 ** of the current row.
119621 ** More specifically, the returned buffer contains 1 varint for each
119622 ** occurence of the phrase in the column, stored using the normal (delta+2)
119623 ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
119624 ** if the requested column contains "a b X c d X X" and the position-list
119625 ** for 'X' is requested, the buffer returned may contain:
119627 ** 0x04 0x05 0x03 0x01 or 0x04 0x05 0x03 0x00
119629 ** This function works regardless of whether or not the phrase is deferred,
119630 ** incremental, or neither.
119632 SQLITE_PRIVATE char *sqlite3Fts3EvalPhrasePoslist(
119633 Fts3Cursor *pCsr, /* FTS3 cursor object */
119634 Fts3Expr *pExpr, /* Phrase to return doclist for */
119635 int iCol /* Column to return position list for */
119637 Fts3Phrase *pPhrase = pExpr->pPhrase;
119638 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
119639 char *pIter = pPhrase->doclist.pList;
119640 int iThis;
119642 assert( iCol>=0 && iCol<pTab->nColumn );
119643 if( !pIter
119644 || pExpr->bEof
119645 || pExpr->iDocid!=pCsr->iPrevId
119646 || (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol)
119648 return 0;
119651 assert( pPhrase->doclist.nList>0 );
119652 if( *pIter==0x01 ){
119653 pIter++;
119654 pIter += sqlite3Fts3GetVarint32(pIter, &iThis);
119655 }else{
119656 iThis = 0;
119658 while( iThis<iCol ){
119659 fts3ColumnlistCopy(0, &pIter);
119660 if( *pIter==0x00 ) return 0;
119661 pIter++;
119662 pIter += sqlite3Fts3GetVarint32(pIter, &iThis);
119665 return ((iCol==iThis)?pIter:0);
119669 ** Free all components of the Fts3Phrase structure that were allocated by
119670 ** the eval module. Specifically, this means to free:
119672 ** * the contents of pPhrase->doclist, and
119673 ** * any Fts3MultiSegReader objects held by phrase tokens.
119675 SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
119676 if( pPhrase ){
119677 int i;
119678 sqlite3_free(pPhrase->doclist.aAll);
119679 fts3EvalInvalidatePoslist(pPhrase);
119680 memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
119681 for(i=0; i<pPhrase->nToken; i++){
119682 fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
119683 pPhrase->aToken[i].pSegcsr = 0;
119689 ** Return SQLITE_CORRUPT_VTAB.
119691 #ifdef SQLITE_DEBUG
119692 SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
119693 return SQLITE_CORRUPT_VTAB;
119695 #endif
119697 #if !SQLITE_CORE
119699 ** Initialize API pointer table, if required.
119701 SQLITE_API int sqlite3_extension_init(
119702 sqlite3 *db,
119703 char **pzErrMsg,
119704 const sqlite3_api_routines *pApi
119706 SQLITE_EXTENSION_INIT2(pApi)
119707 return sqlite3Fts3Init(db);
119709 #endif
119711 #endif
119713 /************** End of fts3.c ************************************************/
119714 /************** Begin file fts3_aux.c ****************************************/
119716 ** 2011 Jan 27
119718 ** The author disclaims copyright to this source code. In place of
119719 ** a legal notice, here is a blessing:
119721 ** May you do good and not evil.
119722 ** May you find forgiveness for yourself and forgive others.
119723 ** May you share freely, never taking more than you give.
119725 ******************************************************************************
119728 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
119730 /* #include <string.h> */
119731 /* #include <assert.h> */
119733 typedef struct Fts3auxTable Fts3auxTable;
119734 typedef struct Fts3auxCursor Fts3auxCursor;
119736 struct Fts3auxTable {
119737 sqlite3_vtab base; /* Base class used by SQLite core */
119738 Fts3Table *pFts3Tab;
119741 struct Fts3auxCursor {
119742 sqlite3_vtab_cursor base; /* Base class used by SQLite core */
119743 Fts3MultiSegReader csr; /* Must be right after "base" */
119744 Fts3SegFilter filter;
119745 char *zStop;
119746 int nStop; /* Byte-length of string zStop */
119747 int isEof; /* True if cursor is at EOF */
119748 sqlite3_int64 iRowid; /* Current rowid */
119750 int iCol; /* Current value of 'col' column */
119751 int nStat; /* Size of aStat[] array */
119752 struct Fts3auxColstats {
119753 sqlite3_int64 nDoc; /* 'documents' values for current csr row */
119754 sqlite3_int64 nOcc; /* 'occurrences' values for current csr row */
119755 } *aStat;
119759 ** Schema of the terms table.
119761 #define FTS3_TERMS_SCHEMA "CREATE TABLE x(term, col, documents, occurrences)"
119764 ** This function does all the work for both the xConnect and xCreate methods.
119765 ** These tables have no persistent representation of their own, so xConnect
119766 ** and xCreate are identical operations.
119768 static int fts3auxConnectMethod(
119769 sqlite3 *db, /* Database connection */
119770 void *pUnused, /* Unused */
119771 int argc, /* Number of elements in argv array */
119772 const char * const *argv, /* xCreate/xConnect argument array */
119773 sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
119774 char **pzErr /* OUT: sqlite3_malloc'd error message */
119776 char const *zDb; /* Name of database (e.g. "main") */
119777 char const *zFts3; /* Name of fts3 table */
119778 int nDb; /* Result of strlen(zDb) */
119779 int nFts3; /* Result of strlen(zFts3) */
119780 int nByte; /* Bytes of space to allocate here */
119781 int rc; /* value returned by declare_vtab() */
119782 Fts3auxTable *p; /* Virtual table object to return */
119784 UNUSED_PARAMETER(pUnused);
119786 /* The user should specify a single argument - the name of an fts3 table. */
119787 if( argc!=4 ){
119788 *pzErr = sqlite3_mprintf(
119789 "wrong number of arguments to fts4aux constructor"
119791 return SQLITE_ERROR;
119794 zDb = argv[1];
119795 nDb = strlen(zDb);
119796 zFts3 = argv[3];
119797 nFts3 = strlen(zFts3);
119799 rc = sqlite3_declare_vtab(db, FTS3_TERMS_SCHEMA);
119800 if( rc!=SQLITE_OK ) return rc;
119802 nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
119803 p = (Fts3auxTable *)sqlite3_malloc(nByte);
119804 if( !p ) return SQLITE_NOMEM;
119805 memset(p, 0, nByte);
119807 p->pFts3Tab = (Fts3Table *)&p[1];
119808 p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
119809 p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
119810 p->pFts3Tab->db = db;
119811 p->pFts3Tab->nIndex = 1;
119813 memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
119814 memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
119815 sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
119817 *ppVtab = (sqlite3_vtab *)p;
119818 return SQLITE_OK;
119822 ** This function does the work for both the xDisconnect and xDestroy methods.
119823 ** These tables have no persistent representation of their own, so xDisconnect
119824 ** and xDestroy are identical operations.
119826 static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
119827 Fts3auxTable *p = (Fts3auxTable *)pVtab;
119828 Fts3Table *pFts3 = p->pFts3Tab;
119829 int i;
119831 /* Free any prepared statements held */
119832 for(i=0; i<SizeofArray(pFts3->aStmt); i++){
119833 sqlite3_finalize(pFts3->aStmt[i]);
119835 sqlite3_free(pFts3->zSegmentsTbl);
119836 sqlite3_free(p);
119837 return SQLITE_OK;
119840 #define FTS4AUX_EQ_CONSTRAINT 1
119841 #define FTS4AUX_GE_CONSTRAINT 2
119842 #define FTS4AUX_LE_CONSTRAINT 4
119845 ** xBestIndex - Analyze a WHERE and ORDER BY clause.
119847 static int fts3auxBestIndexMethod(
119848 sqlite3_vtab *pVTab,
119849 sqlite3_index_info *pInfo
119851 int i;
119852 int iEq = -1;
119853 int iGe = -1;
119854 int iLe = -1;
119856 UNUSED_PARAMETER(pVTab);
119858 /* This vtab delivers always results in "ORDER BY term ASC" order. */
119859 if( pInfo->nOrderBy==1
119860 && pInfo->aOrderBy[0].iColumn==0
119861 && pInfo->aOrderBy[0].desc==0
119863 pInfo->orderByConsumed = 1;
119866 /* Search for equality and range constraints on the "term" column. */
119867 for(i=0; i<pInfo->nConstraint; i++){
119868 if( pInfo->aConstraint[i].usable && pInfo->aConstraint[i].iColumn==0 ){
119869 int op = pInfo->aConstraint[i].op;
119870 if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
119871 if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
119872 if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
119873 if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
119874 if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
119878 if( iEq>=0 ){
119879 pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
119880 pInfo->aConstraintUsage[iEq].argvIndex = 1;
119881 pInfo->estimatedCost = 5;
119882 }else{
119883 pInfo->idxNum = 0;
119884 pInfo->estimatedCost = 20000;
119885 if( iGe>=0 ){
119886 pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
119887 pInfo->aConstraintUsage[iGe].argvIndex = 1;
119888 pInfo->estimatedCost /= 2;
119890 if( iLe>=0 ){
119891 pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
119892 pInfo->aConstraintUsage[iLe].argvIndex = 1 + (iGe>=0);
119893 pInfo->estimatedCost /= 2;
119897 return SQLITE_OK;
119901 ** xOpen - Open a cursor.
119903 static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
119904 Fts3auxCursor *pCsr; /* Pointer to cursor object to return */
119906 UNUSED_PARAMETER(pVTab);
119908 pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
119909 if( !pCsr ) return SQLITE_NOMEM;
119910 memset(pCsr, 0, sizeof(Fts3auxCursor));
119912 *ppCsr = (sqlite3_vtab_cursor *)pCsr;
119913 return SQLITE_OK;
119917 ** xClose - Close a cursor.
119919 static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
119920 Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
119921 Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
119923 sqlite3Fts3SegmentsClose(pFts3);
119924 sqlite3Fts3SegReaderFinish(&pCsr->csr);
119925 sqlite3_free((void *)pCsr->filter.zTerm);
119926 sqlite3_free(pCsr->zStop);
119927 sqlite3_free(pCsr->aStat);
119928 sqlite3_free(pCsr);
119929 return SQLITE_OK;
119932 static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
119933 if( nSize>pCsr->nStat ){
119934 struct Fts3auxColstats *aNew;
119935 aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat,
119936 sizeof(struct Fts3auxColstats) * nSize
119938 if( aNew==0 ) return SQLITE_NOMEM;
119939 memset(&aNew[pCsr->nStat], 0,
119940 sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
119942 pCsr->aStat = aNew;
119943 pCsr->nStat = nSize;
119945 return SQLITE_OK;
119949 ** xNext - Advance the cursor to the next row, if any.
119951 static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
119952 Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
119953 Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
119954 int rc;
119956 /* Increment our pretend rowid value. */
119957 pCsr->iRowid++;
119959 for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
119960 if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
119963 rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
119964 if( rc==SQLITE_ROW ){
119965 int i = 0;
119966 int nDoclist = pCsr->csr.nDoclist;
119967 char *aDoclist = pCsr->csr.aDoclist;
119968 int iCol;
119970 int eState = 0;
119972 if( pCsr->zStop ){
119973 int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
119974 int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
119975 if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
119976 pCsr->isEof = 1;
119977 return SQLITE_OK;
119981 if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
119982 memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
119983 iCol = 0;
119985 while( i<nDoclist ){
119986 sqlite3_int64 v = 0;
119988 i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
119989 switch( eState ){
119990 /* State 0. In this state the integer just read was a docid. */
119991 case 0:
119992 pCsr->aStat[0].nDoc++;
119993 eState = 1;
119994 iCol = 0;
119995 break;
119997 /* State 1. In this state we are expecting either a 1, indicating
119998 ** that the following integer will be a column number, or the
119999 ** start of a position list for column 0.
120001 ** The only difference between state 1 and state 2 is that if the
120002 ** integer encountered in state 1 is not 0 or 1, then we need to
120003 ** increment the column 0 "nDoc" count for this term.
120005 case 1:
120006 assert( iCol==0 );
120007 if( v>1 ){
120008 pCsr->aStat[1].nDoc++;
120010 eState = 2;
120011 /* fall through */
120013 case 2:
120014 if( v==0 ){ /* 0x00. Next integer will be a docid. */
120015 eState = 0;
120016 }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
120017 eState = 3;
120018 }else{ /* 2 or greater. A position. */
120019 pCsr->aStat[iCol+1].nOcc++;
120020 pCsr->aStat[0].nOcc++;
120022 break;
120024 /* State 3. The integer just read is a column number. */
120025 default: assert( eState==3 );
120026 iCol = (int)v;
120027 if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
120028 pCsr->aStat[iCol+1].nDoc++;
120029 eState = 2;
120030 break;
120034 pCsr->iCol = 0;
120035 rc = SQLITE_OK;
120036 }else{
120037 pCsr->isEof = 1;
120039 return rc;
120043 ** xFilter - Initialize a cursor to point at the start of its data.
120045 static int fts3auxFilterMethod(
120046 sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
120047 int idxNum, /* Strategy index */
120048 const char *idxStr, /* Unused */
120049 int nVal, /* Number of elements in apVal */
120050 sqlite3_value **apVal /* Arguments for the indexing scheme */
120052 Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
120053 Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
120054 int rc;
120055 int isScan;
120057 UNUSED_PARAMETER(nVal);
120058 UNUSED_PARAMETER(idxStr);
120060 assert( idxStr==0 );
120061 assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
120062 || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
120063 || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
120065 isScan = (idxNum!=FTS4AUX_EQ_CONSTRAINT);
120067 /* In case this cursor is being reused, close and zero it. */
120068 testcase(pCsr->filter.zTerm);
120069 sqlite3Fts3SegReaderFinish(&pCsr->csr);
120070 sqlite3_free((void *)pCsr->filter.zTerm);
120071 sqlite3_free(pCsr->aStat);
120072 memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
120074 pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
120075 if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
120077 if( idxNum&(FTS4AUX_EQ_CONSTRAINT|FTS4AUX_GE_CONSTRAINT) ){
120078 const unsigned char *zStr = sqlite3_value_text(apVal[0]);
120079 if( zStr ){
120080 pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
120081 pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
120082 if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
120085 if( idxNum&FTS4AUX_LE_CONSTRAINT ){
120086 int iIdx = (idxNum&FTS4AUX_GE_CONSTRAINT) ? 1 : 0;
120087 pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iIdx]));
120088 pCsr->nStop = sqlite3_value_bytes(apVal[iIdx]);
120089 if( pCsr->zStop==0 ) return SQLITE_NOMEM;
120092 rc = sqlite3Fts3SegReaderCursor(pFts3, 0, FTS3_SEGCURSOR_ALL,
120093 pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
120095 if( rc==SQLITE_OK ){
120096 rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
120099 if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
120100 return rc;
120104 ** xEof - Return true if the cursor is at EOF, or false otherwise.
120106 static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
120107 Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
120108 return pCsr->isEof;
120112 ** xColumn - Return a column value.
120114 static int fts3auxColumnMethod(
120115 sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
120116 sqlite3_context *pContext, /* Context for sqlite3_result_xxx() calls */
120117 int iCol /* Index of column to read value from */
120119 Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
120121 assert( p->isEof==0 );
120122 if( iCol==0 ){ /* Column "term" */
120123 sqlite3_result_text(pContext, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
120124 }else if( iCol==1 ){ /* Column "col" */
120125 if( p->iCol ){
120126 sqlite3_result_int(pContext, p->iCol-1);
120127 }else{
120128 sqlite3_result_text(pContext, "*", -1, SQLITE_STATIC);
120130 }else if( iCol==2 ){ /* Column "documents" */
120131 sqlite3_result_int64(pContext, p->aStat[p->iCol].nDoc);
120132 }else{ /* Column "occurrences" */
120133 sqlite3_result_int64(pContext, p->aStat[p->iCol].nOcc);
120136 return SQLITE_OK;
120140 ** xRowid - Return the current rowid for the cursor.
120142 static int fts3auxRowidMethod(
120143 sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
120144 sqlite_int64 *pRowid /* OUT: Rowid value */
120146 Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
120147 *pRowid = pCsr->iRowid;
120148 return SQLITE_OK;
120152 ** Register the fts3aux module with database connection db. Return SQLITE_OK
120153 ** if successful or an error code if sqlite3_create_module() fails.
120155 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
120156 static const sqlite3_module fts3aux_module = {
120157 0, /* iVersion */
120158 fts3auxConnectMethod, /* xCreate */
120159 fts3auxConnectMethod, /* xConnect */
120160 fts3auxBestIndexMethod, /* xBestIndex */
120161 fts3auxDisconnectMethod, /* xDisconnect */
120162 fts3auxDisconnectMethod, /* xDestroy */
120163 fts3auxOpenMethod, /* xOpen */
120164 fts3auxCloseMethod, /* xClose */
120165 fts3auxFilterMethod, /* xFilter */
120166 fts3auxNextMethod, /* xNext */
120167 fts3auxEofMethod, /* xEof */
120168 fts3auxColumnMethod, /* xColumn */
120169 fts3auxRowidMethod, /* xRowid */
120170 0, /* xUpdate */
120171 0, /* xBegin */
120172 0, /* xSync */
120173 0, /* xCommit */
120174 0, /* xRollback */
120175 0, /* xFindFunction */
120176 0, /* xRename */
120177 0, /* xSavepoint */
120178 0, /* xRelease */
120179 0 /* xRollbackTo */
120181 int rc; /* Return code */
120183 rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
120184 return rc;
120187 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
120189 /************** End of fts3_aux.c ********************************************/
120190 /************** Begin file fts3_expr.c ***************************************/
120192 ** 2008 Nov 28
120194 ** The author disclaims copyright to this source code. In place of
120195 ** a legal notice, here is a blessing:
120197 ** May you do good and not evil.
120198 ** May you find forgiveness for yourself and forgive others.
120199 ** May you share freely, never taking more than you give.
120201 ******************************************************************************
120203 ** This module contains code that implements a parser for fts3 query strings
120204 ** (the right-hand argument to the MATCH operator). Because the supported
120205 ** syntax is relatively simple, the whole tokenizer/parser system is
120206 ** hand-coded.
120208 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
120211 ** By default, this module parses the legacy syntax that has been
120212 ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
120213 ** is defined, then it uses the new syntax. The differences between
120214 ** the new and the old syntaxes are:
120216 ** a) The new syntax supports parenthesis. The old does not.
120218 ** b) The new syntax supports the AND and NOT operators. The old does not.
120220 ** c) The old syntax supports the "-" token qualifier. This is not
120221 ** supported by the new syntax (it is replaced by the NOT operator).
120223 ** d) When using the old syntax, the OR operator has a greater precedence
120224 ** than an implicit AND. When using the new, both implicity and explicit
120225 ** AND operators have a higher precedence than OR.
120227 ** If compiled with SQLITE_TEST defined, then this module exports the
120228 ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
120229 ** to zero causes the module to use the old syntax. If it is set to
120230 ** non-zero the new syntax is activated. This is so both syntaxes can
120231 ** be tested using a single build of testfixture.
120233 ** The following describes the syntax supported by the fts3 MATCH
120234 ** operator in a similar format to that used by the lemon parser
120235 ** generator. This module does not use actually lemon, it uses a
120236 ** custom parser.
120238 ** query ::= andexpr (OR andexpr)*.
120240 ** andexpr ::= notexpr (AND? notexpr)*.
120242 ** notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
120243 ** notexpr ::= LP query RP.
120245 ** nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
120247 ** distance_opt ::= .
120248 ** distance_opt ::= / INTEGER.
120250 ** phrase ::= TOKEN.
120251 ** phrase ::= COLUMN:TOKEN.
120252 ** phrase ::= "TOKEN TOKEN TOKEN...".
120255 #ifdef SQLITE_TEST
120256 SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
120257 #else
120258 # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
120259 # define sqlite3_fts3_enable_parentheses 1
120260 # else
120261 # define sqlite3_fts3_enable_parentheses 0
120262 # endif
120263 #endif
120266 ** Default span for NEAR operators.
120268 #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
120270 /* #include <string.h> */
120271 /* #include <assert.h> */
120274 ** isNot:
120275 ** This variable is used by function getNextNode(). When getNextNode() is
120276 ** called, it sets ParseContext.isNot to true if the 'next node' is a
120277 ** FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
120278 ** FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
120279 ** zero.
120281 typedef struct ParseContext ParseContext;
120282 struct ParseContext {
120283 sqlite3_tokenizer *pTokenizer; /* Tokenizer module */
120284 const char **azCol; /* Array of column names for fts3 table */
120285 int bFts4; /* True to allow FTS4-only syntax */
120286 int nCol; /* Number of entries in azCol[] */
120287 int iDefaultCol; /* Default column to query */
120288 int isNot; /* True if getNextNode() sees a unary - */
120289 sqlite3_context *pCtx; /* Write error message here */
120290 int nNest; /* Number of nested brackets */
120294 ** This function is equivalent to the standard isspace() function.
120296 ** The standard isspace() can be awkward to use safely, because although it
120297 ** is defined to accept an argument of type int, its behaviour when passed
120298 ** an integer that falls outside of the range of the unsigned char type
120299 ** is undefined (and sometimes, "undefined" means segfault). This wrapper
120300 ** is defined to accept an argument of type char, and always returns 0 for
120301 ** any values that fall outside of the range of the unsigned char type (i.e.
120302 ** negative values).
120304 static int fts3isspace(char c){
120305 return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
120309 ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
120310 ** zero the memory before returning a pointer to it. If unsuccessful,
120311 ** return NULL.
120313 static void *fts3MallocZero(int nByte){
120314 void *pRet = sqlite3_malloc(nByte);
120315 if( pRet ) memset(pRet, 0, nByte);
120316 return pRet;
120321 ** Extract the next token from buffer z (length n) using the tokenizer
120322 ** and other information (column names etc.) in pParse. Create an Fts3Expr
120323 ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
120324 ** single token and set *ppExpr to point to it. If the end of the buffer is
120325 ** reached before a token is found, set *ppExpr to zero. It is the
120326 ** responsibility of the caller to eventually deallocate the allocated
120327 ** Fts3Expr structure (if any) by passing it to sqlite3_free().
120329 ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
120330 ** fails.
120332 static int getNextToken(
120333 ParseContext *pParse, /* fts3 query parse context */
120334 int iCol, /* Value for Fts3Phrase.iColumn */
120335 const char *z, int n, /* Input string */
120336 Fts3Expr **ppExpr, /* OUT: expression */
120337 int *pnConsumed /* OUT: Number of bytes consumed */
120339 sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
120340 sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
120341 int rc;
120342 sqlite3_tokenizer_cursor *pCursor;
120343 Fts3Expr *pRet = 0;
120344 int nConsumed = 0;
120346 rc = pModule->xOpen(pTokenizer, z, n, &pCursor);
120347 if( rc==SQLITE_OK ){
120348 const char *zToken;
120349 int nToken, iStart, iEnd, iPosition;
120350 int nByte; /* total space to allocate */
120352 pCursor->pTokenizer = pTokenizer;
120353 rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
120355 if( rc==SQLITE_OK ){
120356 nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
120357 pRet = (Fts3Expr *)fts3MallocZero(nByte);
120358 if( !pRet ){
120359 rc = SQLITE_NOMEM;
120360 }else{
120361 pRet->eType = FTSQUERY_PHRASE;
120362 pRet->pPhrase = (Fts3Phrase *)&pRet[1];
120363 pRet->pPhrase->nToken = 1;
120364 pRet->pPhrase->iColumn = iCol;
120365 pRet->pPhrase->aToken[0].n = nToken;
120366 pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
120367 memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
120369 if( iEnd<n && z[iEnd]=='*' ){
120370 pRet->pPhrase->aToken[0].isPrefix = 1;
120371 iEnd++;
120374 while( 1 ){
120375 if( !sqlite3_fts3_enable_parentheses
120376 && iStart>0 && z[iStart-1]=='-'
120378 pParse->isNot = 1;
120379 iStart--;
120380 }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
120381 pRet->pPhrase->aToken[0].bFirst = 1;
120382 iStart--;
120383 }else{
120384 break;
120389 nConsumed = iEnd;
120392 pModule->xClose(pCursor);
120395 *pnConsumed = nConsumed;
120396 *ppExpr = pRet;
120397 return rc;
120402 ** Enlarge a memory allocation. If an out-of-memory allocation occurs,
120403 ** then free the old allocation.
120405 static void *fts3ReallocOrFree(void *pOrig, int nNew){
120406 void *pRet = sqlite3_realloc(pOrig, nNew);
120407 if( !pRet ){
120408 sqlite3_free(pOrig);
120410 return pRet;
120414 ** Buffer zInput, length nInput, contains the contents of a quoted string
120415 ** that appeared as part of an fts3 query expression. Neither quote character
120416 ** is included in the buffer. This function attempts to tokenize the entire
120417 ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
120418 ** containing the results.
120420 ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
120421 ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
120422 ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
120423 ** to 0.
120425 static int getNextString(
120426 ParseContext *pParse, /* fts3 query parse context */
120427 const char *zInput, int nInput, /* Input string */
120428 Fts3Expr **ppExpr /* OUT: expression */
120430 sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
120431 sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
120432 int rc;
120433 Fts3Expr *p = 0;
120434 sqlite3_tokenizer_cursor *pCursor = 0;
120435 char *zTemp = 0;
120436 int nTemp = 0;
120438 const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
120439 int nToken = 0;
120441 /* The final Fts3Expr data structure, including the Fts3Phrase,
120442 ** Fts3PhraseToken structures token buffers are all stored as a single
120443 ** allocation so that the expression can be freed with a single call to
120444 ** sqlite3_free(). Setting this up requires a two pass approach.
120446 ** The first pass, in the block below, uses a tokenizer cursor to iterate
120447 ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
120448 ** to assemble data in two dynamic buffers:
120450 ** Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
120451 ** structure, followed by the array of Fts3PhraseToken
120452 ** structures. This pass only populates the Fts3PhraseToken array.
120454 ** Buffer zTemp: Contains copies of all tokens.
120456 ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
120457 ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
120458 ** structures.
120460 rc = pModule->xOpen(pTokenizer, zInput, nInput, &pCursor);
120461 if( rc==SQLITE_OK ){
120462 int ii;
120463 pCursor->pTokenizer = pTokenizer;
120464 for(ii=0; rc==SQLITE_OK; ii++){
120465 const char *zByte;
120466 int nByte, iBegin, iEnd, iPos;
120467 rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
120468 if( rc==SQLITE_OK ){
120469 Fts3PhraseToken *pToken;
120471 p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
120472 if( !p ) goto no_mem;
120474 zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
120475 if( !zTemp ) goto no_mem;
120477 assert( nToken==ii );
120478 pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
120479 memset(pToken, 0, sizeof(Fts3PhraseToken));
120481 memcpy(&zTemp[nTemp], zByte, nByte);
120482 nTemp += nByte;
120484 pToken->n = nByte;
120485 pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
120486 pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
120487 nToken = ii+1;
120491 pModule->xClose(pCursor);
120492 pCursor = 0;
120495 if( rc==SQLITE_DONE ){
120496 int jj;
120497 char *zBuf = 0;
120499 p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
120500 if( !p ) goto no_mem;
120501 memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
120502 p->eType = FTSQUERY_PHRASE;
120503 p->pPhrase = (Fts3Phrase *)&p[1];
120504 p->pPhrase->iColumn = pParse->iDefaultCol;
120505 p->pPhrase->nToken = nToken;
120507 zBuf = (char *)&p->pPhrase->aToken[nToken];
120508 if( zTemp ){
120509 memcpy(zBuf, zTemp, nTemp);
120510 sqlite3_free(zTemp);
120511 }else{
120512 assert( nTemp==0 );
120515 for(jj=0; jj<p->pPhrase->nToken; jj++){
120516 p->pPhrase->aToken[jj].z = zBuf;
120517 zBuf += p->pPhrase->aToken[jj].n;
120519 rc = SQLITE_OK;
120522 *ppExpr = p;
120523 return rc;
120524 no_mem:
120526 if( pCursor ){
120527 pModule->xClose(pCursor);
120529 sqlite3_free(zTemp);
120530 sqlite3_free(p);
120531 *ppExpr = 0;
120532 return SQLITE_NOMEM;
120536 ** Function getNextNode(), which is called by fts3ExprParse(), may itself
120537 ** call fts3ExprParse(). So this forward declaration is required.
120539 static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
120542 ** The output variable *ppExpr is populated with an allocated Fts3Expr
120543 ** structure, or set to 0 if the end of the input buffer is reached.
120545 ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
120546 ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
120547 ** If SQLITE_ERROR is returned, pContext is populated with an error message.
120549 static int getNextNode(
120550 ParseContext *pParse, /* fts3 query parse context */
120551 const char *z, int n, /* Input string */
120552 Fts3Expr **ppExpr, /* OUT: expression */
120553 int *pnConsumed /* OUT: Number of bytes consumed */
120555 static const struct Fts3Keyword {
120556 char *z; /* Keyword text */
120557 unsigned char n; /* Length of the keyword */
120558 unsigned char parenOnly; /* Only valid in paren mode */
120559 unsigned char eType; /* Keyword code */
120560 } aKeyword[] = {
120561 { "OR" , 2, 0, FTSQUERY_OR },
120562 { "AND", 3, 1, FTSQUERY_AND },
120563 { "NOT", 3, 1, FTSQUERY_NOT },
120564 { "NEAR", 4, 0, FTSQUERY_NEAR }
120566 int ii;
120567 int iCol;
120568 int iColLen;
120569 int rc;
120570 Fts3Expr *pRet = 0;
120572 const char *zInput = z;
120573 int nInput = n;
120575 pParse->isNot = 0;
120577 /* Skip over any whitespace before checking for a keyword, an open or
120578 ** close bracket, or a quoted string.
120580 while( nInput>0 && fts3isspace(*zInput) ){
120581 nInput--;
120582 zInput++;
120584 if( nInput==0 ){
120585 return SQLITE_DONE;
120588 /* See if we are dealing with a keyword. */
120589 for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
120590 const struct Fts3Keyword *pKey = &aKeyword[ii];
120592 if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
120593 continue;
120596 if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
120597 int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
120598 int nKey = pKey->n;
120599 char cNext;
120601 /* If this is a "NEAR" keyword, check for an explicit nearness. */
120602 if( pKey->eType==FTSQUERY_NEAR ){
120603 assert( nKey==4 );
120604 if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
120605 nNear = 0;
120606 for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
120607 nNear = nNear * 10 + (zInput[nKey] - '0');
120612 /* At this point this is probably a keyword. But for that to be true,
120613 ** the next byte must contain either whitespace, an open or close
120614 ** parenthesis, a quote character, or EOF.
120616 cNext = zInput[nKey];
120617 if( fts3isspace(cNext)
120618 || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
120620 pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
120621 if( !pRet ){
120622 return SQLITE_NOMEM;
120624 pRet->eType = pKey->eType;
120625 pRet->nNear = nNear;
120626 *ppExpr = pRet;
120627 *pnConsumed = (int)((zInput - z) + nKey);
120628 return SQLITE_OK;
120631 /* Turns out that wasn't a keyword after all. This happens if the
120632 ** user has supplied a token such as "ORacle". Continue.
120637 /* Check for an open bracket. */
120638 if( sqlite3_fts3_enable_parentheses ){
120639 if( *zInput=='(' ){
120640 int nConsumed;
120641 pParse->nNest++;
120642 rc = fts3ExprParse(pParse, &zInput[1], nInput-1, ppExpr, &nConsumed);
120643 if( rc==SQLITE_OK && !*ppExpr ){
120644 rc = SQLITE_DONE;
120646 *pnConsumed = (int)((zInput - z) + 1 + nConsumed);
120647 return rc;
120650 /* Check for a close bracket. */
120651 if( *zInput==')' ){
120652 pParse->nNest--;
120653 *pnConsumed = (int)((zInput - z) + 1);
120654 return SQLITE_DONE;
120658 /* See if we are dealing with a quoted phrase. If this is the case, then
120659 ** search for the closing quote and pass the whole string to getNextString()
120660 ** for processing. This is easy to do, as fts3 has no syntax for escaping
120661 ** a quote character embedded in a string.
120663 if( *zInput=='"' ){
120664 for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
120665 *pnConsumed = (int)((zInput - z) + ii + 1);
120666 if( ii==nInput ){
120667 return SQLITE_ERROR;
120669 return getNextString(pParse, &zInput[1], ii-1, ppExpr);
120673 /* If control flows to this point, this must be a regular token, or
120674 ** the end of the input. Read a regular token using the sqlite3_tokenizer
120675 ** interface. Before doing so, figure out if there is an explicit
120676 ** column specifier for the token.
120678 ** TODO: Strangely, it is not possible to associate a column specifier
120679 ** with a quoted phrase, only with a single token. Not sure if this was
120680 ** an implementation artifact or an intentional decision when fts3 was
120681 ** first implemented. Whichever it was, this module duplicates the
120682 ** limitation.
120684 iCol = pParse->iDefaultCol;
120685 iColLen = 0;
120686 for(ii=0; ii<pParse->nCol; ii++){
120687 const char *zStr = pParse->azCol[ii];
120688 int nStr = (int)strlen(zStr);
120689 if( nInput>nStr && zInput[nStr]==':'
120690 && sqlite3_strnicmp(zStr, zInput, nStr)==0
120692 iCol = ii;
120693 iColLen = (int)((zInput - z) + nStr + 1);
120694 break;
120697 rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
120698 *pnConsumed += iColLen;
120699 return rc;
120703 ** The argument is an Fts3Expr structure for a binary operator (any type
120704 ** except an FTSQUERY_PHRASE). Return an integer value representing the
120705 ** precedence of the operator. Lower values have a higher precedence (i.e.
120706 ** group more tightly). For example, in the C language, the == operator
120707 ** groups more tightly than ||, and would therefore have a higher precedence.
120709 ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
120710 ** is defined), the order of the operators in precedence from highest to
120711 ** lowest is:
120713 ** NEAR
120714 ** NOT
120715 ** AND (including implicit ANDs)
120716 ** OR
120718 ** Note that when using the old query syntax, the OR operator has a higher
120719 ** precedence than the AND operator.
120721 static int opPrecedence(Fts3Expr *p){
120722 assert( p->eType!=FTSQUERY_PHRASE );
120723 if( sqlite3_fts3_enable_parentheses ){
120724 return p->eType;
120725 }else if( p->eType==FTSQUERY_NEAR ){
120726 return 1;
120727 }else if( p->eType==FTSQUERY_OR ){
120728 return 2;
120730 assert( p->eType==FTSQUERY_AND );
120731 return 3;
120735 ** Argument ppHead contains a pointer to the current head of a query
120736 ** expression tree being parsed. pPrev is the expression node most recently
120737 ** inserted into the tree. This function adds pNew, which is always a binary
120738 ** operator node, into the expression tree based on the relative precedence
120739 ** of pNew and the existing nodes of the tree. This may result in the head
120740 ** of the tree changing, in which case *ppHead is set to the new root node.
120742 static void insertBinaryOperator(
120743 Fts3Expr **ppHead, /* Pointer to the root node of a tree */
120744 Fts3Expr *pPrev, /* Node most recently inserted into the tree */
120745 Fts3Expr *pNew /* New binary node to insert into expression tree */
120747 Fts3Expr *pSplit = pPrev;
120748 while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
120749 pSplit = pSplit->pParent;
120752 if( pSplit->pParent ){
120753 assert( pSplit->pParent->pRight==pSplit );
120754 pSplit->pParent->pRight = pNew;
120755 pNew->pParent = pSplit->pParent;
120756 }else{
120757 *ppHead = pNew;
120759 pNew->pLeft = pSplit;
120760 pSplit->pParent = pNew;
120764 ** Parse the fts3 query expression found in buffer z, length n. This function
120765 ** returns either when the end of the buffer is reached or an unmatched
120766 ** closing bracket - ')' - is encountered.
120768 ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
120769 ** parsed form of the expression and *pnConsumed is set to the number of
120770 ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
120771 ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
120773 static int fts3ExprParse(
120774 ParseContext *pParse, /* fts3 query parse context */
120775 const char *z, int n, /* Text of MATCH query */
120776 Fts3Expr **ppExpr, /* OUT: Parsed query structure */
120777 int *pnConsumed /* OUT: Number of bytes consumed */
120779 Fts3Expr *pRet = 0;
120780 Fts3Expr *pPrev = 0;
120781 Fts3Expr *pNotBranch = 0; /* Only used in legacy parse mode */
120782 int nIn = n;
120783 const char *zIn = z;
120784 int rc = SQLITE_OK;
120785 int isRequirePhrase = 1;
120787 while( rc==SQLITE_OK ){
120788 Fts3Expr *p = 0;
120789 int nByte = 0;
120790 rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
120791 if( rc==SQLITE_OK ){
120792 int isPhrase;
120794 if( !sqlite3_fts3_enable_parentheses
120795 && p->eType==FTSQUERY_PHRASE && pParse->isNot
120797 /* Create an implicit NOT operator. */
120798 Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
120799 if( !pNot ){
120800 sqlite3Fts3ExprFree(p);
120801 rc = SQLITE_NOMEM;
120802 goto exprparse_out;
120804 pNot->eType = FTSQUERY_NOT;
120805 pNot->pRight = p;
120806 if( pNotBranch ){
120807 pNot->pLeft = pNotBranch;
120809 pNotBranch = pNot;
120810 p = pPrev;
120811 }else{
120812 int eType = p->eType;
120813 isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
120815 /* The isRequirePhrase variable is set to true if a phrase or
120816 ** an expression contained in parenthesis is required. If a
120817 ** binary operator (AND, OR, NOT or NEAR) is encounted when
120818 ** isRequirePhrase is set, this is a syntax error.
120820 if( !isPhrase && isRequirePhrase ){
120821 sqlite3Fts3ExprFree(p);
120822 rc = SQLITE_ERROR;
120823 goto exprparse_out;
120826 if( isPhrase && !isRequirePhrase ){
120827 /* Insert an implicit AND operator. */
120828 Fts3Expr *pAnd;
120829 assert( pRet && pPrev );
120830 pAnd = fts3MallocZero(sizeof(Fts3Expr));
120831 if( !pAnd ){
120832 sqlite3Fts3ExprFree(p);
120833 rc = SQLITE_NOMEM;
120834 goto exprparse_out;
120836 pAnd->eType = FTSQUERY_AND;
120837 insertBinaryOperator(&pRet, pPrev, pAnd);
120838 pPrev = pAnd;
120841 /* This test catches attempts to make either operand of a NEAR
120842 ** operator something other than a phrase. For example, either of
120843 ** the following:
120845 ** (bracketed expression) NEAR phrase
120846 ** phrase NEAR (bracketed expression)
120848 ** Return an error in either case.
120850 if( pPrev && (
120851 (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
120852 || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
120854 sqlite3Fts3ExprFree(p);
120855 rc = SQLITE_ERROR;
120856 goto exprparse_out;
120859 if( isPhrase ){
120860 if( pRet ){
120861 assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
120862 pPrev->pRight = p;
120863 p->pParent = pPrev;
120864 }else{
120865 pRet = p;
120867 }else{
120868 insertBinaryOperator(&pRet, pPrev, p);
120870 isRequirePhrase = !isPhrase;
120872 assert( nByte>0 );
120874 assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
120875 nIn -= nByte;
120876 zIn += nByte;
120877 pPrev = p;
120880 if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
120881 rc = SQLITE_ERROR;
120884 if( rc==SQLITE_DONE ){
120885 rc = SQLITE_OK;
120886 if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
120887 if( !pRet ){
120888 rc = SQLITE_ERROR;
120889 }else{
120890 Fts3Expr *pIter = pNotBranch;
120891 while( pIter->pLeft ){
120892 pIter = pIter->pLeft;
120894 pIter->pLeft = pRet;
120895 pRet = pNotBranch;
120899 *pnConsumed = n - nIn;
120901 exprparse_out:
120902 if( rc!=SQLITE_OK ){
120903 sqlite3Fts3ExprFree(pRet);
120904 sqlite3Fts3ExprFree(pNotBranch);
120905 pRet = 0;
120907 *ppExpr = pRet;
120908 return rc;
120912 ** Parameters z and n contain a pointer to and length of a buffer containing
120913 ** an fts3 query expression, respectively. This function attempts to parse the
120914 ** query expression and create a tree of Fts3Expr structures representing the
120915 ** parsed expression. If successful, *ppExpr is set to point to the head
120916 ** of the parsed expression tree and SQLITE_OK is returned. If an error
120917 ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
120918 ** error) is returned and *ppExpr is set to 0.
120920 ** If parameter n is a negative number, then z is assumed to point to a
120921 ** nul-terminated string and the length is determined using strlen().
120923 ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
120924 ** use to normalize query tokens while parsing the expression. The azCol[]
120925 ** array, which is assumed to contain nCol entries, should contain the names
120926 ** of each column in the target fts3 table, in order from left to right.
120927 ** Column names must be nul-terminated strings.
120929 ** The iDefaultCol parameter should be passed the index of the table column
120930 ** that appears on the left-hand-side of the MATCH operator (the default
120931 ** column to match against for tokens for which a column name is not explicitly
120932 ** specified as part of the query string), or -1 if tokens may by default
120933 ** match any table column.
120935 SQLITE_PRIVATE int sqlite3Fts3ExprParse(
120936 sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
120937 char **azCol, /* Array of column names for fts3 table */
120938 int bFts4, /* True to allow FTS4-only syntax */
120939 int nCol, /* Number of entries in azCol[] */
120940 int iDefaultCol, /* Default column to query */
120941 const char *z, int n, /* Text of MATCH query */
120942 Fts3Expr **ppExpr /* OUT: Parsed query structure */
120944 int nParsed;
120945 int rc;
120946 ParseContext sParse;
120947 sParse.pTokenizer = pTokenizer;
120948 sParse.azCol = (const char **)azCol;
120949 sParse.nCol = nCol;
120950 sParse.iDefaultCol = iDefaultCol;
120951 sParse.nNest = 0;
120952 sParse.bFts4 = bFts4;
120953 if( z==0 ){
120954 *ppExpr = 0;
120955 return SQLITE_OK;
120957 if( n<0 ){
120958 n = (int)strlen(z);
120960 rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
120962 /* Check for mismatched parenthesis */
120963 if( rc==SQLITE_OK && sParse.nNest ){
120964 rc = SQLITE_ERROR;
120965 sqlite3Fts3ExprFree(*ppExpr);
120966 *ppExpr = 0;
120969 return rc;
120973 ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
120975 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *p){
120976 if( p ){
120977 assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
120978 sqlite3Fts3ExprFree(p->pLeft);
120979 sqlite3Fts3ExprFree(p->pRight);
120980 sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
120981 sqlite3_free(p->aMI);
120982 sqlite3_free(p);
120986 /****************************************************************************
120987 *****************************************************************************
120988 ** Everything after this point is just test code.
120991 #ifdef SQLITE_TEST
120993 /* #include <stdio.h> */
120996 ** Function to query the hash-table of tokenizers (see README.tokenizers).
120998 static int queryTestTokenizer(
120999 sqlite3 *db,
121000 const char *zName,
121001 const sqlite3_tokenizer_module **pp
121003 int rc;
121004 sqlite3_stmt *pStmt;
121005 const char zSql[] = "SELECT fts3_tokenizer(?)";
121007 *pp = 0;
121008 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
121009 if( rc!=SQLITE_OK ){
121010 return rc;
121013 sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
121014 if( SQLITE_ROW==sqlite3_step(pStmt) ){
121015 if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
121016 memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
121020 return sqlite3_finalize(pStmt);
121024 ** Return a pointer to a buffer containing a text representation of the
121025 ** expression passed as the first argument. The buffer is obtained from
121026 ** sqlite3_malloc(). It is the responsibility of the caller to use
121027 ** sqlite3_free() to release the memory. If an OOM condition is encountered,
121028 ** NULL is returned.
121030 ** If the second argument is not NULL, then its contents are prepended to
121031 ** the returned expression text and then freed using sqlite3_free().
121033 static char *exprToString(Fts3Expr *pExpr, char *zBuf){
121034 switch( pExpr->eType ){
121035 case FTSQUERY_PHRASE: {
121036 Fts3Phrase *pPhrase = pExpr->pPhrase;
121037 int i;
121038 zBuf = sqlite3_mprintf(
121039 "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
121040 for(i=0; zBuf && i<pPhrase->nToken; i++){
121041 zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
121042 pPhrase->aToken[i].n, pPhrase->aToken[i].z,
121043 (pPhrase->aToken[i].isPrefix?"+":"")
121046 return zBuf;
121049 case FTSQUERY_NEAR:
121050 zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
121051 break;
121052 case FTSQUERY_NOT:
121053 zBuf = sqlite3_mprintf("%zNOT ", zBuf);
121054 break;
121055 case FTSQUERY_AND:
121056 zBuf = sqlite3_mprintf("%zAND ", zBuf);
121057 break;
121058 case FTSQUERY_OR:
121059 zBuf = sqlite3_mprintf("%zOR ", zBuf);
121060 break;
121063 if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
121064 if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
121065 if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
121067 if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
121068 if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
121070 return zBuf;
121074 ** This is the implementation of a scalar SQL function used to test the
121075 ** expression parser. It should be called as follows:
121077 ** fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
121079 ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
121080 ** to parse the query expression (see README.tokenizers). The second argument
121081 ** is the query expression to parse. Each subsequent argument is the name
121082 ** of a column of the fts3 table that the query expression may refer to.
121083 ** For example:
121085 ** SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
121087 static void fts3ExprTest(
121088 sqlite3_context *context,
121089 int argc,
121090 sqlite3_value **argv
121092 sqlite3_tokenizer_module const *pModule = 0;
121093 sqlite3_tokenizer *pTokenizer = 0;
121094 int rc;
121095 char **azCol = 0;
121096 const char *zExpr;
121097 int nExpr;
121098 int nCol;
121099 int ii;
121100 Fts3Expr *pExpr;
121101 char *zBuf = 0;
121102 sqlite3 *db = sqlite3_context_db_handle(context);
121104 if( argc<3 ){
121105 sqlite3_result_error(context,
121106 "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
121108 return;
121111 rc = queryTestTokenizer(db,
121112 (const char *)sqlite3_value_text(argv[0]), &pModule);
121113 if( rc==SQLITE_NOMEM ){
121114 sqlite3_result_error_nomem(context);
121115 goto exprtest_out;
121116 }else if( !pModule ){
121117 sqlite3_result_error(context, "No such tokenizer module", -1);
121118 goto exprtest_out;
121121 rc = pModule->xCreate(0, 0, &pTokenizer);
121122 assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
121123 if( rc==SQLITE_NOMEM ){
121124 sqlite3_result_error_nomem(context);
121125 goto exprtest_out;
121127 pTokenizer->pModule = pModule;
121129 zExpr = (const char *)sqlite3_value_text(argv[1]);
121130 nExpr = sqlite3_value_bytes(argv[1]);
121131 nCol = argc-2;
121132 azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
121133 if( !azCol ){
121134 sqlite3_result_error_nomem(context);
121135 goto exprtest_out;
121137 for(ii=0; ii<nCol; ii++){
121138 azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
121141 rc = sqlite3Fts3ExprParse(
121142 pTokenizer, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
121144 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
121145 sqlite3_result_error(context, "Error parsing expression", -1);
121146 }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
121147 sqlite3_result_error_nomem(context);
121148 }else{
121149 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
121150 sqlite3_free(zBuf);
121153 sqlite3Fts3ExprFree(pExpr);
121155 exprtest_out:
121156 if( pModule && pTokenizer ){
121157 rc = pModule->xDestroy(pTokenizer);
121159 sqlite3_free(azCol);
121163 ** Register the query expression parser test function fts3_exprtest()
121164 ** with database connection db.
121166 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
121167 return sqlite3_create_function(
121168 db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
121172 #endif
121173 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
121175 /************** End of fts3_expr.c *******************************************/
121176 /************** Begin file fts3_hash.c ***************************************/
121178 ** 2001 September 22
121180 ** The author disclaims copyright to this source code. In place of
121181 ** a legal notice, here is a blessing:
121183 ** May you do good and not evil.
121184 ** May you find forgiveness for yourself and forgive others.
121185 ** May you share freely, never taking more than you give.
121187 *************************************************************************
121188 ** This is the implementation of generic hash-tables used in SQLite.
121189 ** We've modified it slightly to serve as a standalone hash table
121190 ** implementation for the full-text indexing module.
121194 ** The code in this file is only compiled if:
121196 ** * The FTS3 module is being built as an extension
121197 ** (in which case SQLITE_CORE is not defined), or
121199 ** * The FTS3 module is being built into the core of
121200 ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
121202 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
121204 /* #include <assert.h> */
121205 /* #include <stdlib.h> */
121206 /* #include <string.h> */
121210 ** Malloc and Free functions
121212 static void *fts3HashMalloc(int n){
121213 void *p = sqlite3_malloc(n);
121214 if( p ){
121215 memset(p, 0, n);
121217 return p;
121219 static void fts3HashFree(void *p){
121220 sqlite3_free(p);
121223 /* Turn bulk memory into a hash table object by initializing the
121224 ** fields of the Hash structure.
121226 ** "pNew" is a pointer to the hash table that is to be initialized.
121227 ** keyClass is one of the constants
121228 ** FTS3_HASH_BINARY or FTS3_HASH_STRING. The value of keyClass
121229 ** determines what kind of key the hash table will use. "copyKey" is
121230 ** true if the hash table should make its own private copy of keys and
121231 ** false if it should just use the supplied pointer.
121233 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
121234 assert( pNew!=0 );
121235 assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
121236 pNew->keyClass = keyClass;
121237 pNew->copyKey = copyKey;
121238 pNew->first = 0;
121239 pNew->count = 0;
121240 pNew->htsize = 0;
121241 pNew->ht = 0;
121244 /* Remove all entries from a hash table. Reclaim all memory.
121245 ** Call this routine to delete a hash table or to reset a hash table
121246 ** to the empty state.
121248 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
121249 Fts3HashElem *elem; /* For looping over all elements of the table */
121251 assert( pH!=0 );
121252 elem = pH->first;
121253 pH->first = 0;
121254 fts3HashFree(pH->ht);
121255 pH->ht = 0;
121256 pH->htsize = 0;
121257 while( elem ){
121258 Fts3HashElem *next_elem = elem->next;
121259 if( pH->copyKey && elem->pKey ){
121260 fts3HashFree(elem->pKey);
121262 fts3HashFree(elem);
121263 elem = next_elem;
121265 pH->count = 0;
121269 ** Hash and comparison functions when the mode is FTS3_HASH_STRING
121271 static int fts3StrHash(const void *pKey, int nKey){
121272 const char *z = (const char *)pKey;
121273 int h = 0;
121274 if( nKey<=0 ) nKey = (int) strlen(z);
121275 while( nKey > 0 ){
121276 h = (h<<3) ^ h ^ *z++;
121277 nKey--;
121279 return h & 0x7fffffff;
121281 static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
121282 if( n1!=n2 ) return 1;
121283 return strncmp((const char*)pKey1,(const char*)pKey2,n1);
121287 ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
121289 static int fts3BinHash(const void *pKey, int nKey){
121290 int h = 0;
121291 const char *z = (const char *)pKey;
121292 while( nKey-- > 0 ){
121293 h = (h<<3) ^ h ^ *(z++);
121295 return h & 0x7fffffff;
121297 static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
121298 if( n1!=n2 ) return 1;
121299 return memcmp(pKey1,pKey2,n1);
121303 ** Return a pointer to the appropriate hash function given the key class.
121305 ** The C syntax in this function definition may be unfamilar to some
121306 ** programmers, so we provide the following additional explanation:
121308 ** The name of the function is "ftsHashFunction". The function takes a
121309 ** single parameter "keyClass". The return value of ftsHashFunction()
121310 ** is a pointer to another function. Specifically, the return value
121311 ** of ftsHashFunction() is a pointer to a function that takes two parameters
121312 ** with types "const void*" and "int" and returns an "int".
121314 static int (*ftsHashFunction(int keyClass))(const void*,int){
121315 if( keyClass==FTS3_HASH_STRING ){
121316 return &fts3StrHash;
121317 }else{
121318 assert( keyClass==FTS3_HASH_BINARY );
121319 return &fts3BinHash;
121324 ** Return a pointer to the appropriate hash function given the key class.
121326 ** For help in interpreted the obscure C code in the function definition,
121327 ** see the header comment on the previous function.
121329 static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
121330 if( keyClass==FTS3_HASH_STRING ){
121331 return &fts3StrCompare;
121332 }else{
121333 assert( keyClass==FTS3_HASH_BINARY );
121334 return &fts3BinCompare;
121338 /* Link an element into the hash table
121340 static void fts3HashInsertElement(
121341 Fts3Hash *pH, /* The complete hash table */
121342 struct _fts3ht *pEntry, /* The entry into which pNew is inserted */
121343 Fts3HashElem *pNew /* The element to be inserted */
121345 Fts3HashElem *pHead; /* First element already in pEntry */
121346 pHead = pEntry->chain;
121347 if( pHead ){
121348 pNew->next = pHead;
121349 pNew->prev = pHead->prev;
121350 if( pHead->prev ){ pHead->prev->next = pNew; }
121351 else { pH->first = pNew; }
121352 pHead->prev = pNew;
121353 }else{
121354 pNew->next = pH->first;
121355 if( pH->first ){ pH->first->prev = pNew; }
121356 pNew->prev = 0;
121357 pH->first = pNew;
121359 pEntry->count++;
121360 pEntry->chain = pNew;
121364 /* Resize the hash table so that it cantains "new_size" buckets.
121365 ** "new_size" must be a power of 2. The hash table might fail
121366 ** to resize if sqliteMalloc() fails.
121368 ** Return non-zero if a memory allocation error occurs.
121370 static int fts3Rehash(Fts3Hash *pH, int new_size){
121371 struct _fts3ht *new_ht; /* The new hash table */
121372 Fts3HashElem *elem, *next_elem; /* For looping over existing elements */
121373 int (*xHash)(const void*,int); /* The hash function */
121375 assert( (new_size & (new_size-1))==0 );
121376 new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
121377 if( new_ht==0 ) return 1;
121378 fts3HashFree(pH->ht);
121379 pH->ht = new_ht;
121380 pH->htsize = new_size;
121381 xHash = ftsHashFunction(pH->keyClass);
121382 for(elem=pH->first, pH->first=0; elem; elem = next_elem){
121383 int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
121384 next_elem = elem->next;
121385 fts3HashInsertElement(pH, &new_ht[h], elem);
121387 return 0;
121390 /* This function (for internal use only) locates an element in an
121391 ** hash table that matches the given key. The hash for this key has
121392 ** already been computed and is passed as the 4th parameter.
121394 static Fts3HashElem *fts3FindElementByHash(
121395 const Fts3Hash *pH, /* The pH to be searched */
121396 const void *pKey, /* The key we are searching for */
121397 int nKey,
121398 int h /* The hash for this key. */
121400 Fts3HashElem *elem; /* Used to loop thru the element list */
121401 int count; /* Number of elements left to test */
121402 int (*xCompare)(const void*,int,const void*,int); /* comparison function */
121404 if( pH->ht ){
121405 struct _fts3ht *pEntry = &pH->ht[h];
121406 elem = pEntry->chain;
121407 count = pEntry->count;
121408 xCompare = ftsCompareFunction(pH->keyClass);
121409 while( count-- && elem ){
121410 if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
121411 return elem;
121413 elem = elem->next;
121416 return 0;
121419 /* Remove a single entry from the hash table given a pointer to that
121420 ** element and a hash on the element's key.
121422 static void fts3RemoveElementByHash(
121423 Fts3Hash *pH, /* The pH containing "elem" */
121424 Fts3HashElem* elem, /* The element to be removed from the pH */
121425 int h /* Hash value for the element */
121427 struct _fts3ht *pEntry;
121428 if( elem->prev ){
121429 elem->prev->next = elem->next;
121430 }else{
121431 pH->first = elem->next;
121433 if( elem->next ){
121434 elem->next->prev = elem->prev;
121436 pEntry = &pH->ht[h];
121437 if( pEntry->chain==elem ){
121438 pEntry->chain = elem->next;
121440 pEntry->count--;
121441 if( pEntry->count<=0 ){
121442 pEntry->chain = 0;
121444 if( pH->copyKey && elem->pKey ){
121445 fts3HashFree(elem->pKey);
121447 fts3HashFree( elem );
121448 pH->count--;
121449 if( pH->count<=0 ){
121450 assert( pH->first==0 );
121451 assert( pH->count==0 );
121452 fts3HashClear(pH);
121456 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
121457 const Fts3Hash *pH,
121458 const void *pKey,
121459 int nKey
121461 int h; /* A hash on key */
121462 int (*xHash)(const void*,int); /* The hash function */
121464 if( pH==0 || pH->ht==0 ) return 0;
121465 xHash = ftsHashFunction(pH->keyClass);
121466 assert( xHash!=0 );
121467 h = (*xHash)(pKey,nKey);
121468 assert( (pH->htsize & (pH->htsize-1))==0 );
121469 return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
121473 ** Attempt to locate an element of the hash table pH with a key
121474 ** that matches pKey,nKey. Return the data for this element if it is
121475 ** found, or NULL if there is no match.
121477 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
121478 Fts3HashElem *pElem; /* The element that matches key (if any) */
121480 pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
121481 return pElem ? pElem->data : 0;
121484 /* Insert an element into the hash table pH. The key is pKey,nKey
121485 ** and the data is "data".
121487 ** If no element exists with a matching key, then a new
121488 ** element is created. A copy of the key is made if the copyKey
121489 ** flag is set. NULL is returned.
121491 ** If another element already exists with the same key, then the
121492 ** new data replaces the old data and the old data is returned.
121493 ** The key is not copied in this instance. If a malloc fails, then
121494 ** the new data is returned and the hash table is unchanged.
121496 ** If the "data" parameter to this function is NULL, then the
121497 ** element corresponding to "key" is removed from the hash table.
121499 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
121500 Fts3Hash *pH, /* The hash table to insert into */
121501 const void *pKey, /* The key */
121502 int nKey, /* Number of bytes in the key */
121503 void *data /* The data */
121505 int hraw; /* Raw hash value of the key */
121506 int h; /* the hash of the key modulo hash table size */
121507 Fts3HashElem *elem; /* Used to loop thru the element list */
121508 Fts3HashElem *new_elem; /* New element added to the pH */
121509 int (*xHash)(const void*,int); /* The hash function */
121511 assert( pH!=0 );
121512 xHash = ftsHashFunction(pH->keyClass);
121513 assert( xHash!=0 );
121514 hraw = (*xHash)(pKey, nKey);
121515 assert( (pH->htsize & (pH->htsize-1))==0 );
121516 h = hraw & (pH->htsize-1);
121517 elem = fts3FindElementByHash(pH,pKey,nKey,h);
121518 if( elem ){
121519 void *old_data = elem->data;
121520 if( data==0 ){
121521 fts3RemoveElementByHash(pH,elem,h);
121522 }else{
121523 elem->data = data;
121525 return old_data;
121527 if( data==0 ) return 0;
121528 if( (pH->htsize==0 && fts3Rehash(pH,8))
121529 || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
121531 pH->count = 0;
121532 return data;
121534 assert( pH->htsize>0 );
121535 new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
121536 if( new_elem==0 ) return data;
121537 if( pH->copyKey && pKey!=0 ){
121538 new_elem->pKey = fts3HashMalloc( nKey );
121539 if( new_elem->pKey==0 ){
121540 fts3HashFree(new_elem);
121541 return data;
121543 memcpy((void*)new_elem->pKey, pKey, nKey);
121544 }else{
121545 new_elem->pKey = (void*)pKey;
121547 new_elem->nKey = nKey;
121548 pH->count++;
121549 assert( pH->htsize>0 );
121550 assert( (pH->htsize & (pH->htsize-1))==0 );
121551 h = hraw & (pH->htsize-1);
121552 fts3HashInsertElement(pH, &pH->ht[h], new_elem);
121553 new_elem->data = data;
121554 return 0;
121557 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
121559 /************** End of fts3_hash.c *******************************************/
121560 /************** Begin file fts3_porter.c *************************************/
121562 ** 2006 September 30
121564 ** The author disclaims copyright to this source code. In place of
121565 ** a legal notice, here is a blessing:
121567 ** May you do good and not evil.
121568 ** May you find forgiveness for yourself and forgive others.
121569 ** May you share freely, never taking more than you give.
121571 *************************************************************************
121572 ** Implementation of the full-text-search tokenizer that implements
121573 ** a Porter stemmer.
121577 ** The code in this file is only compiled if:
121579 ** * The FTS3 module is being built as an extension
121580 ** (in which case SQLITE_CORE is not defined), or
121582 ** * The FTS3 module is being built into the core of
121583 ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
121585 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
121587 /* #include <assert.h> */
121588 /* #include <stdlib.h> */
121589 /* #include <stdio.h> */
121590 /* #include <string.h> */
121594 ** Class derived from sqlite3_tokenizer
121596 typedef struct porter_tokenizer {
121597 sqlite3_tokenizer base; /* Base class */
121598 } porter_tokenizer;
121601 ** Class derived from sqlit3_tokenizer_cursor
121603 typedef struct porter_tokenizer_cursor {
121604 sqlite3_tokenizer_cursor base;
121605 const char *zInput; /* input we are tokenizing */
121606 int nInput; /* size of the input */
121607 int iOffset; /* current position in zInput */
121608 int iToken; /* index of next token to be returned */
121609 char *zToken; /* storage for current token */
121610 int nAllocated; /* space allocated to zToken buffer */
121611 } porter_tokenizer_cursor;
121615 ** Create a new tokenizer instance.
121617 static int porterCreate(
121618 int argc, const char * const *argv,
121619 sqlite3_tokenizer **ppTokenizer
121621 porter_tokenizer *t;
121623 UNUSED_PARAMETER(argc);
121624 UNUSED_PARAMETER(argv);
121626 t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
121627 if( t==NULL ) return SQLITE_NOMEM;
121628 memset(t, 0, sizeof(*t));
121629 *ppTokenizer = &t->base;
121630 return SQLITE_OK;
121634 ** Destroy a tokenizer
121636 static int porterDestroy(sqlite3_tokenizer *pTokenizer){
121637 sqlite3_free(pTokenizer);
121638 return SQLITE_OK;
121642 ** Prepare to begin tokenizing a particular string. The input
121643 ** string to be tokenized is zInput[0..nInput-1]. A cursor
121644 ** used to incrementally tokenize this string is returned in
121645 ** *ppCursor.
121647 static int porterOpen(
121648 sqlite3_tokenizer *pTokenizer, /* The tokenizer */
121649 const char *zInput, int nInput, /* String to be tokenized */
121650 sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
121652 porter_tokenizer_cursor *c;
121654 UNUSED_PARAMETER(pTokenizer);
121656 c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
121657 if( c==NULL ) return SQLITE_NOMEM;
121659 c->zInput = zInput;
121660 if( zInput==0 ){
121661 c->nInput = 0;
121662 }else if( nInput<0 ){
121663 c->nInput = (int)strlen(zInput);
121664 }else{
121665 c->nInput = nInput;
121667 c->iOffset = 0; /* start tokenizing at the beginning */
121668 c->iToken = 0;
121669 c->zToken = NULL; /* no space allocated, yet. */
121670 c->nAllocated = 0;
121672 *ppCursor = &c->base;
121673 return SQLITE_OK;
121677 ** Close a tokenization cursor previously opened by a call to
121678 ** porterOpen() above.
121680 static int porterClose(sqlite3_tokenizer_cursor *pCursor){
121681 porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
121682 sqlite3_free(c->zToken);
121683 sqlite3_free(c);
121684 return SQLITE_OK;
121687 ** Vowel or consonant
121689 static const char cType[] = {
121690 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
121691 1, 1, 1, 2, 1
121695 ** isConsonant() and isVowel() determine if their first character in
121696 ** the string they point to is a consonant or a vowel, according
121697 ** to Porter ruls.
121699 ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
121700 ** 'Y' is a consonant unless it follows another consonant,
121701 ** in which case it is a vowel.
121703 ** In these routine, the letters are in reverse order. So the 'y' rule
121704 ** is that 'y' is a consonant unless it is followed by another
121705 ** consonent.
121707 static int isVowel(const char*);
121708 static int isConsonant(const char *z){
121709 int j;
121710 char x = *z;
121711 if( x==0 ) return 0;
121712 assert( x>='a' && x<='z' );
121713 j = cType[x-'a'];
121714 if( j<2 ) return j;
121715 return z[1]==0 || isVowel(z + 1);
121717 static int isVowel(const char *z){
121718 int j;
121719 char x = *z;
121720 if( x==0 ) return 0;
121721 assert( x>='a' && x<='z' );
121722 j = cType[x-'a'];
121723 if( j<2 ) return 1-j;
121724 return isConsonant(z + 1);
121728 ** Let any sequence of one or more vowels be represented by V and let
121729 ** C be sequence of one or more consonants. Then every word can be
121730 ** represented as:
121732 ** [C] (VC){m} [V]
121734 ** In prose: A word is an optional consonant followed by zero or
121735 ** vowel-consonant pairs followed by an optional vowel. "m" is the
121736 ** number of vowel consonant pairs. This routine computes the value
121737 ** of m for the first i bytes of a word.
121739 ** Return true if the m-value for z is 1 or more. In other words,
121740 ** return true if z contains at least one vowel that is followed
121741 ** by a consonant.
121743 ** In this routine z[] is in reverse order. So we are really looking
121744 ** for an instance of of a consonant followed by a vowel.
121746 static int m_gt_0(const char *z){
121747 while( isVowel(z) ){ z++; }
121748 if( *z==0 ) return 0;
121749 while( isConsonant(z) ){ z++; }
121750 return *z!=0;
121753 /* Like mgt0 above except we are looking for a value of m which is
121754 ** exactly 1
121756 static int m_eq_1(const char *z){
121757 while( isVowel(z) ){ z++; }
121758 if( *z==0 ) return 0;
121759 while( isConsonant(z) ){ z++; }
121760 if( *z==0 ) return 0;
121761 while( isVowel(z) ){ z++; }
121762 if( *z==0 ) return 1;
121763 while( isConsonant(z) ){ z++; }
121764 return *z==0;
121767 /* Like mgt0 above except we are looking for a value of m>1 instead
121768 ** or m>0
121770 static int m_gt_1(const char *z){
121771 while( isVowel(z) ){ z++; }
121772 if( *z==0 ) return 0;
121773 while( isConsonant(z) ){ z++; }
121774 if( *z==0 ) return 0;
121775 while( isVowel(z) ){ z++; }
121776 if( *z==0 ) return 0;
121777 while( isConsonant(z) ){ z++; }
121778 return *z!=0;
121782 ** Return TRUE if there is a vowel anywhere within z[0..n-1]
121784 static int hasVowel(const char *z){
121785 while( isConsonant(z) ){ z++; }
121786 return *z!=0;
121790 ** Return TRUE if the word ends in a double consonant.
121792 ** The text is reversed here. So we are really looking at
121793 ** the first two characters of z[].
121795 static int doubleConsonant(const char *z){
121796 return isConsonant(z) && z[0]==z[1];
121800 ** Return TRUE if the word ends with three letters which
121801 ** are consonant-vowel-consonent and where the final consonant
121802 ** is not 'w', 'x', or 'y'.
121804 ** The word is reversed here. So we are really checking the
121805 ** first three letters and the first one cannot be in [wxy].
121807 static int star_oh(const char *z){
121808 return
121809 isConsonant(z) &&
121810 z[0]!='w' && z[0]!='x' && z[0]!='y' &&
121811 isVowel(z+1) &&
121812 isConsonant(z+2);
121816 ** If the word ends with zFrom and xCond() is true for the stem
121817 ** of the word that preceeds the zFrom ending, then change the
121818 ** ending to zTo.
121820 ** The input word *pz and zFrom are both in reverse order. zTo
121821 ** is in normal order.
121823 ** Return TRUE if zFrom matches. Return FALSE if zFrom does not
121824 ** match. Not that TRUE is returned even if xCond() fails and
121825 ** no substitution occurs.
121827 static int stem(
121828 char **pz, /* The word being stemmed (Reversed) */
121829 const char *zFrom, /* If the ending matches this... (Reversed) */
121830 const char *zTo, /* ... change the ending to this (not reversed) */
121831 int (*xCond)(const char*) /* Condition that must be true */
121833 char *z = *pz;
121834 while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
121835 if( *zFrom!=0 ) return 0;
121836 if( xCond && !xCond(z) ) return 1;
121837 while( *zTo ){
121838 *(--z) = *(zTo++);
121840 *pz = z;
121841 return 1;
121845 ** This is the fallback stemmer used when the porter stemmer is
121846 ** inappropriate. The input word is copied into the output with
121847 ** US-ASCII case folding. If the input word is too long (more
121848 ** than 20 bytes if it contains no digits or more than 6 bytes if
121849 ** it contains digits) then word is truncated to 20 or 6 bytes
121850 ** by taking 10 or 3 bytes from the beginning and end.
121852 static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
121853 int i, mx, j;
121854 int hasDigit = 0;
121855 for(i=0; i<nIn; i++){
121856 char c = zIn[i];
121857 if( c>='A' && c<='Z' ){
121858 zOut[i] = c - 'A' + 'a';
121859 }else{
121860 if( c>='0' && c<='9' ) hasDigit = 1;
121861 zOut[i] = c;
121864 mx = hasDigit ? 3 : 10;
121865 if( nIn>mx*2 ){
121866 for(j=mx, i=nIn-mx; i<nIn; i++, j++){
121867 zOut[j] = zOut[i];
121869 i = j;
121871 zOut[i] = 0;
121872 *pnOut = i;
121877 ** Stem the input word zIn[0..nIn-1]. Store the output in zOut.
121878 ** zOut is at least big enough to hold nIn bytes. Write the actual
121879 ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
121881 ** Any upper-case characters in the US-ASCII character set ([A-Z])
121882 ** are converted to lower case. Upper-case UTF characters are
121883 ** unchanged.
121885 ** Words that are longer than about 20 bytes are stemmed by retaining
121886 ** a few bytes from the beginning and the end of the word. If the
121887 ** word contains digits, 3 bytes are taken from the beginning and
121888 ** 3 bytes from the end. For long words without digits, 10 bytes
121889 ** are taken from each end. US-ASCII case folding still applies.
121891 ** If the input word contains not digits but does characters not
121892 ** in [a-zA-Z] then no stemming is attempted and this routine just
121893 ** copies the input into the input into the output with US-ASCII
121894 ** case folding.
121896 ** Stemming never increases the length of the word. So there is
121897 ** no chance of overflowing the zOut buffer.
121899 static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
121900 int i, j;
121901 char zReverse[28];
121902 char *z, *z2;
121903 if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
121904 /* The word is too big or too small for the porter stemmer.
121905 ** Fallback to the copy stemmer */
121906 copy_stemmer(zIn, nIn, zOut, pnOut);
121907 return;
121909 for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
121910 char c = zIn[i];
121911 if( c>='A' && c<='Z' ){
121912 zReverse[j] = c + 'a' - 'A';
121913 }else if( c>='a' && c<='z' ){
121914 zReverse[j] = c;
121915 }else{
121916 /* The use of a character not in [a-zA-Z] means that we fallback
121917 ** to the copy stemmer */
121918 copy_stemmer(zIn, nIn, zOut, pnOut);
121919 return;
121922 memset(&zReverse[sizeof(zReverse)-5], 0, 5);
121923 z = &zReverse[j+1];
121926 /* Step 1a */
121927 if( z[0]=='s' ){
121929 !stem(&z, "sess", "ss", 0) &&
121930 !stem(&z, "sei", "i", 0) &&
121931 !stem(&z, "ss", "ss", 0)
121937 /* Step 1b */
121938 z2 = z;
121939 if( stem(&z, "dee", "ee", m_gt_0) ){
121940 /* Do nothing. The work was all in the test */
121941 }else if(
121942 (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
121943 && z!=z2
121945 if( stem(&z, "ta", "ate", 0) ||
121946 stem(&z, "lb", "ble", 0) ||
121947 stem(&z, "zi", "ize", 0) ){
121948 /* Do nothing. The work was all in the test */
121949 }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
121951 }else if( m_eq_1(z) && star_oh(z) ){
121952 *(--z) = 'e';
121956 /* Step 1c */
121957 if( z[0]=='y' && hasVowel(z+1) ){
121958 z[0] = 'i';
121961 /* Step 2 */
121962 switch( z[1] ){
121963 case 'a':
121964 stem(&z, "lanoita", "ate", m_gt_0) ||
121965 stem(&z, "lanoit", "tion", m_gt_0);
121966 break;
121967 case 'c':
121968 stem(&z, "icne", "ence", m_gt_0) ||
121969 stem(&z, "icna", "ance", m_gt_0);
121970 break;
121971 case 'e':
121972 stem(&z, "rezi", "ize", m_gt_0);
121973 break;
121974 case 'g':
121975 stem(&z, "igol", "log", m_gt_0);
121976 break;
121977 case 'l':
121978 stem(&z, "ilb", "ble", m_gt_0) ||
121979 stem(&z, "illa", "al", m_gt_0) ||
121980 stem(&z, "iltne", "ent", m_gt_0) ||
121981 stem(&z, "ile", "e", m_gt_0) ||
121982 stem(&z, "ilsuo", "ous", m_gt_0);
121983 break;
121984 case 'o':
121985 stem(&z, "noitazi", "ize", m_gt_0) ||
121986 stem(&z, "noita", "ate", m_gt_0) ||
121987 stem(&z, "rota", "ate", m_gt_0);
121988 break;
121989 case 's':
121990 stem(&z, "msila", "al", m_gt_0) ||
121991 stem(&z, "ssenevi", "ive", m_gt_0) ||
121992 stem(&z, "ssenluf", "ful", m_gt_0) ||
121993 stem(&z, "ssensuo", "ous", m_gt_0);
121994 break;
121995 case 't':
121996 stem(&z, "itila", "al", m_gt_0) ||
121997 stem(&z, "itivi", "ive", m_gt_0) ||
121998 stem(&z, "itilib", "ble", m_gt_0);
121999 break;
122002 /* Step 3 */
122003 switch( z[0] ){
122004 case 'e':
122005 stem(&z, "etaci", "ic", m_gt_0) ||
122006 stem(&z, "evita", "", m_gt_0) ||
122007 stem(&z, "ezila", "al", m_gt_0);
122008 break;
122009 case 'i':
122010 stem(&z, "itici", "ic", m_gt_0);
122011 break;
122012 case 'l':
122013 stem(&z, "laci", "ic", m_gt_0) ||
122014 stem(&z, "luf", "", m_gt_0);
122015 break;
122016 case 's':
122017 stem(&z, "ssen", "", m_gt_0);
122018 break;
122021 /* Step 4 */
122022 switch( z[1] ){
122023 case 'a':
122024 if( z[0]=='l' && m_gt_1(z+2) ){
122025 z += 2;
122027 break;
122028 case 'c':
122029 if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e') && m_gt_1(z+4) ){
122030 z += 4;
122032 break;
122033 case 'e':
122034 if( z[0]=='r' && m_gt_1(z+2) ){
122035 z += 2;
122037 break;
122038 case 'i':
122039 if( z[0]=='c' && m_gt_1(z+2) ){
122040 z += 2;
122042 break;
122043 case 'l':
122044 if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
122045 z += 4;
122047 break;
122048 case 'n':
122049 if( z[0]=='t' ){
122050 if( z[2]=='a' ){
122051 if( m_gt_1(z+3) ){
122052 z += 3;
122054 }else if( z[2]=='e' ){
122055 stem(&z, "tneme", "", m_gt_1) ||
122056 stem(&z, "tnem", "", m_gt_1) ||
122057 stem(&z, "tne", "", m_gt_1);
122060 break;
122061 case 'o':
122062 if( z[0]=='u' ){
122063 if( m_gt_1(z+2) ){
122064 z += 2;
122066 }else if( z[3]=='s' || z[3]=='t' ){
122067 stem(&z, "noi", "", m_gt_1);
122069 break;
122070 case 's':
122071 if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
122072 z += 3;
122074 break;
122075 case 't':
122076 stem(&z, "eta", "", m_gt_1) ||
122077 stem(&z, "iti", "", m_gt_1);
122078 break;
122079 case 'u':
122080 if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
122081 z += 3;
122083 break;
122084 case 'v':
122085 case 'z':
122086 if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
122087 z += 3;
122089 break;
122092 /* Step 5a */
122093 if( z[0]=='e' ){
122094 if( m_gt_1(z+1) ){
122096 }else if( m_eq_1(z+1) && !star_oh(z+1) ){
122101 /* Step 5b */
122102 if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
122106 /* z[] is now the stemmed word in reverse order. Flip it back
122107 ** around into forward order and return.
122109 *pnOut = i = (int)strlen(z);
122110 zOut[i] = 0;
122111 while( *z ){
122112 zOut[--i] = *(z++);
122117 ** Characters that can be part of a token. We assume any character
122118 ** whose value is greater than 0x80 (any UTF character) can be
122119 ** part of a token. In other words, delimiters all must have
122120 ** values of 0x7f or lower.
122122 static const char porterIdChar[] = {
122123 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
122124 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
122125 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
122126 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
122127 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
122128 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
122130 #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
122133 ** Extract the next token from a tokenization cursor. The cursor must
122134 ** have been opened by a prior call to porterOpen().
122136 static int porterNext(
122137 sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by porterOpen */
122138 const char **pzToken, /* OUT: *pzToken is the token text */
122139 int *pnBytes, /* OUT: Number of bytes in token */
122140 int *piStartOffset, /* OUT: Starting offset of token */
122141 int *piEndOffset, /* OUT: Ending offset of token */
122142 int *piPosition /* OUT: Position integer of token */
122144 porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
122145 const char *z = c->zInput;
122147 while( c->iOffset<c->nInput ){
122148 int iStartOffset, ch;
122150 /* Scan past delimiter characters */
122151 while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
122152 c->iOffset++;
122155 /* Count non-delimiter characters. */
122156 iStartOffset = c->iOffset;
122157 while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
122158 c->iOffset++;
122161 if( c->iOffset>iStartOffset ){
122162 int n = c->iOffset-iStartOffset;
122163 if( n>c->nAllocated ){
122164 char *pNew;
122165 c->nAllocated = n+20;
122166 pNew = sqlite3_realloc(c->zToken, c->nAllocated);
122167 if( !pNew ) return SQLITE_NOMEM;
122168 c->zToken = pNew;
122170 porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
122171 *pzToken = c->zToken;
122172 *piStartOffset = iStartOffset;
122173 *piEndOffset = c->iOffset;
122174 *piPosition = c->iToken++;
122175 return SQLITE_OK;
122178 return SQLITE_DONE;
122182 ** The set of routines that implement the porter-stemmer tokenizer
122184 static const sqlite3_tokenizer_module porterTokenizerModule = {
122186 porterCreate,
122187 porterDestroy,
122188 porterOpen,
122189 porterClose,
122190 porterNext,
122194 ** Allocate a new porter tokenizer. Return a pointer to the new
122195 ** tokenizer in *ppModule
122197 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
122198 sqlite3_tokenizer_module const**ppModule
122200 *ppModule = &porterTokenizerModule;
122203 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
122205 /************** End of fts3_porter.c *****************************************/
122206 /************** Begin file fts3_tokenizer.c **********************************/
122208 ** 2007 June 22
122210 ** The author disclaims copyright to this source code. In place of
122211 ** a legal notice, here is a blessing:
122213 ** May you do good and not evil.
122214 ** May you find forgiveness for yourself and forgive others.
122215 ** May you share freely, never taking more than you give.
122217 ******************************************************************************
122219 ** This is part of an SQLite module implementing full-text search.
122220 ** This particular file implements the generic tokenizer interface.
122224 ** The code in this file is only compiled if:
122226 ** * The FTS3 module is being built as an extension
122227 ** (in which case SQLITE_CORE is not defined), or
122229 ** * The FTS3 module is being built into the core of
122230 ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
122232 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
122234 /* #include <assert.h> */
122235 /* #include <string.h> */
122238 ** Implementation of the SQL scalar function for accessing the underlying
122239 ** hash table. This function may be called as follows:
122241 ** SELECT <function-name>(<key-name>);
122242 ** SELECT <function-name>(<key-name>, <pointer>);
122244 ** where <function-name> is the name passed as the second argument
122245 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
122247 ** If the <pointer> argument is specified, it must be a blob value
122248 ** containing a pointer to be stored as the hash data corresponding
122249 ** to the string <key-name>. If <pointer> is not specified, then
122250 ** the string <key-name> must already exist in the has table. Otherwise,
122251 ** an error is returned.
122253 ** Whether or not the <pointer> argument is specified, the value returned
122254 ** is a blob containing the pointer stored as the hash data corresponding
122255 ** to string <key-name> (after the hash-table is updated, if applicable).
122257 static void scalarFunc(
122258 sqlite3_context *context,
122259 int argc,
122260 sqlite3_value **argv
122262 Fts3Hash *pHash;
122263 void *pPtr = 0;
122264 const unsigned char *zName;
122265 int nName;
122267 assert( argc==1 || argc==2 );
122269 pHash = (Fts3Hash *)sqlite3_user_data(context);
122271 zName = sqlite3_value_text(argv[0]);
122272 nName = sqlite3_value_bytes(argv[0])+1;
122274 if( argc==2 ){
122275 void *pOld;
122276 int n = sqlite3_value_bytes(argv[1]);
122277 if( n!=sizeof(pPtr) ){
122278 sqlite3_result_error(context, "argument type mismatch", -1);
122279 return;
122281 pPtr = *(void **)sqlite3_value_blob(argv[1]);
122282 pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
122283 if( pOld==pPtr ){
122284 sqlite3_result_error(context, "out of memory", -1);
122285 return;
122287 }else{
122288 pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
122289 if( !pPtr ){
122290 char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
122291 sqlite3_result_error(context, zErr, -1);
122292 sqlite3_free(zErr);
122293 return;
122297 sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
122300 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
122301 static const char isFtsIdChar[] = {
122302 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
122303 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
122304 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
122305 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
122306 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
122307 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
122308 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
122309 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
122311 return (c&0x80 || isFtsIdChar[(int)(c)]);
122314 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
122315 const char *z1;
122316 const char *z2 = 0;
122318 /* Find the start of the next token. */
122319 z1 = zStr;
122320 while( z2==0 ){
122321 char c = *z1;
122322 switch( c ){
122323 case '\0': return 0; /* No more tokens here */
122324 case '\'':
122325 case '"':
122326 case '`': {
122327 z2 = z1;
122328 while( *++z2 && (*z2!=c || *++z2==c) );
122329 break;
122331 case '[':
122332 z2 = &z1[1];
122333 while( *z2 && z2[0]!=']' ) z2++;
122334 if( *z2 ) z2++;
122335 break;
122337 default:
122338 if( sqlite3Fts3IsIdChar(*z1) ){
122339 z2 = &z1[1];
122340 while( sqlite3Fts3IsIdChar(*z2) ) z2++;
122341 }else{
122342 z1++;
122347 *pn = (int)(z2-z1);
122348 return z1;
122351 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
122352 Fts3Hash *pHash, /* Tokenizer hash table */
122353 const char *zArg, /* Tokenizer name */
122354 sqlite3_tokenizer **ppTok, /* OUT: Tokenizer (if applicable) */
122355 char **pzErr /* OUT: Set to malloced error message */
122357 int rc;
122358 char *z = (char *)zArg;
122359 int n = 0;
122360 char *zCopy;
122361 char *zEnd; /* Pointer to nul-term of zCopy */
122362 sqlite3_tokenizer_module *m;
122364 zCopy = sqlite3_mprintf("%s", zArg);
122365 if( !zCopy ) return SQLITE_NOMEM;
122366 zEnd = &zCopy[strlen(zCopy)];
122368 z = (char *)sqlite3Fts3NextToken(zCopy, &n);
122369 z[n] = '\0';
122370 sqlite3Fts3Dequote(z);
122372 m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
122373 if( !m ){
122374 *pzErr = sqlite3_mprintf("unknown tokenizer: %s", z);
122375 rc = SQLITE_ERROR;
122376 }else{
122377 char const **aArg = 0;
122378 int iArg = 0;
122379 z = &z[n+1];
122380 while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
122381 int nNew = sizeof(char *)*(iArg+1);
122382 char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
122383 if( !aNew ){
122384 sqlite3_free(zCopy);
122385 sqlite3_free((void *)aArg);
122386 return SQLITE_NOMEM;
122388 aArg = aNew;
122389 aArg[iArg++] = z;
122390 z[n] = '\0';
122391 sqlite3Fts3Dequote(z);
122392 z = &z[n+1];
122394 rc = m->xCreate(iArg, aArg, ppTok);
122395 assert( rc!=SQLITE_OK || *ppTok );
122396 if( rc!=SQLITE_OK ){
122397 *pzErr = sqlite3_mprintf("unknown tokenizer");
122398 }else{
122399 (*ppTok)->pModule = m;
122401 sqlite3_free((void *)aArg);
122404 sqlite3_free(zCopy);
122405 return rc;
122409 #ifdef SQLITE_TEST
122411 /* #include <tcl.h> */
122412 /* #include <string.h> */
122415 ** Implementation of a special SQL scalar function for testing tokenizers
122416 ** designed to be used in concert with the Tcl testing framework. This
122417 ** function must be called with two arguments:
122419 ** SELECT <function-name>(<key-name>, <input-string>);
122420 ** SELECT <function-name>(<key-name>, <pointer>);
122422 ** where <function-name> is the name passed as the second argument
122423 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
122424 ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
122426 ** The return value is a string that may be interpreted as a Tcl
122427 ** list. For each token in the <input-string>, three elements are
122428 ** added to the returned list. The first is the token position, the
122429 ** second is the token text (folded, stemmed, etc.) and the third is the
122430 ** substring of <input-string> associated with the token. For example,
122431 ** using the built-in "simple" tokenizer:
122433 ** SELECT fts_tokenizer_test('simple', 'I don't see how');
122435 ** will return the string:
122437 ** "{0 i I 1 dont don't 2 see see 3 how how}"
122440 static void testFunc(
122441 sqlite3_context *context,
122442 int argc,
122443 sqlite3_value **argv
122445 Fts3Hash *pHash;
122446 sqlite3_tokenizer_module *p;
122447 sqlite3_tokenizer *pTokenizer = 0;
122448 sqlite3_tokenizer_cursor *pCsr = 0;
122450 const char *zErr = 0;
122452 const char *zName;
122453 int nName;
122454 const char *zInput;
122455 int nInput;
122457 const char *zArg = 0;
122459 const char *zToken;
122460 int nToken;
122461 int iStart;
122462 int iEnd;
122463 int iPos;
122465 Tcl_Obj *pRet;
122467 assert( argc==2 || argc==3 );
122469 nName = sqlite3_value_bytes(argv[0]);
122470 zName = (const char *)sqlite3_value_text(argv[0]);
122471 nInput = sqlite3_value_bytes(argv[argc-1]);
122472 zInput = (const char *)sqlite3_value_text(argv[argc-1]);
122474 if( argc==3 ){
122475 zArg = (const char *)sqlite3_value_text(argv[1]);
122478 pHash = (Fts3Hash *)sqlite3_user_data(context);
122479 p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
122481 if( !p ){
122482 char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
122483 sqlite3_result_error(context, zErr, -1);
122484 sqlite3_free(zErr);
122485 return;
122488 pRet = Tcl_NewObj();
122489 Tcl_IncrRefCount(pRet);
122491 if( SQLITE_OK!=p->xCreate(zArg ? 1 : 0, &zArg, &pTokenizer) ){
122492 zErr = "error in xCreate()";
122493 goto finish;
122495 pTokenizer->pModule = p;
122496 if( SQLITE_OK!=p->xOpen(pTokenizer, zInput, nInput, &pCsr) ){
122497 zErr = "error in xOpen()";
122498 goto finish;
122500 pCsr->pTokenizer = pTokenizer;
122502 while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
122503 Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
122504 Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
122505 zToken = &zInput[iStart];
122506 nToken = iEnd-iStart;
122507 Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
122510 if( SQLITE_OK!=p->xClose(pCsr) ){
122511 zErr = "error in xClose()";
122512 goto finish;
122514 if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
122515 zErr = "error in xDestroy()";
122516 goto finish;
122519 finish:
122520 if( zErr ){
122521 sqlite3_result_error(context, zErr, -1);
122522 }else{
122523 sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
122525 Tcl_DecrRefCount(pRet);
122528 static
122529 int registerTokenizer(
122530 sqlite3 *db,
122531 char *zName,
122532 const sqlite3_tokenizer_module *p
122534 int rc;
122535 sqlite3_stmt *pStmt;
122536 const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
122538 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
122539 if( rc!=SQLITE_OK ){
122540 return rc;
122543 sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
122544 sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
122545 sqlite3_step(pStmt);
122547 return sqlite3_finalize(pStmt);
122550 static
122551 int queryTokenizer(
122552 sqlite3 *db,
122553 char *zName,
122554 const sqlite3_tokenizer_module **pp
122556 int rc;
122557 sqlite3_stmt *pStmt;
122558 const char zSql[] = "SELECT fts3_tokenizer(?)";
122560 *pp = 0;
122561 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
122562 if( rc!=SQLITE_OK ){
122563 return rc;
122566 sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
122567 if( SQLITE_ROW==sqlite3_step(pStmt) ){
122568 if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
122569 memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
122573 return sqlite3_finalize(pStmt);
122576 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
122579 ** Implementation of the scalar function fts3_tokenizer_internal_test().
122580 ** This function is used for testing only, it is not included in the
122581 ** build unless SQLITE_TEST is defined.
122583 ** The purpose of this is to test that the fts3_tokenizer() function
122584 ** can be used as designed by the C-code in the queryTokenizer and
122585 ** registerTokenizer() functions above. These two functions are repeated
122586 ** in the README.tokenizer file as an example, so it is important to
122587 ** test them.
122589 ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
122590 ** function with no arguments. An assert() will fail if a problem is
122591 ** detected. i.e.:
122593 ** SELECT fts3_tokenizer_internal_test();
122596 static void intTestFunc(
122597 sqlite3_context *context,
122598 int argc,
122599 sqlite3_value **argv
122601 int rc;
122602 const sqlite3_tokenizer_module *p1;
122603 const sqlite3_tokenizer_module *p2;
122604 sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
122606 UNUSED_PARAMETER(argc);
122607 UNUSED_PARAMETER(argv);
122609 /* Test the query function */
122610 sqlite3Fts3SimpleTokenizerModule(&p1);
122611 rc = queryTokenizer(db, "simple", &p2);
122612 assert( rc==SQLITE_OK );
122613 assert( p1==p2 );
122614 rc = queryTokenizer(db, "nosuchtokenizer", &p2);
122615 assert( rc==SQLITE_ERROR );
122616 assert( p2==0 );
122617 assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
122619 /* Test the storage function */
122620 rc = registerTokenizer(db, "nosuchtokenizer", p1);
122621 assert( rc==SQLITE_OK );
122622 rc = queryTokenizer(db, "nosuchtokenizer", &p2);
122623 assert( rc==SQLITE_OK );
122624 assert( p2==p1 );
122626 sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
122629 #endif
122632 ** Set up SQL objects in database db used to access the contents of
122633 ** the hash table pointed to by argument pHash. The hash table must
122634 ** been initialised to use string keys, and to take a private copy
122635 ** of the key when a value is inserted. i.e. by a call similar to:
122637 ** sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
122639 ** This function adds a scalar function (see header comment above
122640 ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
122641 ** defined at compilation time, a temporary virtual table (see header
122642 ** comment above struct HashTableVtab) to the database schema. Both
122643 ** provide read/write access to the contents of *pHash.
122645 ** The third argument to this function, zName, is used as the name
122646 ** of both the scalar and, if created, the virtual table.
122648 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
122649 sqlite3 *db,
122650 Fts3Hash *pHash,
122651 const char *zName
122653 int rc = SQLITE_OK;
122654 void *p = (void *)pHash;
122655 const int any = SQLITE_ANY;
122657 #ifdef SQLITE_TEST
122658 char *zTest = 0;
122659 char *zTest2 = 0;
122660 void *pdb = (void *)db;
122661 zTest = sqlite3_mprintf("%s_test", zName);
122662 zTest2 = sqlite3_mprintf("%s_internal_test", zName);
122663 if( !zTest || !zTest2 ){
122664 rc = SQLITE_NOMEM;
122666 #endif
122668 if( SQLITE_OK==rc ){
122669 rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0);
122671 if( SQLITE_OK==rc ){
122672 rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0);
122674 #ifdef SQLITE_TEST
122675 if( SQLITE_OK==rc ){
122676 rc = sqlite3_create_function(db, zTest, 2, any, p, testFunc, 0, 0);
122678 if( SQLITE_OK==rc ){
122679 rc = sqlite3_create_function(db, zTest, 3, any, p, testFunc, 0, 0);
122681 if( SQLITE_OK==rc ){
122682 rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
122684 #endif
122686 #ifdef SQLITE_TEST
122687 sqlite3_free(zTest);
122688 sqlite3_free(zTest2);
122689 #endif
122691 return rc;
122694 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
122696 /************** End of fts3_tokenizer.c **************************************/
122697 /************** Begin file fts3_tokenizer1.c *********************************/
122699 ** 2006 Oct 10
122701 ** The author disclaims copyright to this source code. In place of
122702 ** a legal notice, here is a blessing:
122704 ** May you do good and not evil.
122705 ** May you find forgiveness for yourself and forgive others.
122706 ** May you share freely, never taking more than you give.
122708 ******************************************************************************
122710 ** Implementation of the "simple" full-text-search tokenizer.
122714 ** The code in this file is only compiled if:
122716 ** * The FTS3 module is being built as an extension
122717 ** (in which case SQLITE_CORE is not defined), or
122719 ** * The FTS3 module is being built into the core of
122720 ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
122722 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
122724 /* #include <assert.h> */
122725 /* #include <stdlib.h> */
122726 /* #include <stdio.h> */
122727 /* #include <string.h> */
122730 typedef struct simple_tokenizer {
122731 sqlite3_tokenizer base;
122732 char delim[128]; /* flag ASCII delimiters */
122733 } simple_tokenizer;
122735 typedef struct simple_tokenizer_cursor {
122736 sqlite3_tokenizer_cursor base;
122737 const char *pInput; /* input we are tokenizing */
122738 int nBytes; /* size of the input */
122739 int iOffset; /* current position in pInput */
122740 int iToken; /* index of next token to be returned */
122741 char *pToken; /* storage for current token */
122742 int nTokenAllocated; /* space allocated to zToken buffer */
122743 } simple_tokenizer_cursor;
122746 static int simpleDelim(simple_tokenizer *t, unsigned char c){
122747 return c<0x80 && t->delim[c];
122749 static int fts3_isalnum(int x){
122750 return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
122754 ** Create a new tokenizer instance.
122756 static int simpleCreate(
122757 int argc, const char * const *argv,
122758 sqlite3_tokenizer **ppTokenizer
122760 simple_tokenizer *t;
122762 t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
122763 if( t==NULL ) return SQLITE_NOMEM;
122764 memset(t, 0, sizeof(*t));
122766 /* TODO(shess) Delimiters need to remain the same from run to run,
122767 ** else we need to reindex. One solution would be a meta-table to
122768 ** track such information in the database, then we'd only want this
122769 ** information on the initial create.
122771 if( argc>1 ){
122772 int i, n = (int)strlen(argv[1]);
122773 for(i=0; i<n; i++){
122774 unsigned char ch = argv[1][i];
122775 /* We explicitly don't support UTF-8 delimiters for now. */
122776 if( ch>=0x80 ){
122777 sqlite3_free(t);
122778 return SQLITE_ERROR;
122780 t->delim[ch] = 1;
122782 } else {
122783 /* Mark non-alphanumeric ASCII characters as delimiters */
122784 int i;
122785 for(i=1; i<0x80; i++){
122786 t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
122790 *ppTokenizer = &t->base;
122791 return SQLITE_OK;
122795 ** Destroy a tokenizer
122797 static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
122798 sqlite3_free(pTokenizer);
122799 return SQLITE_OK;
122803 ** Prepare to begin tokenizing a particular string. The input
122804 ** string to be tokenized is pInput[0..nBytes-1]. A cursor
122805 ** used to incrementally tokenize this string is returned in
122806 ** *ppCursor.
122808 static int simpleOpen(
122809 sqlite3_tokenizer *pTokenizer, /* The tokenizer */
122810 const char *pInput, int nBytes, /* String to be tokenized */
122811 sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
122813 simple_tokenizer_cursor *c;
122815 UNUSED_PARAMETER(pTokenizer);
122817 c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
122818 if( c==NULL ) return SQLITE_NOMEM;
122820 c->pInput = pInput;
122821 if( pInput==0 ){
122822 c->nBytes = 0;
122823 }else if( nBytes<0 ){
122824 c->nBytes = (int)strlen(pInput);
122825 }else{
122826 c->nBytes = nBytes;
122828 c->iOffset = 0; /* start tokenizing at the beginning */
122829 c->iToken = 0;
122830 c->pToken = NULL; /* no space allocated, yet. */
122831 c->nTokenAllocated = 0;
122833 *ppCursor = &c->base;
122834 return SQLITE_OK;
122838 ** Close a tokenization cursor previously opened by a call to
122839 ** simpleOpen() above.
122841 static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
122842 simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
122843 sqlite3_free(c->pToken);
122844 sqlite3_free(c);
122845 return SQLITE_OK;
122849 ** Extract the next token from a tokenization cursor. The cursor must
122850 ** have been opened by a prior call to simpleOpen().
122852 static int simpleNext(
122853 sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
122854 const char **ppToken, /* OUT: *ppToken is the token text */
122855 int *pnBytes, /* OUT: Number of bytes in token */
122856 int *piStartOffset, /* OUT: Starting offset of token */
122857 int *piEndOffset, /* OUT: Ending offset of token */
122858 int *piPosition /* OUT: Position integer of token */
122860 simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
122861 simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
122862 unsigned char *p = (unsigned char *)c->pInput;
122864 while( c->iOffset<c->nBytes ){
122865 int iStartOffset;
122867 /* Scan past delimiter characters */
122868 while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
122869 c->iOffset++;
122872 /* Count non-delimiter characters. */
122873 iStartOffset = c->iOffset;
122874 while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
122875 c->iOffset++;
122878 if( c->iOffset>iStartOffset ){
122879 int i, n = c->iOffset-iStartOffset;
122880 if( n>c->nTokenAllocated ){
122881 char *pNew;
122882 c->nTokenAllocated = n+20;
122883 pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
122884 if( !pNew ) return SQLITE_NOMEM;
122885 c->pToken = pNew;
122887 for(i=0; i<n; i++){
122888 /* TODO(shess) This needs expansion to handle UTF-8
122889 ** case-insensitivity.
122891 unsigned char ch = p[iStartOffset+i];
122892 c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
122894 *ppToken = c->pToken;
122895 *pnBytes = n;
122896 *piStartOffset = iStartOffset;
122897 *piEndOffset = c->iOffset;
122898 *piPosition = c->iToken++;
122900 return SQLITE_OK;
122903 return SQLITE_DONE;
122907 ** The set of routines that implement the simple tokenizer
122909 static const sqlite3_tokenizer_module simpleTokenizerModule = {
122911 simpleCreate,
122912 simpleDestroy,
122913 simpleOpen,
122914 simpleClose,
122915 simpleNext,
122919 ** Allocate a new simple tokenizer. Return a pointer to the new
122920 ** tokenizer in *ppModule
122922 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
122923 sqlite3_tokenizer_module const**ppModule
122925 *ppModule = &simpleTokenizerModule;
122928 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
122930 /************** End of fts3_tokenizer1.c *************************************/
122931 /************** Begin file fts3_write.c **************************************/
122933 ** 2009 Oct 23
122935 ** The author disclaims copyright to this source code. In place of
122936 ** a legal notice, here is a blessing:
122938 ** May you do good and not evil.
122939 ** May you find forgiveness for yourself and forgive others.
122940 ** May you share freely, never taking more than you give.
122942 ******************************************************************************
122944 ** This file is part of the SQLite FTS3 extension module. Specifically,
122945 ** this file contains code to insert, update and delete rows from FTS3
122946 ** tables. It also contains code to merge FTS3 b-tree segments. Some
122947 ** of the sub-routines used to merge segments are also used by the query
122948 ** code in fts3.c.
122951 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
122953 /* #include <string.h> */
122954 /* #include <assert.h> */
122955 /* #include <stdlib.h> */
122958 ** When full-text index nodes are loaded from disk, the buffer that they
122959 ** are loaded into has the following number of bytes of padding at the end
122960 ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
122961 ** of 920 bytes is allocated for it.
122963 ** This means that if we have a pointer into a buffer containing node data,
122964 ** it is always safe to read up to two varints from it without risking an
122965 ** overread, even if the node data is corrupted.
122967 #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
122970 ** Under certain circumstances, b-tree nodes (doclists) can be loaded into
122971 ** memory incrementally instead of all at once. This can be a big performance
122972 ** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
122973 ** method before retrieving all query results (as may happen, for example,
122974 ** if a query has a LIMIT clause).
122976 ** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD
122977 ** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
122978 ** The code is written so that the hard lower-limit for each of these values
122979 ** is 1. Clearly such small values would be inefficient, but can be useful
122980 ** for testing purposes.
122982 ** If this module is built with SQLITE_TEST defined, these constants may
122983 ** be overridden at runtime for testing purposes. File fts3_test.c contains
122984 ** a Tcl interface to read and write the values.
122986 #ifdef SQLITE_TEST
122987 int test_fts3_node_chunksize = (4*1024);
122988 int test_fts3_node_chunk_threshold = (4*1024)*4;
122989 # define FTS3_NODE_CHUNKSIZE test_fts3_node_chunksize
122990 # define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
122991 #else
122992 # define FTS3_NODE_CHUNKSIZE (4*1024)
122993 # define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
122994 #endif
122996 typedef struct PendingList PendingList;
122997 typedef struct SegmentNode SegmentNode;
122998 typedef struct SegmentWriter SegmentWriter;
123001 ** An instance of the following data structure is used to build doclists
123002 ** incrementally. See function fts3PendingListAppend() for details.
123004 struct PendingList {
123005 int nData;
123006 char *aData;
123007 int nSpace;
123008 sqlite3_int64 iLastDocid;
123009 sqlite3_int64 iLastCol;
123010 sqlite3_int64 iLastPos;
123015 ** Each cursor has a (possibly empty) linked list of the following objects.
123017 struct Fts3DeferredToken {
123018 Fts3PhraseToken *pToken; /* Pointer to corresponding expr token */
123019 int iCol; /* Column token must occur in */
123020 Fts3DeferredToken *pNext; /* Next in list of deferred tokens */
123021 PendingList *pList; /* Doclist is assembled here */
123025 ** An instance of this structure is used to iterate through the terms on
123026 ** a contiguous set of segment b-tree leaf nodes. Although the details of
123027 ** this structure are only manipulated by code in this file, opaque handles
123028 ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
123029 ** terms when querying the full-text index. See functions:
123031 ** sqlite3Fts3SegReaderNew()
123032 ** sqlite3Fts3SegReaderFree()
123033 ** sqlite3Fts3SegReaderIterate()
123035 ** Methods used to manipulate Fts3SegReader structures:
123037 ** fts3SegReaderNext()
123038 ** fts3SegReaderFirstDocid()
123039 ** fts3SegReaderNextDocid()
123041 struct Fts3SegReader {
123042 int iIdx; /* Index within level, or 0x7FFFFFFF for PT */
123044 sqlite3_int64 iStartBlock; /* Rowid of first leaf block to traverse */
123045 sqlite3_int64 iLeafEndBlock; /* Rowid of final leaf block to traverse */
123046 sqlite3_int64 iEndBlock; /* Rowid of final block in segment (or 0) */
123047 sqlite3_int64 iCurrentBlock; /* Current leaf block (or 0) */
123049 char *aNode; /* Pointer to node data (or NULL) */
123050 int nNode; /* Size of buffer at aNode (or 0) */
123051 int nPopulate; /* If >0, bytes of buffer aNode[] loaded */
123052 sqlite3_blob *pBlob; /* If not NULL, blob handle to read node */
123054 Fts3HashElem **ppNextElem;
123056 /* Variables set by fts3SegReaderNext(). These may be read directly
123057 ** by the caller. They are valid from the time SegmentReaderNew() returns
123058 ** until SegmentReaderNext() returns something other than SQLITE_OK
123059 ** (i.e. SQLITE_DONE).
123061 int nTerm; /* Number of bytes in current term */
123062 char *zTerm; /* Pointer to current term */
123063 int nTermAlloc; /* Allocated size of zTerm buffer */
123064 char *aDoclist; /* Pointer to doclist of current entry */
123065 int nDoclist; /* Size of doclist in current entry */
123067 /* The following variables are used by fts3SegReaderNextDocid() to iterate
123068 ** through the current doclist (aDoclist/nDoclist).
123070 char *pOffsetList;
123071 int nOffsetList; /* For descending pending seg-readers only */
123072 sqlite3_int64 iDocid;
123075 #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
123076 #define fts3SegReaderIsRootOnly(p) ((p)->aNode==(char *)&(p)[1])
123079 ** An instance of this structure is used to create a segment b-tree in the
123080 ** database. The internal details of this type are only accessed by the
123081 ** following functions:
123083 ** fts3SegWriterAdd()
123084 ** fts3SegWriterFlush()
123085 ** fts3SegWriterFree()
123087 struct SegmentWriter {
123088 SegmentNode *pTree; /* Pointer to interior tree structure */
123089 sqlite3_int64 iFirst; /* First slot in %_segments written */
123090 sqlite3_int64 iFree; /* Next free slot in %_segments */
123091 char *zTerm; /* Pointer to previous term buffer */
123092 int nTerm; /* Number of bytes in zTerm */
123093 int nMalloc; /* Size of malloc'd buffer at zMalloc */
123094 char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
123095 int nSize; /* Size of allocation at aData */
123096 int nData; /* Bytes of data in aData */
123097 char *aData; /* Pointer to block from malloc() */
123101 ** Type SegmentNode is used by the following three functions to create
123102 ** the interior part of the segment b+-tree structures (everything except
123103 ** the leaf nodes). These functions and type are only ever used by code
123104 ** within the fts3SegWriterXXX() family of functions described above.
123106 ** fts3NodeAddTerm()
123107 ** fts3NodeWrite()
123108 ** fts3NodeFree()
123110 ** When a b+tree is written to the database (either as a result of a merge
123111 ** or the pending-terms table being flushed), leaves are written into the
123112 ** database file as soon as they are completely populated. The interior of
123113 ** the tree is assembled in memory and written out only once all leaves have
123114 ** been populated and stored. This is Ok, as the b+-tree fanout is usually
123115 ** very large, meaning that the interior of the tree consumes relatively
123116 ** little memory.
123118 struct SegmentNode {
123119 SegmentNode *pParent; /* Parent node (or NULL for root node) */
123120 SegmentNode *pRight; /* Pointer to right-sibling */
123121 SegmentNode *pLeftmost; /* Pointer to left-most node of this depth */
123122 int nEntry; /* Number of terms written to node so far */
123123 char *zTerm; /* Pointer to previous term buffer */
123124 int nTerm; /* Number of bytes in zTerm */
123125 int nMalloc; /* Size of malloc'd buffer at zMalloc */
123126 char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
123127 int nData; /* Bytes of valid data so far */
123128 char *aData; /* Node data */
123132 ** Valid values for the second argument to fts3SqlStmt().
123134 #define SQL_DELETE_CONTENT 0
123135 #define SQL_IS_EMPTY 1
123136 #define SQL_DELETE_ALL_CONTENT 2
123137 #define SQL_DELETE_ALL_SEGMENTS 3
123138 #define SQL_DELETE_ALL_SEGDIR 4
123139 #define SQL_DELETE_ALL_DOCSIZE 5
123140 #define SQL_DELETE_ALL_STAT 6
123141 #define SQL_SELECT_CONTENT_BY_ROWID 7
123142 #define SQL_NEXT_SEGMENT_INDEX 8
123143 #define SQL_INSERT_SEGMENTS 9
123144 #define SQL_NEXT_SEGMENTS_ID 10
123145 #define SQL_INSERT_SEGDIR 11
123146 #define SQL_SELECT_LEVEL 12
123147 #define SQL_SELECT_LEVEL_RANGE 13
123148 #define SQL_SELECT_LEVEL_COUNT 14
123149 #define SQL_SELECT_SEGDIR_MAX_LEVEL 15
123150 #define SQL_DELETE_SEGDIR_LEVEL 16
123151 #define SQL_DELETE_SEGMENTS_RANGE 17
123152 #define SQL_CONTENT_INSERT 18
123153 #define SQL_DELETE_DOCSIZE 19
123154 #define SQL_REPLACE_DOCSIZE 20
123155 #define SQL_SELECT_DOCSIZE 21
123156 #define SQL_SELECT_DOCTOTAL 22
123157 #define SQL_REPLACE_DOCTOTAL 23
123159 #define SQL_SELECT_ALL_PREFIX_LEVEL 24
123160 #define SQL_DELETE_ALL_TERMS_SEGDIR 25
123162 #define SQL_DELETE_SEGDIR_RANGE 26
123165 ** This function is used to obtain an SQLite prepared statement handle
123166 ** for the statement identified by the second argument. If successful,
123167 ** *pp is set to the requested statement handle and SQLITE_OK returned.
123168 ** Otherwise, an SQLite error code is returned and *pp is set to 0.
123170 ** If argument apVal is not NULL, then it must point to an array with
123171 ** at least as many entries as the requested statement has bound
123172 ** parameters. The values are bound to the statements parameters before
123173 ** returning.
123175 static int fts3SqlStmt(
123176 Fts3Table *p, /* Virtual table handle */
123177 int eStmt, /* One of the SQL_XXX constants above */
123178 sqlite3_stmt **pp, /* OUT: Statement handle */
123179 sqlite3_value **apVal /* Values to bind to statement */
123181 const char *azSql[] = {
123182 /* 0 */ "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
123183 /* 1 */ "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
123184 /* 2 */ "DELETE FROM %Q.'%q_content'",
123185 /* 3 */ "DELETE FROM %Q.'%q_segments'",
123186 /* 4 */ "DELETE FROM %Q.'%q_segdir'",
123187 /* 5 */ "DELETE FROM %Q.'%q_docsize'",
123188 /* 6 */ "DELETE FROM %Q.'%q_stat'",
123189 /* 7 */ "SELECT %s WHERE rowid=?",
123190 /* 8 */ "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
123191 /* 9 */ "INSERT INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
123192 /* 10 */ "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
123193 /* 11 */ "INSERT INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
123195 /* Return segments in order from oldest to newest.*/
123196 /* 12 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
123197 "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
123198 /* 13 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
123199 "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
123200 "ORDER BY level DESC, idx ASC",
123202 /* 14 */ "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
123203 /* 15 */ "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
123205 /* 16 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
123206 /* 17 */ "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
123207 /* 18 */ "INSERT INTO %Q.'%q_content' VALUES(%s)",
123208 /* 19 */ "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
123209 /* 20 */ "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
123210 /* 21 */ "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
123211 /* 22 */ "SELECT value FROM %Q.'%q_stat' WHERE id=0",
123212 /* 23 */ "REPLACE INTO %Q.'%q_stat' VALUES(0,?)",
123213 /* 24 */ "",
123214 /* 25 */ "",
123216 /* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
123219 int rc = SQLITE_OK;
123220 sqlite3_stmt *pStmt;
123222 assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
123223 assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
123225 pStmt = p->aStmt[eStmt];
123226 if( !pStmt ){
123227 char *zSql;
123228 if( eStmt==SQL_CONTENT_INSERT ){
123229 zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
123230 }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
123231 zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
123232 }else{
123233 zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
123235 if( !zSql ){
123236 rc = SQLITE_NOMEM;
123237 }else{
123238 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
123239 sqlite3_free(zSql);
123240 assert( rc==SQLITE_OK || pStmt==0 );
123241 p->aStmt[eStmt] = pStmt;
123244 if( apVal ){
123245 int i;
123246 int nParam = sqlite3_bind_parameter_count(pStmt);
123247 for(i=0; rc==SQLITE_OK && i<nParam; i++){
123248 rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
123251 *pp = pStmt;
123252 return rc;
123255 static int fts3SelectDocsize(
123256 Fts3Table *pTab, /* FTS3 table handle */
123257 int eStmt, /* Either SQL_SELECT_DOCSIZE or DOCTOTAL */
123258 sqlite3_int64 iDocid, /* Docid to bind for SQL_SELECT_DOCSIZE */
123259 sqlite3_stmt **ppStmt /* OUT: Statement handle */
123261 sqlite3_stmt *pStmt = 0; /* Statement requested from fts3SqlStmt() */
123262 int rc; /* Return code */
123264 assert( eStmt==SQL_SELECT_DOCSIZE || eStmt==SQL_SELECT_DOCTOTAL );
123266 rc = fts3SqlStmt(pTab, eStmt, &pStmt, 0);
123267 if( rc==SQLITE_OK ){
123268 if( eStmt==SQL_SELECT_DOCSIZE ){
123269 sqlite3_bind_int64(pStmt, 1, iDocid);
123271 rc = sqlite3_step(pStmt);
123272 if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
123273 rc = sqlite3_reset(pStmt);
123274 if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
123275 pStmt = 0;
123276 }else{
123277 rc = SQLITE_OK;
123281 *ppStmt = pStmt;
123282 return rc;
123285 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
123286 Fts3Table *pTab, /* Fts3 table handle */
123287 sqlite3_stmt **ppStmt /* OUT: Statement handle */
123289 return fts3SelectDocsize(pTab, SQL_SELECT_DOCTOTAL, 0, ppStmt);
123292 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
123293 Fts3Table *pTab, /* Fts3 table handle */
123294 sqlite3_int64 iDocid, /* Docid to read size data for */
123295 sqlite3_stmt **ppStmt /* OUT: Statement handle */
123297 return fts3SelectDocsize(pTab, SQL_SELECT_DOCSIZE, iDocid, ppStmt);
123301 ** Similar to fts3SqlStmt(). Except, after binding the parameters in
123302 ** array apVal[] to the SQL statement identified by eStmt, the statement
123303 ** is executed.
123305 ** Returns SQLITE_OK if the statement is successfully executed, or an
123306 ** SQLite error code otherwise.
123308 static void fts3SqlExec(
123309 int *pRC, /* Result code */
123310 Fts3Table *p, /* The FTS3 table */
123311 int eStmt, /* Index of statement to evaluate */
123312 sqlite3_value **apVal /* Parameters to bind */
123314 sqlite3_stmt *pStmt;
123315 int rc;
123316 if( *pRC ) return;
123317 rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
123318 if( rc==SQLITE_OK ){
123319 sqlite3_step(pStmt);
123320 rc = sqlite3_reset(pStmt);
123322 *pRC = rc;
123327 ** This function ensures that the caller has obtained a shared-cache
123328 ** table-lock on the %_content table. This is required before reading
123329 ** data from the fts3 table. If this lock is not acquired first, then
123330 ** the caller may end up holding read-locks on the %_segments and %_segdir
123331 ** tables, but no read-lock on the %_content table. If this happens
123332 ** a second connection will be able to write to the fts3 table, but
123333 ** attempting to commit those writes might return SQLITE_LOCKED or
123334 ** SQLITE_LOCKED_SHAREDCACHE (because the commit attempts to obtain
123335 ** write-locks on the %_segments and %_segdir ** tables).
123337 ** We try to avoid this because if FTS3 returns any error when committing
123338 ** a transaction, the whole transaction will be rolled back. And this is
123339 ** not what users expect when they get SQLITE_LOCKED_SHAREDCACHE. It can
123340 ** still happen if the user reads data directly from the %_segments or
123341 ** %_segdir tables instead of going through FTS3 though.
123343 ** This reasoning does not apply to a content=xxx table.
123345 SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *p){
123346 int rc; /* Return code */
123347 sqlite3_stmt *pStmt; /* Statement used to obtain lock */
123349 if( p->zContentTbl==0 ){
123350 rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pStmt, 0);
123351 if( rc==SQLITE_OK ){
123352 sqlite3_bind_null(pStmt, 1);
123353 sqlite3_step(pStmt);
123354 rc = sqlite3_reset(pStmt);
123356 }else{
123357 rc = SQLITE_OK;
123360 return rc;
123364 ** Set *ppStmt to a statement handle that may be used to iterate through
123365 ** all rows in the %_segdir table, from oldest to newest. If successful,
123366 ** return SQLITE_OK. If an error occurs while preparing the statement,
123367 ** return an SQLite error code.
123369 ** There is only ever one instance of this SQL statement compiled for
123370 ** each FTS3 table.
123372 ** The statement returns the following columns from the %_segdir table:
123374 ** 0: idx
123375 ** 1: start_block
123376 ** 2: leaves_end_block
123377 ** 3: end_block
123378 ** 4: root
123380 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
123381 Fts3Table *p, /* FTS3 table */
123382 int iIndex, /* Index for p->aIndex[] */
123383 int iLevel, /* Level to select */
123384 sqlite3_stmt **ppStmt /* OUT: Compiled statement */
123386 int rc;
123387 sqlite3_stmt *pStmt = 0;
123389 assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
123390 assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
123391 assert( iIndex>=0 && iIndex<p->nIndex );
123393 if( iLevel<0 ){
123394 /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
123395 rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
123396 if( rc==SQLITE_OK ){
123397 sqlite3_bind_int(pStmt, 1, iIndex*FTS3_SEGDIR_MAXLEVEL);
123398 sqlite3_bind_int(pStmt, 2, (iIndex+1)*FTS3_SEGDIR_MAXLEVEL-1);
123400 }else{
123401 /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
123402 rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
123403 if( rc==SQLITE_OK ){
123404 sqlite3_bind_int(pStmt, 1, iLevel+iIndex*FTS3_SEGDIR_MAXLEVEL);
123407 *ppStmt = pStmt;
123408 return rc;
123413 ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
123414 ** if successful, or an SQLite error code otherwise.
123416 ** This function also serves to allocate the PendingList structure itself.
123417 ** For example, to create a new PendingList structure containing two
123418 ** varints:
123420 ** PendingList *p = 0;
123421 ** fts3PendingListAppendVarint(&p, 1);
123422 ** fts3PendingListAppendVarint(&p, 2);
123424 static int fts3PendingListAppendVarint(
123425 PendingList **pp, /* IN/OUT: Pointer to PendingList struct */
123426 sqlite3_int64 i /* Value to append to data */
123428 PendingList *p = *pp;
123430 /* Allocate or grow the PendingList as required. */
123431 if( !p ){
123432 p = sqlite3_malloc(sizeof(*p) + 100);
123433 if( !p ){
123434 return SQLITE_NOMEM;
123436 p->nSpace = 100;
123437 p->aData = (char *)&p[1];
123438 p->nData = 0;
123440 else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
123441 int nNew = p->nSpace * 2;
123442 p = sqlite3_realloc(p, sizeof(*p) + nNew);
123443 if( !p ){
123444 sqlite3_free(*pp);
123445 *pp = 0;
123446 return SQLITE_NOMEM;
123448 p->nSpace = nNew;
123449 p->aData = (char *)&p[1];
123452 /* Append the new serialized varint to the end of the list. */
123453 p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
123454 p->aData[p->nData] = '\0';
123455 *pp = p;
123456 return SQLITE_OK;
123460 ** Add a docid/column/position entry to a PendingList structure. Non-zero
123461 ** is returned if the structure is sqlite3_realloced as part of adding
123462 ** the entry. Otherwise, zero.
123464 ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
123465 ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
123466 ** it is set to SQLITE_OK.
123468 static int fts3PendingListAppend(
123469 PendingList **pp, /* IN/OUT: PendingList structure */
123470 sqlite3_int64 iDocid, /* Docid for entry to add */
123471 sqlite3_int64 iCol, /* Column for entry to add */
123472 sqlite3_int64 iPos, /* Position of term for entry to add */
123473 int *pRc /* OUT: Return code */
123475 PendingList *p = *pp;
123476 int rc = SQLITE_OK;
123478 assert( !p || p->iLastDocid<=iDocid );
123480 if( !p || p->iLastDocid!=iDocid ){
123481 sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
123482 if( p ){
123483 assert( p->nData<p->nSpace );
123484 assert( p->aData[p->nData]==0 );
123485 p->nData++;
123487 if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
123488 goto pendinglistappend_out;
123490 p->iLastCol = -1;
123491 p->iLastPos = 0;
123492 p->iLastDocid = iDocid;
123494 if( iCol>0 && p->iLastCol!=iCol ){
123495 if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
123496 || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
123498 goto pendinglistappend_out;
123500 p->iLastCol = iCol;
123501 p->iLastPos = 0;
123503 if( iCol>=0 ){
123504 assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
123505 rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
123506 if( rc==SQLITE_OK ){
123507 p->iLastPos = iPos;
123511 pendinglistappend_out:
123512 *pRc = rc;
123513 if( p!=*pp ){
123514 *pp = p;
123515 return 1;
123517 return 0;
123521 ** Free a PendingList object allocated by fts3PendingListAppend().
123523 static void fts3PendingListDelete(PendingList *pList){
123524 sqlite3_free(pList);
123528 ** Add an entry to one of the pending-terms hash tables.
123530 static int fts3PendingTermsAddOne(
123531 Fts3Table *p,
123532 int iCol,
123533 int iPos,
123534 Fts3Hash *pHash, /* Pending terms hash table to add entry to */
123535 const char *zToken,
123536 int nToken
123538 PendingList *pList;
123539 int rc = SQLITE_OK;
123541 pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
123542 if( pList ){
123543 p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
123545 if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
123546 if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
123547 /* Malloc failed while inserting the new entry. This can only
123548 ** happen if there was no previous entry for this token.
123550 assert( 0==fts3HashFind(pHash, zToken, nToken) );
123551 sqlite3_free(pList);
123552 rc = SQLITE_NOMEM;
123555 if( rc==SQLITE_OK ){
123556 p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
123558 return rc;
123562 ** Tokenize the nul-terminated string zText and add all tokens to the
123563 ** pending-terms hash-table. The docid used is that currently stored in
123564 ** p->iPrevDocid, and the column is specified by argument iCol.
123566 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
123568 static int fts3PendingTermsAdd(
123569 Fts3Table *p, /* Table into which text will be inserted */
123570 const char *zText, /* Text of document to be inserted */
123571 int iCol, /* Column into which text is being inserted */
123572 u32 *pnWord /* OUT: Number of tokens inserted */
123574 int rc;
123575 int iStart;
123576 int iEnd;
123577 int iPos;
123578 int nWord = 0;
123580 char const *zToken;
123581 int nToken;
123583 sqlite3_tokenizer *pTokenizer = p->pTokenizer;
123584 sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
123585 sqlite3_tokenizer_cursor *pCsr;
123586 int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
123587 const char**,int*,int*,int*,int*);
123589 assert( pTokenizer && pModule );
123591 /* If the user has inserted a NULL value, this function may be called with
123592 ** zText==0. In this case, add zero token entries to the hash table and
123593 ** return early. */
123594 if( zText==0 ){
123595 *pnWord = 0;
123596 return SQLITE_OK;
123599 rc = pModule->xOpen(pTokenizer, zText, -1, &pCsr);
123600 if( rc!=SQLITE_OK ){
123601 return rc;
123603 pCsr->pTokenizer = pTokenizer;
123605 xNext = pModule->xNext;
123606 while( SQLITE_OK==rc
123607 && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
123609 int i;
123610 if( iPos>=nWord ) nWord = iPos+1;
123612 /* Positions cannot be negative; we use -1 as a terminator internally.
123613 ** Tokens must have a non-zero length.
123615 if( iPos<0 || !zToken || nToken<=0 ){
123616 rc = SQLITE_ERROR;
123617 break;
123620 /* Add the term to the terms index */
123621 rc = fts3PendingTermsAddOne(
123622 p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
123625 /* Add the term to each of the prefix indexes that it is not too
123626 ** short for. */
123627 for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
123628 struct Fts3Index *pIndex = &p->aIndex[i];
123629 if( nToken<pIndex->nPrefix ) continue;
123630 rc = fts3PendingTermsAddOne(
123631 p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
123636 pModule->xClose(pCsr);
123637 *pnWord = nWord;
123638 return (rc==SQLITE_DONE ? SQLITE_OK : rc);
123642 ** Calling this function indicates that subsequent calls to
123643 ** fts3PendingTermsAdd() are to add term/position-list pairs for the
123644 ** contents of the document with docid iDocid.
123646 static int fts3PendingTermsDocid(Fts3Table *p, sqlite_int64 iDocid){
123647 /* TODO(shess) Explore whether partially flushing the buffer on
123648 ** forced-flush would provide better performance. I suspect that if
123649 ** we ordered the doclists by size and flushed the largest until the
123650 ** buffer was half empty, that would let the less frequent terms
123651 ** generate longer doclists.
123653 if( iDocid<=p->iPrevDocid || p->nPendingData>p->nMaxPendingData ){
123654 int rc = sqlite3Fts3PendingTermsFlush(p);
123655 if( rc!=SQLITE_OK ) return rc;
123657 p->iPrevDocid = iDocid;
123658 return SQLITE_OK;
123662 ** Discard the contents of the pending-terms hash tables.
123664 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
123665 int i;
123666 for(i=0; i<p->nIndex; i++){
123667 Fts3HashElem *pElem;
123668 Fts3Hash *pHash = &p->aIndex[i].hPending;
123669 for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
123670 PendingList *pList = (PendingList *)fts3HashData(pElem);
123671 fts3PendingListDelete(pList);
123673 fts3HashClear(pHash);
123675 p->nPendingData = 0;
123679 ** This function is called by the xUpdate() method as part of an INSERT
123680 ** operation. It adds entries for each term in the new record to the
123681 ** pendingTerms hash table.
123683 ** Argument apVal is the same as the similarly named argument passed to
123684 ** fts3InsertData(). Parameter iDocid is the docid of the new row.
123686 static int fts3InsertTerms(Fts3Table *p, sqlite3_value **apVal, u32 *aSz){
123687 int i; /* Iterator variable */
123688 for(i=2; i<p->nColumn+2; i++){
123689 const char *zText = (const char *)sqlite3_value_text(apVal[i]);
123690 int rc = fts3PendingTermsAdd(p, zText, i-2, &aSz[i-2]);
123691 if( rc!=SQLITE_OK ){
123692 return rc;
123694 aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
123696 return SQLITE_OK;
123700 ** This function is called by the xUpdate() method for an INSERT operation.
123701 ** The apVal parameter is passed a copy of the apVal argument passed by
123702 ** SQLite to the xUpdate() method. i.e:
123704 ** apVal[0] Not used for INSERT.
123705 ** apVal[1] rowid
123706 ** apVal[2] Left-most user-defined column
123707 ** ...
123708 ** apVal[p->nColumn+1] Right-most user-defined column
123709 ** apVal[p->nColumn+2] Hidden column with same name as table
123710 ** apVal[p->nColumn+3] Hidden "docid" column (alias for rowid)
123712 static int fts3InsertData(
123713 Fts3Table *p, /* Full-text table */
123714 sqlite3_value **apVal, /* Array of values to insert */
123715 sqlite3_int64 *piDocid /* OUT: Docid for row just inserted */
123717 int rc; /* Return code */
123718 sqlite3_stmt *pContentInsert; /* INSERT INTO %_content VALUES(...) */
123720 if( p->zContentTbl ){
123721 sqlite3_value *pRowid = apVal[p->nColumn+3];
123722 if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
123723 pRowid = apVal[1];
123725 if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
123726 return SQLITE_CONSTRAINT;
123728 *piDocid = sqlite3_value_int64(pRowid);
123729 return SQLITE_OK;
123732 /* Locate the statement handle used to insert data into the %_content
123733 ** table. The SQL for this statement is:
123735 ** INSERT INTO %_content VALUES(?, ?, ?, ...)
123737 ** The statement features N '?' variables, where N is the number of user
123738 ** defined columns in the FTS3 table, plus one for the docid field.
123740 rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
123741 if( rc!=SQLITE_OK ){
123742 return rc;
123745 /* There is a quirk here. The users INSERT statement may have specified
123746 ** a value for the "rowid" field, for the "docid" field, or for both.
123747 ** Which is a problem, since "rowid" and "docid" are aliases for the
123748 ** same value. For example:
123750 ** INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
123752 ** In FTS3, this is an error. It is an error to specify non-NULL values
123753 ** for both docid and some other rowid alias.
123755 if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
123756 if( SQLITE_NULL==sqlite3_value_type(apVal[0])
123757 && SQLITE_NULL!=sqlite3_value_type(apVal[1])
123759 /* A rowid/docid conflict. */
123760 return SQLITE_ERROR;
123762 rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
123763 if( rc!=SQLITE_OK ) return rc;
123766 /* Execute the statement to insert the record. Set *piDocid to the
123767 ** new docid value.
123769 sqlite3_step(pContentInsert);
123770 rc = sqlite3_reset(pContentInsert);
123772 *piDocid = sqlite3_last_insert_rowid(p->db);
123773 return rc;
123779 ** Remove all data from the FTS3 table. Clear the hash table containing
123780 ** pending terms.
123782 static int fts3DeleteAll(Fts3Table *p, int bContent){
123783 int rc = SQLITE_OK; /* Return code */
123785 /* Discard the contents of the pending-terms hash table. */
123786 sqlite3Fts3PendingTermsClear(p);
123788 /* Delete everything from the shadow tables. Except, leave %_content as
123789 ** is if bContent is false. */
123790 assert( p->zContentTbl==0 || bContent==0 );
123791 if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
123792 fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
123793 fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
123794 if( p->bHasDocsize ){
123795 fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
123797 if( p->bHasStat ){
123798 fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
123800 return rc;
123804 ** The first element in the apVal[] array is assumed to contain the docid
123805 ** (an integer) of a row about to be deleted. Remove all terms from the
123806 ** full-text index.
123808 static void fts3DeleteTerms(
123809 int *pRC, /* Result code */
123810 Fts3Table *p, /* The FTS table to delete from */
123811 sqlite3_value *pRowid, /* The docid to be deleted */
123812 u32 *aSz /* Sizes of deleted document written here */
123814 int rc;
123815 sqlite3_stmt *pSelect;
123817 if( *pRC ) return;
123818 rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
123819 if( rc==SQLITE_OK ){
123820 if( SQLITE_ROW==sqlite3_step(pSelect) ){
123821 int i;
123822 for(i=1; i<=p->nColumn; i++){
123823 const char *zText = (const char *)sqlite3_column_text(pSelect, i);
123824 rc = fts3PendingTermsAdd(p, zText, -1, &aSz[i-1]);
123825 if( rc!=SQLITE_OK ){
123826 sqlite3_reset(pSelect);
123827 *pRC = rc;
123828 return;
123830 aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
123833 rc = sqlite3_reset(pSelect);
123834 }else{
123835 sqlite3_reset(pSelect);
123837 *pRC = rc;
123841 ** Forward declaration to account for the circular dependency between
123842 ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
123844 static int fts3SegmentMerge(Fts3Table *, int, int);
123847 ** This function allocates a new level iLevel index in the segdir table.
123848 ** Usually, indexes are allocated within a level sequentially starting
123849 ** with 0, so the allocated index is one greater than the value returned
123850 ** by:
123852 ** SELECT max(idx) FROM %_segdir WHERE level = :iLevel
123854 ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
123855 ** level, they are merged into a single level (iLevel+1) segment and the
123856 ** allocated index is 0.
123858 ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
123859 ** returned. Otherwise, an SQLite error code is returned.
123861 static int fts3AllocateSegdirIdx(
123862 Fts3Table *p,
123863 int iIndex, /* Index for p->aIndex */
123864 int iLevel,
123865 int *piIdx
123867 int rc; /* Return Code */
123868 sqlite3_stmt *pNextIdx; /* Query for next idx at level iLevel */
123869 int iNext = 0; /* Result of query pNextIdx */
123871 /* Set variable iNext to the next available segdir index at level iLevel. */
123872 rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
123873 if( rc==SQLITE_OK ){
123874 sqlite3_bind_int(pNextIdx, 1, iIndex*FTS3_SEGDIR_MAXLEVEL + iLevel);
123875 if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
123876 iNext = sqlite3_column_int(pNextIdx, 0);
123878 rc = sqlite3_reset(pNextIdx);
123881 if( rc==SQLITE_OK ){
123882 /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
123883 ** full, merge all segments in level iLevel into a single iLevel+1
123884 ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
123885 ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
123887 if( iNext>=FTS3_MERGE_COUNT ){
123888 rc = fts3SegmentMerge(p, iIndex, iLevel);
123889 *piIdx = 0;
123890 }else{
123891 *piIdx = iNext;
123895 return rc;
123899 ** The %_segments table is declared as follows:
123901 ** CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
123903 ** This function reads data from a single row of the %_segments table. The
123904 ** specific row is identified by the iBlockid parameter. If paBlob is not
123905 ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
123906 ** with the contents of the blob stored in the "block" column of the
123907 ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
123908 ** to the size of the blob in bytes before returning.
123910 ** If an error occurs, or the table does not contain the specified row,
123911 ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
123912 ** paBlob is non-NULL, then it is the responsibility of the caller to
123913 ** eventually free the returned buffer.
123915 ** This function may leave an open sqlite3_blob* handle in the
123916 ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
123917 ** to this function. The handle may be closed by calling the
123918 ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
123919 ** performance improvement, but the blob handle should always be closed
123920 ** before control is returned to the user (to prevent a lock being held
123921 ** on the database file for longer than necessary). Thus, any virtual table
123922 ** method (xFilter etc.) that may directly or indirectly call this function
123923 ** must call sqlite3Fts3SegmentsClose() before returning.
123925 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
123926 Fts3Table *p, /* FTS3 table handle */
123927 sqlite3_int64 iBlockid, /* Access the row with blockid=$iBlockid */
123928 char **paBlob, /* OUT: Blob data in malloc'd buffer */
123929 int *pnBlob, /* OUT: Size of blob data */
123930 int *pnLoad /* OUT: Bytes actually loaded */
123932 int rc; /* Return code */
123934 /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
123935 assert( pnBlob);
123937 if( p->pSegments ){
123938 rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
123939 }else{
123940 if( 0==p->zSegmentsTbl ){
123941 p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
123942 if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
123944 rc = sqlite3_blob_open(
123945 p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
123949 if( rc==SQLITE_OK ){
123950 int nByte = sqlite3_blob_bytes(p->pSegments);
123951 *pnBlob = nByte;
123952 if( paBlob ){
123953 char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
123954 if( !aByte ){
123955 rc = SQLITE_NOMEM;
123956 }else{
123957 if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
123958 nByte = FTS3_NODE_CHUNKSIZE;
123959 *pnLoad = nByte;
123961 rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
123962 memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
123963 if( rc!=SQLITE_OK ){
123964 sqlite3_free(aByte);
123965 aByte = 0;
123968 *paBlob = aByte;
123972 return rc;
123976 ** Close the blob handle at p->pSegments, if it is open. See comments above
123977 ** the sqlite3Fts3ReadBlock() function for details.
123979 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
123980 sqlite3_blob_close(p->pSegments);
123981 p->pSegments = 0;
123984 static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
123985 int nRead; /* Number of bytes to read */
123986 int rc; /* Return code */
123988 nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
123989 rc = sqlite3_blob_read(
123990 pReader->pBlob,
123991 &pReader->aNode[pReader->nPopulate],
123992 nRead,
123993 pReader->nPopulate
123996 if( rc==SQLITE_OK ){
123997 pReader->nPopulate += nRead;
123998 memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
123999 if( pReader->nPopulate==pReader->nNode ){
124000 sqlite3_blob_close(pReader->pBlob);
124001 pReader->pBlob = 0;
124002 pReader->nPopulate = 0;
124005 return rc;
124008 static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
124009 int rc = SQLITE_OK;
124010 assert( !pReader->pBlob
124011 || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
124013 while( pReader->pBlob && rc==SQLITE_OK
124014 && (pFrom - pReader->aNode + nByte)>pReader->nPopulate
124016 rc = fts3SegReaderIncrRead(pReader);
124018 return rc;
124022 ** Move the iterator passed as the first argument to the next term in the
124023 ** segment. If successful, SQLITE_OK is returned. If there is no next term,
124024 ** SQLITE_DONE. Otherwise, an SQLite error code.
124026 static int fts3SegReaderNext(
124027 Fts3Table *p,
124028 Fts3SegReader *pReader,
124029 int bIncr
124031 int rc; /* Return code of various sub-routines */
124032 char *pNext; /* Cursor variable */
124033 int nPrefix; /* Number of bytes in term prefix */
124034 int nSuffix; /* Number of bytes in term suffix */
124036 if( !pReader->aDoclist ){
124037 pNext = pReader->aNode;
124038 }else{
124039 pNext = &pReader->aDoclist[pReader->nDoclist];
124042 if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
124044 if( fts3SegReaderIsPending(pReader) ){
124045 Fts3HashElem *pElem = *(pReader->ppNextElem);
124046 if( pElem==0 ){
124047 pReader->aNode = 0;
124048 }else{
124049 PendingList *pList = (PendingList *)fts3HashData(pElem);
124050 pReader->zTerm = (char *)fts3HashKey(pElem);
124051 pReader->nTerm = fts3HashKeysize(pElem);
124052 pReader->nNode = pReader->nDoclist = pList->nData + 1;
124053 pReader->aNode = pReader->aDoclist = pList->aData;
124054 pReader->ppNextElem++;
124055 assert( pReader->aNode );
124057 return SQLITE_OK;
124060 if( !fts3SegReaderIsRootOnly(pReader) ){
124061 sqlite3_free(pReader->aNode);
124062 sqlite3_blob_close(pReader->pBlob);
124063 pReader->pBlob = 0;
124065 pReader->aNode = 0;
124067 /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
124068 ** blocks have already been traversed. */
124069 assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
124070 if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
124071 return SQLITE_OK;
124074 rc = sqlite3Fts3ReadBlock(
124075 p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode,
124076 (bIncr ? &pReader->nPopulate : 0)
124078 if( rc!=SQLITE_OK ) return rc;
124079 assert( pReader->pBlob==0 );
124080 if( bIncr && pReader->nPopulate<pReader->nNode ){
124081 pReader->pBlob = p->pSegments;
124082 p->pSegments = 0;
124084 pNext = pReader->aNode;
124087 assert( !fts3SegReaderIsPending(pReader) );
124089 rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
124090 if( rc!=SQLITE_OK ) return rc;
124092 /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
124093 ** safe (no risk of overread) even if the node data is corrupted. */
124094 pNext += sqlite3Fts3GetVarint32(pNext, &nPrefix);
124095 pNext += sqlite3Fts3GetVarint32(pNext, &nSuffix);
124096 if( nPrefix<0 || nSuffix<=0
124097 || &pNext[nSuffix]>&pReader->aNode[pReader->nNode]
124099 return FTS_CORRUPT_VTAB;
124102 if( nPrefix+nSuffix>pReader->nTermAlloc ){
124103 int nNew = (nPrefix+nSuffix)*2;
124104 char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
124105 if( !zNew ){
124106 return SQLITE_NOMEM;
124108 pReader->zTerm = zNew;
124109 pReader->nTermAlloc = nNew;
124112 rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
124113 if( rc!=SQLITE_OK ) return rc;
124115 memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
124116 pReader->nTerm = nPrefix+nSuffix;
124117 pNext += nSuffix;
124118 pNext += sqlite3Fts3GetVarint32(pNext, &pReader->nDoclist);
124119 pReader->aDoclist = pNext;
124120 pReader->pOffsetList = 0;
124122 /* Check that the doclist does not appear to extend past the end of the
124123 ** b-tree node. And that the final byte of the doclist is 0x00. If either
124124 ** of these statements is untrue, then the data structure is corrupt.
124126 if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode]
124127 || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
124129 return FTS_CORRUPT_VTAB;
124131 return SQLITE_OK;
124135 ** Set the SegReader to point to the first docid in the doclist associated
124136 ** with the current term.
124138 static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
124139 int rc = SQLITE_OK;
124140 assert( pReader->aDoclist );
124141 assert( !pReader->pOffsetList );
124142 if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
124143 u8 bEof = 0;
124144 pReader->iDocid = 0;
124145 pReader->nOffsetList = 0;
124146 sqlite3Fts3DoclistPrev(0,
124147 pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList,
124148 &pReader->iDocid, &pReader->nOffsetList, &bEof
124150 }else{
124151 rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
124152 if( rc==SQLITE_OK ){
124153 int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
124154 pReader->pOffsetList = &pReader->aDoclist[n];
124157 return rc;
124161 ** Advance the SegReader to point to the next docid in the doclist
124162 ** associated with the current term.
124164 ** If arguments ppOffsetList and pnOffsetList are not NULL, then
124165 ** *ppOffsetList is set to point to the first column-offset list
124166 ** in the doclist entry (i.e. immediately past the docid varint).
124167 ** *pnOffsetList is set to the length of the set of column-offset
124168 ** lists, not including the nul-terminator byte. For example:
124170 static int fts3SegReaderNextDocid(
124171 Fts3Table *pTab,
124172 Fts3SegReader *pReader, /* Reader to advance to next docid */
124173 char **ppOffsetList, /* OUT: Pointer to current position-list */
124174 int *pnOffsetList /* OUT: Length of *ppOffsetList in bytes */
124176 int rc = SQLITE_OK;
124177 char *p = pReader->pOffsetList;
124178 char c = 0;
124180 assert( p );
124182 if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
124183 /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
124184 ** Pending-terms doclists are always built up in ascending order, so
124185 ** we have to iterate through them backwards here. */
124186 u8 bEof = 0;
124187 if( ppOffsetList ){
124188 *ppOffsetList = pReader->pOffsetList;
124189 *pnOffsetList = pReader->nOffsetList - 1;
124191 sqlite3Fts3DoclistPrev(0,
124192 pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
124193 &pReader->nOffsetList, &bEof
124195 if( bEof ){
124196 pReader->pOffsetList = 0;
124197 }else{
124198 pReader->pOffsetList = p;
124200 }else{
124201 char *pEnd = &pReader->aDoclist[pReader->nDoclist];
124203 /* Pointer p currently points at the first byte of an offset list. The
124204 ** following block advances it to point one byte past the end of
124205 ** the same offset list. */
124206 while( 1 ){
124208 /* The following line of code (and the "p++" below the while() loop) is
124209 ** normally all that is required to move pointer p to the desired
124210 ** position. The exception is if this node is being loaded from disk
124211 ** incrementally and pointer "p" now points to the first byte passed
124212 ** the populated part of pReader->aNode[].
124214 while( *p | c ) c = *p++ & 0x80;
124215 assert( *p==0 );
124217 if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
124218 rc = fts3SegReaderIncrRead(pReader);
124219 if( rc!=SQLITE_OK ) return rc;
124223 /* If required, populate the output variables with a pointer to and the
124224 ** size of the previous offset-list.
124226 if( ppOffsetList ){
124227 *ppOffsetList = pReader->pOffsetList;
124228 *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
124231 while( p<pEnd && *p==0 ) p++;
124233 /* If there are no more entries in the doclist, set pOffsetList to
124234 ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
124235 ** Fts3SegReader.pOffsetList to point to the next offset list before
124236 ** returning.
124238 if( p>=pEnd ){
124239 pReader->pOffsetList = 0;
124240 }else{
124241 rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
124242 if( rc==SQLITE_OK ){
124243 sqlite3_int64 iDelta;
124244 pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
124245 if( pTab->bDescIdx ){
124246 pReader->iDocid -= iDelta;
124247 }else{
124248 pReader->iDocid += iDelta;
124254 return SQLITE_OK;
124258 SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
124259 Fts3Cursor *pCsr,
124260 Fts3MultiSegReader *pMsr,
124261 int *pnOvfl
124263 Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
124264 int nOvfl = 0;
124265 int ii;
124266 int rc = SQLITE_OK;
124267 int pgsz = p->nPgsz;
124269 assert( p->bHasStat );
124270 assert( pgsz>0 );
124272 for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
124273 Fts3SegReader *pReader = pMsr->apSegment[ii];
124274 if( !fts3SegReaderIsPending(pReader)
124275 && !fts3SegReaderIsRootOnly(pReader)
124277 sqlite3_int64 jj;
124278 for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
124279 int nBlob;
124280 rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
124281 if( rc!=SQLITE_OK ) break;
124282 if( (nBlob+35)>pgsz ){
124283 nOvfl += (nBlob + 34)/pgsz;
124288 *pnOvfl = nOvfl;
124289 return rc;
124293 ** Free all allocations associated with the iterator passed as the
124294 ** second argument.
124296 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
124297 if( pReader && !fts3SegReaderIsPending(pReader) ){
124298 sqlite3_free(pReader->zTerm);
124299 if( !fts3SegReaderIsRootOnly(pReader) ){
124300 sqlite3_free(pReader->aNode);
124301 sqlite3_blob_close(pReader->pBlob);
124304 sqlite3_free(pReader);
124308 ** Allocate a new SegReader object.
124310 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
124311 int iAge, /* Segment "age". */
124312 sqlite3_int64 iStartLeaf, /* First leaf to traverse */
124313 sqlite3_int64 iEndLeaf, /* Final leaf to traverse */
124314 sqlite3_int64 iEndBlock, /* Final block of segment */
124315 const char *zRoot, /* Buffer containing root node */
124316 int nRoot, /* Size of buffer containing root node */
124317 Fts3SegReader **ppReader /* OUT: Allocated Fts3SegReader */
124319 int rc = SQLITE_OK; /* Return code */
124320 Fts3SegReader *pReader; /* Newly allocated SegReader object */
124321 int nExtra = 0; /* Bytes to allocate segment root node */
124323 assert( iStartLeaf<=iEndLeaf );
124324 if( iStartLeaf==0 ){
124325 nExtra = nRoot + FTS3_NODE_PADDING;
124328 pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
124329 if( !pReader ){
124330 return SQLITE_NOMEM;
124332 memset(pReader, 0, sizeof(Fts3SegReader));
124333 pReader->iIdx = iAge;
124334 pReader->iStartBlock = iStartLeaf;
124335 pReader->iLeafEndBlock = iEndLeaf;
124336 pReader->iEndBlock = iEndBlock;
124338 if( nExtra ){
124339 /* The entire segment is stored in the root node. */
124340 pReader->aNode = (char *)&pReader[1];
124341 pReader->nNode = nRoot;
124342 memcpy(pReader->aNode, zRoot, nRoot);
124343 memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
124344 }else{
124345 pReader->iCurrentBlock = iStartLeaf-1;
124348 if( rc==SQLITE_OK ){
124349 *ppReader = pReader;
124350 }else{
124351 sqlite3Fts3SegReaderFree(pReader);
124353 return rc;
124357 ** This is a comparison function used as a qsort() callback when sorting
124358 ** an array of pending terms by term. This occurs as part of flushing
124359 ** the contents of the pending-terms hash table to the database.
124361 static int fts3CompareElemByTerm(const void *lhs, const void *rhs){
124362 char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
124363 char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
124364 int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
124365 int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
124367 int n = (n1<n2 ? n1 : n2);
124368 int c = memcmp(z1, z2, n);
124369 if( c==0 ){
124370 c = n1 - n2;
124372 return c;
124376 ** This function is used to allocate an Fts3SegReader that iterates through
124377 ** a subset of the terms stored in the Fts3Table.pendingTerms array.
124379 ** If the isPrefixIter parameter is zero, then the returned SegReader iterates
124380 ** through each term in the pending-terms table. Or, if isPrefixIter is
124381 ** non-zero, it iterates through each term and its prefixes. For example, if
124382 ** the pending terms hash table contains the terms "sqlite", "mysql" and
124383 ** "firebird", then the iterator visits the following 'terms' (in the order
124384 ** shown):
124386 ** f fi fir fire fireb firebi firebir firebird
124387 ** m my mys mysq mysql
124388 ** s sq sql sqli sqlit sqlite
124390 ** Whereas if isPrefixIter is zero, the terms visited are:
124392 ** firebird mysql sqlite
124394 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
124395 Fts3Table *p, /* Virtual table handle */
124396 int iIndex, /* Index for p->aIndex */
124397 const char *zTerm, /* Term to search for */
124398 int nTerm, /* Size of buffer zTerm */
124399 int bPrefix, /* True for a prefix iterator */
124400 Fts3SegReader **ppReader /* OUT: SegReader for pending-terms */
124402 Fts3SegReader *pReader = 0; /* Fts3SegReader object to return */
124403 Fts3HashElem **aElem = 0; /* Array of term hash entries to scan */
124404 int nElem = 0; /* Size of array at aElem */
124405 int rc = SQLITE_OK; /* Return Code */
124406 Fts3Hash *pHash;
124408 pHash = &p->aIndex[iIndex].hPending;
124409 if( bPrefix ){
124410 int nAlloc = 0; /* Size of allocated array at aElem */
124411 Fts3HashElem *pE = 0; /* Iterator variable */
124413 for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
124414 char *zKey = (char *)fts3HashKey(pE);
124415 int nKey = fts3HashKeysize(pE);
124416 if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
124417 if( nElem==nAlloc ){
124418 Fts3HashElem **aElem2;
124419 nAlloc += 16;
124420 aElem2 = (Fts3HashElem **)sqlite3_realloc(
124421 aElem, nAlloc*sizeof(Fts3HashElem *)
124423 if( !aElem2 ){
124424 rc = SQLITE_NOMEM;
124425 nElem = 0;
124426 break;
124428 aElem = aElem2;
124431 aElem[nElem++] = pE;
124435 /* If more than one term matches the prefix, sort the Fts3HashElem
124436 ** objects in term order using qsort(). This uses the same comparison
124437 ** callback as is used when flushing terms to disk.
124439 if( nElem>1 ){
124440 qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
124443 }else{
124444 /* The query is a simple term lookup that matches at most one term in
124445 ** the index. All that is required is a straight hash-lookup. */
124446 Fts3HashElem *pE = fts3HashFindElem(pHash, zTerm, nTerm);
124447 if( pE ){
124448 aElem = &pE;
124449 nElem = 1;
124453 if( nElem>0 ){
124454 int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
124455 pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
124456 if( !pReader ){
124457 rc = SQLITE_NOMEM;
124458 }else{
124459 memset(pReader, 0, nByte);
124460 pReader->iIdx = 0x7FFFFFFF;
124461 pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
124462 memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
124466 if( bPrefix ){
124467 sqlite3_free(aElem);
124469 *ppReader = pReader;
124470 return rc;
124474 ** Compare the entries pointed to by two Fts3SegReader structures.
124475 ** Comparison is as follows:
124477 ** 1) EOF is greater than not EOF.
124479 ** 2) The current terms (if any) are compared using memcmp(). If one
124480 ** term is a prefix of another, the longer term is considered the
124481 ** larger.
124483 ** 3) By segment age. An older segment is considered larger.
124485 static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
124486 int rc;
124487 if( pLhs->aNode && pRhs->aNode ){
124488 int rc2 = pLhs->nTerm - pRhs->nTerm;
124489 if( rc2<0 ){
124490 rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
124491 }else{
124492 rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
124494 if( rc==0 ){
124495 rc = rc2;
124497 }else{
124498 rc = (pLhs->aNode==0) - (pRhs->aNode==0);
124500 if( rc==0 ){
124501 rc = pRhs->iIdx - pLhs->iIdx;
124503 assert( rc!=0 );
124504 return rc;
124508 ** A different comparison function for SegReader structures. In this
124509 ** version, it is assumed that each SegReader points to an entry in
124510 ** a doclist for identical terms. Comparison is made as follows:
124512 ** 1) EOF (end of doclist in this case) is greater than not EOF.
124514 ** 2) By current docid.
124516 ** 3) By segment age. An older segment is considered larger.
124518 static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
124519 int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
124520 if( rc==0 ){
124521 if( pLhs->iDocid==pRhs->iDocid ){
124522 rc = pRhs->iIdx - pLhs->iIdx;
124523 }else{
124524 rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
124527 assert( pLhs->aNode && pRhs->aNode );
124528 return rc;
124530 static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
124531 int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
124532 if( rc==0 ){
124533 if( pLhs->iDocid==pRhs->iDocid ){
124534 rc = pRhs->iIdx - pLhs->iIdx;
124535 }else{
124536 rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
124539 assert( pLhs->aNode && pRhs->aNode );
124540 return rc;
124544 ** Compare the term that the Fts3SegReader object passed as the first argument
124545 ** points to with the term specified by arguments zTerm and nTerm.
124547 ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
124548 ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
124549 ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
124551 static int fts3SegReaderTermCmp(
124552 Fts3SegReader *pSeg, /* Segment reader object */
124553 const char *zTerm, /* Term to compare to */
124554 int nTerm /* Size of term zTerm in bytes */
124556 int res = 0;
124557 if( pSeg->aNode ){
124558 if( pSeg->nTerm>nTerm ){
124559 res = memcmp(pSeg->zTerm, zTerm, nTerm);
124560 }else{
124561 res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
124563 if( res==0 ){
124564 res = pSeg->nTerm-nTerm;
124567 return res;
124571 ** Argument apSegment is an array of nSegment elements. It is known that
124572 ** the final (nSegment-nSuspect) members are already in sorted order
124573 ** (according to the comparison function provided). This function shuffles
124574 ** the array around until all entries are in sorted order.
124576 static void fts3SegReaderSort(
124577 Fts3SegReader **apSegment, /* Array to sort entries of */
124578 int nSegment, /* Size of apSegment array */
124579 int nSuspect, /* Unsorted entry count */
124580 int (*xCmp)(Fts3SegReader *, Fts3SegReader *) /* Comparison function */
124582 int i; /* Iterator variable */
124584 assert( nSuspect<=nSegment );
124586 if( nSuspect==nSegment ) nSuspect--;
124587 for(i=nSuspect-1; i>=0; i--){
124588 int j;
124589 for(j=i; j<(nSegment-1); j++){
124590 Fts3SegReader *pTmp;
124591 if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
124592 pTmp = apSegment[j+1];
124593 apSegment[j+1] = apSegment[j];
124594 apSegment[j] = pTmp;
124598 #ifndef NDEBUG
124599 /* Check that the list really is sorted now. */
124600 for(i=0; i<(nSuspect-1); i++){
124601 assert( xCmp(apSegment[i], apSegment[i+1])<0 );
124603 #endif
124607 ** Insert a record into the %_segments table.
124609 static int fts3WriteSegment(
124610 Fts3Table *p, /* Virtual table handle */
124611 sqlite3_int64 iBlock, /* Block id for new block */
124612 char *z, /* Pointer to buffer containing block data */
124613 int n /* Size of buffer z in bytes */
124615 sqlite3_stmt *pStmt;
124616 int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
124617 if( rc==SQLITE_OK ){
124618 sqlite3_bind_int64(pStmt, 1, iBlock);
124619 sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
124620 sqlite3_step(pStmt);
124621 rc = sqlite3_reset(pStmt);
124623 return rc;
124627 ** Insert a record into the %_segdir table.
124629 static int fts3WriteSegdir(
124630 Fts3Table *p, /* Virtual table handle */
124631 int iLevel, /* Value for "level" field */
124632 int iIdx, /* Value for "idx" field */
124633 sqlite3_int64 iStartBlock, /* Value for "start_block" field */
124634 sqlite3_int64 iLeafEndBlock, /* Value for "leaves_end_block" field */
124635 sqlite3_int64 iEndBlock, /* Value for "end_block" field */
124636 char *zRoot, /* Blob value for "root" field */
124637 int nRoot /* Number of bytes in buffer zRoot */
124639 sqlite3_stmt *pStmt;
124640 int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
124641 if( rc==SQLITE_OK ){
124642 sqlite3_bind_int(pStmt, 1, iLevel);
124643 sqlite3_bind_int(pStmt, 2, iIdx);
124644 sqlite3_bind_int64(pStmt, 3, iStartBlock);
124645 sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
124646 sqlite3_bind_int64(pStmt, 5, iEndBlock);
124647 sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
124648 sqlite3_step(pStmt);
124649 rc = sqlite3_reset(pStmt);
124651 return rc;
124655 ** Return the size of the common prefix (if any) shared by zPrev and
124656 ** zNext, in bytes. For example,
124658 ** fts3PrefixCompress("abc", 3, "abcdef", 6) // returns 3
124659 ** fts3PrefixCompress("abX", 3, "abcdef", 6) // returns 2
124660 ** fts3PrefixCompress("abX", 3, "Xbcdef", 6) // returns 0
124662 static int fts3PrefixCompress(
124663 const char *zPrev, /* Buffer containing previous term */
124664 int nPrev, /* Size of buffer zPrev in bytes */
124665 const char *zNext, /* Buffer containing next term */
124666 int nNext /* Size of buffer zNext in bytes */
124668 int n;
124669 UNUSED_PARAMETER(nNext);
124670 for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
124671 return n;
124675 ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
124676 ** (according to memcmp) than the previous term.
124678 static int fts3NodeAddTerm(
124679 Fts3Table *p, /* Virtual table handle */
124680 SegmentNode **ppTree, /* IN/OUT: SegmentNode handle */
124681 int isCopyTerm, /* True if zTerm/nTerm is transient */
124682 const char *zTerm, /* Pointer to buffer containing term */
124683 int nTerm /* Size of term in bytes */
124685 SegmentNode *pTree = *ppTree;
124686 int rc;
124687 SegmentNode *pNew;
124689 /* First try to append the term to the current node. Return early if
124690 ** this is possible.
124692 if( pTree ){
124693 int nData = pTree->nData; /* Current size of node in bytes */
124694 int nReq = nData; /* Required space after adding zTerm */
124695 int nPrefix; /* Number of bytes of prefix compression */
124696 int nSuffix; /* Suffix length */
124698 nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
124699 nSuffix = nTerm-nPrefix;
124701 nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
124702 if( nReq<=p->nNodeSize || !pTree->zTerm ){
124704 if( nReq>p->nNodeSize ){
124705 /* An unusual case: this is the first term to be added to the node
124706 ** and the static node buffer (p->nNodeSize bytes) is not large
124707 ** enough. Use a separately malloced buffer instead This wastes
124708 ** p->nNodeSize bytes, but since this scenario only comes about when
124709 ** the database contain two terms that share a prefix of almost 2KB,
124710 ** this is not expected to be a serious problem.
124712 assert( pTree->aData==(char *)&pTree[1] );
124713 pTree->aData = (char *)sqlite3_malloc(nReq);
124714 if( !pTree->aData ){
124715 return SQLITE_NOMEM;
124719 if( pTree->zTerm ){
124720 /* There is no prefix-length field for first term in a node */
124721 nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
124724 nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
124725 memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
124726 pTree->nData = nData + nSuffix;
124727 pTree->nEntry++;
124729 if( isCopyTerm ){
124730 if( pTree->nMalloc<nTerm ){
124731 char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
124732 if( !zNew ){
124733 return SQLITE_NOMEM;
124735 pTree->nMalloc = nTerm*2;
124736 pTree->zMalloc = zNew;
124738 pTree->zTerm = pTree->zMalloc;
124739 memcpy(pTree->zTerm, zTerm, nTerm);
124740 pTree->nTerm = nTerm;
124741 }else{
124742 pTree->zTerm = (char *)zTerm;
124743 pTree->nTerm = nTerm;
124745 return SQLITE_OK;
124749 /* If control flows to here, it was not possible to append zTerm to the
124750 ** current node. Create a new node (a right-sibling of the current node).
124751 ** If this is the first node in the tree, the term is added to it.
124753 ** Otherwise, the term is not added to the new node, it is left empty for
124754 ** now. Instead, the term is inserted into the parent of pTree. If pTree
124755 ** has no parent, one is created here.
124757 pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
124758 if( !pNew ){
124759 return SQLITE_NOMEM;
124761 memset(pNew, 0, sizeof(SegmentNode));
124762 pNew->nData = 1 + FTS3_VARINT_MAX;
124763 pNew->aData = (char *)&pNew[1];
124765 if( pTree ){
124766 SegmentNode *pParent = pTree->pParent;
124767 rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
124768 if( pTree->pParent==0 ){
124769 pTree->pParent = pParent;
124771 pTree->pRight = pNew;
124772 pNew->pLeftmost = pTree->pLeftmost;
124773 pNew->pParent = pParent;
124774 pNew->zMalloc = pTree->zMalloc;
124775 pNew->nMalloc = pTree->nMalloc;
124776 pTree->zMalloc = 0;
124777 }else{
124778 pNew->pLeftmost = pNew;
124779 rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
124782 *ppTree = pNew;
124783 return rc;
124787 ** Helper function for fts3NodeWrite().
124789 static int fts3TreeFinishNode(
124790 SegmentNode *pTree,
124791 int iHeight,
124792 sqlite3_int64 iLeftChild
124794 int nStart;
124795 assert( iHeight>=1 && iHeight<128 );
124796 nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
124797 pTree->aData[nStart] = (char)iHeight;
124798 sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
124799 return nStart;
124803 ** Write the buffer for the segment node pTree and all of its peers to the
124804 ** database. Then call this function recursively to write the parent of
124805 ** pTree and its peers to the database.
124807 ** Except, if pTree is a root node, do not write it to the database. Instead,
124808 ** set output variables *paRoot and *pnRoot to contain the root node.
124810 ** If successful, SQLITE_OK is returned and output variable *piLast is
124811 ** set to the largest blockid written to the database (or zero if no
124812 ** blocks were written to the db). Otherwise, an SQLite error code is
124813 ** returned.
124815 static int fts3NodeWrite(
124816 Fts3Table *p, /* Virtual table handle */
124817 SegmentNode *pTree, /* SegmentNode handle */
124818 int iHeight, /* Height of this node in tree */
124819 sqlite3_int64 iLeaf, /* Block id of first leaf node */
124820 sqlite3_int64 iFree, /* Block id of next free slot in %_segments */
124821 sqlite3_int64 *piLast, /* OUT: Block id of last entry written */
124822 char **paRoot, /* OUT: Data for root node */
124823 int *pnRoot /* OUT: Size of root node in bytes */
124825 int rc = SQLITE_OK;
124827 if( !pTree->pParent ){
124828 /* Root node of the tree. */
124829 int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
124830 *piLast = iFree-1;
124831 *pnRoot = pTree->nData - nStart;
124832 *paRoot = &pTree->aData[nStart];
124833 }else{
124834 SegmentNode *pIter;
124835 sqlite3_int64 iNextFree = iFree;
124836 sqlite3_int64 iNextLeaf = iLeaf;
124837 for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
124838 int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
124839 int nWrite = pIter->nData - nStart;
124841 rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
124842 iNextFree++;
124843 iNextLeaf += (pIter->nEntry+1);
124845 if( rc==SQLITE_OK ){
124846 assert( iNextLeaf==iFree );
124847 rc = fts3NodeWrite(
124848 p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
124853 return rc;
124857 ** Free all memory allocations associated with the tree pTree.
124859 static void fts3NodeFree(SegmentNode *pTree){
124860 if( pTree ){
124861 SegmentNode *p = pTree->pLeftmost;
124862 fts3NodeFree(p->pParent);
124863 while( p ){
124864 SegmentNode *pRight = p->pRight;
124865 if( p->aData!=(char *)&p[1] ){
124866 sqlite3_free(p->aData);
124868 assert( pRight==0 || p->zMalloc==0 );
124869 sqlite3_free(p->zMalloc);
124870 sqlite3_free(p);
124871 p = pRight;
124877 ** Add a term to the segment being constructed by the SegmentWriter object
124878 ** *ppWriter. When adding the first term to a segment, *ppWriter should
124879 ** be passed NULL. This function will allocate a new SegmentWriter object
124880 ** and return it via the input/output variable *ppWriter in this case.
124882 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
124884 static int fts3SegWriterAdd(
124885 Fts3Table *p, /* Virtual table handle */
124886 SegmentWriter **ppWriter, /* IN/OUT: SegmentWriter handle */
124887 int isCopyTerm, /* True if buffer zTerm must be copied */
124888 const char *zTerm, /* Pointer to buffer containing term */
124889 int nTerm, /* Size of term in bytes */
124890 const char *aDoclist, /* Pointer to buffer containing doclist */
124891 int nDoclist /* Size of doclist in bytes */
124893 int nPrefix; /* Size of term prefix in bytes */
124894 int nSuffix; /* Size of term suffix in bytes */
124895 int nReq; /* Number of bytes required on leaf page */
124896 int nData;
124897 SegmentWriter *pWriter = *ppWriter;
124899 if( !pWriter ){
124900 int rc;
124901 sqlite3_stmt *pStmt;
124903 /* Allocate the SegmentWriter structure */
124904 pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
124905 if( !pWriter ) return SQLITE_NOMEM;
124906 memset(pWriter, 0, sizeof(SegmentWriter));
124907 *ppWriter = pWriter;
124909 /* Allocate a buffer in which to accumulate data */
124910 pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
124911 if( !pWriter->aData ) return SQLITE_NOMEM;
124912 pWriter->nSize = p->nNodeSize;
124914 /* Find the next free blockid in the %_segments table */
124915 rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
124916 if( rc!=SQLITE_OK ) return rc;
124917 if( SQLITE_ROW==sqlite3_step(pStmt) ){
124918 pWriter->iFree = sqlite3_column_int64(pStmt, 0);
124919 pWriter->iFirst = pWriter->iFree;
124921 rc = sqlite3_reset(pStmt);
124922 if( rc!=SQLITE_OK ) return rc;
124924 nData = pWriter->nData;
124926 nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
124927 nSuffix = nTerm-nPrefix;
124929 /* Figure out how many bytes are required by this new entry */
124930 nReq = sqlite3Fts3VarintLen(nPrefix) + /* varint containing prefix size */
124931 sqlite3Fts3VarintLen(nSuffix) + /* varint containing suffix size */
124932 nSuffix + /* Term suffix */
124933 sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
124934 nDoclist; /* Doclist data */
124936 if( nData>0 && nData+nReq>p->nNodeSize ){
124937 int rc;
124939 /* The current leaf node is full. Write it out to the database. */
124940 rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
124941 if( rc!=SQLITE_OK ) return rc;
124943 /* Add the current term to the interior node tree. The term added to
124944 ** the interior tree must:
124946 ** a) be greater than the largest term on the leaf node just written
124947 ** to the database (still available in pWriter->zTerm), and
124949 ** b) be less than or equal to the term about to be added to the new
124950 ** leaf node (zTerm/nTerm).
124952 ** In other words, it must be the prefix of zTerm 1 byte longer than
124953 ** the common prefix (if any) of zTerm and pWriter->zTerm.
124955 assert( nPrefix<nTerm );
124956 rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
124957 if( rc!=SQLITE_OK ) return rc;
124959 nData = 0;
124960 pWriter->nTerm = 0;
124962 nPrefix = 0;
124963 nSuffix = nTerm;
124964 nReq = 1 + /* varint containing prefix size */
124965 sqlite3Fts3VarintLen(nTerm) + /* varint containing suffix size */
124966 nTerm + /* Term suffix */
124967 sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
124968 nDoclist; /* Doclist data */
124971 /* If the buffer currently allocated is too small for this entry, realloc
124972 ** the buffer to make it large enough.
124974 if( nReq>pWriter->nSize ){
124975 char *aNew = sqlite3_realloc(pWriter->aData, nReq);
124976 if( !aNew ) return SQLITE_NOMEM;
124977 pWriter->aData = aNew;
124978 pWriter->nSize = nReq;
124980 assert( nData+nReq<=pWriter->nSize );
124982 /* Append the prefix-compressed term and doclist to the buffer. */
124983 nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
124984 nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
124985 memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
124986 nData += nSuffix;
124987 nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
124988 memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
124989 pWriter->nData = nData + nDoclist;
124991 /* Save the current term so that it can be used to prefix-compress the next.
124992 ** If the isCopyTerm parameter is true, then the buffer pointed to by
124993 ** zTerm is transient, so take a copy of the term data. Otherwise, just
124994 ** store a copy of the pointer.
124996 if( isCopyTerm ){
124997 if( nTerm>pWriter->nMalloc ){
124998 char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
124999 if( !zNew ){
125000 return SQLITE_NOMEM;
125002 pWriter->nMalloc = nTerm*2;
125003 pWriter->zMalloc = zNew;
125004 pWriter->zTerm = zNew;
125006 assert( pWriter->zTerm==pWriter->zMalloc );
125007 memcpy(pWriter->zTerm, zTerm, nTerm);
125008 }else{
125009 pWriter->zTerm = (char *)zTerm;
125011 pWriter->nTerm = nTerm;
125013 return SQLITE_OK;
125017 ** Flush all data associated with the SegmentWriter object pWriter to the
125018 ** database. This function must be called after all terms have been added
125019 ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
125020 ** returned. Otherwise, an SQLite error code.
125022 static int fts3SegWriterFlush(
125023 Fts3Table *p, /* Virtual table handle */
125024 SegmentWriter *pWriter, /* SegmentWriter to flush to the db */
125025 int iLevel, /* Value for 'level' column of %_segdir */
125026 int iIdx /* Value for 'idx' column of %_segdir */
125028 int rc; /* Return code */
125029 if( pWriter->pTree ){
125030 sqlite3_int64 iLast = 0; /* Largest block id written to database */
125031 sqlite3_int64 iLastLeaf; /* Largest leaf block id written to db */
125032 char *zRoot = NULL; /* Pointer to buffer containing root node */
125033 int nRoot = 0; /* Size of buffer zRoot */
125035 iLastLeaf = pWriter->iFree;
125036 rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
125037 if( rc==SQLITE_OK ){
125038 rc = fts3NodeWrite(p, pWriter->pTree, 1,
125039 pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
125041 if( rc==SQLITE_OK ){
125042 rc = fts3WriteSegdir(
125043 p, iLevel, iIdx, pWriter->iFirst, iLastLeaf, iLast, zRoot, nRoot);
125045 }else{
125046 /* The entire tree fits on the root node. Write it to the segdir table. */
125047 rc = fts3WriteSegdir(
125048 p, iLevel, iIdx, 0, 0, 0, pWriter->aData, pWriter->nData);
125050 return rc;
125054 ** Release all memory held by the SegmentWriter object passed as the
125055 ** first argument.
125057 static void fts3SegWriterFree(SegmentWriter *pWriter){
125058 if( pWriter ){
125059 sqlite3_free(pWriter->aData);
125060 sqlite3_free(pWriter->zMalloc);
125061 fts3NodeFree(pWriter->pTree);
125062 sqlite3_free(pWriter);
125067 ** The first value in the apVal[] array is assumed to contain an integer.
125068 ** This function tests if there exist any documents with docid values that
125069 ** are different from that integer. i.e. if deleting the document with docid
125070 ** pRowid would mean the FTS3 table were empty.
125072 ** If successful, *pisEmpty is set to true if the table is empty except for
125073 ** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
125074 ** error occurs, an SQLite error code is returned.
125076 static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
125077 sqlite3_stmt *pStmt;
125078 int rc;
125079 if( p->zContentTbl ){
125080 /* If using the content=xxx option, assume the table is never empty */
125081 *pisEmpty = 0;
125082 rc = SQLITE_OK;
125083 }else{
125084 rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
125085 if( rc==SQLITE_OK ){
125086 if( SQLITE_ROW==sqlite3_step(pStmt) ){
125087 *pisEmpty = sqlite3_column_int(pStmt, 0);
125089 rc = sqlite3_reset(pStmt);
125092 return rc;
125096 ** Set *pnMax to the largest segment level in the database for the index
125097 ** iIndex.
125099 ** Segment levels are stored in the 'level' column of the %_segdir table.
125101 ** Return SQLITE_OK if successful, or an SQLite error code if not.
125103 static int fts3SegmentMaxLevel(Fts3Table *p, int iIndex, int *pnMax){
125104 sqlite3_stmt *pStmt;
125105 int rc;
125106 assert( iIndex>=0 && iIndex<p->nIndex );
125108 /* Set pStmt to the compiled version of:
125110 ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
125112 ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
125114 rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
125115 if( rc!=SQLITE_OK ) return rc;
125116 sqlite3_bind_int(pStmt, 1, iIndex*FTS3_SEGDIR_MAXLEVEL);
125117 sqlite3_bind_int(pStmt, 2, (iIndex+1)*FTS3_SEGDIR_MAXLEVEL - 1);
125118 if( SQLITE_ROW==sqlite3_step(pStmt) ){
125119 *pnMax = sqlite3_column_int(pStmt, 0);
125121 return sqlite3_reset(pStmt);
125125 ** This function is used after merging multiple segments into a single large
125126 ** segment to delete the old, now redundant, segment b-trees. Specifically,
125127 ** it:
125129 ** 1) Deletes all %_segments entries for the segments associated with
125130 ** each of the SegReader objects in the array passed as the third
125131 ** argument, and
125133 ** 2) deletes all %_segdir entries with level iLevel, or all %_segdir
125134 ** entries regardless of level if (iLevel<0).
125136 ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
125138 static int fts3DeleteSegdir(
125139 Fts3Table *p, /* Virtual table handle */
125140 int iIndex, /* Index for p->aIndex */
125141 int iLevel, /* Level of %_segdir entries to delete */
125142 Fts3SegReader **apSegment, /* Array of SegReader objects */
125143 int nReader /* Size of array apSegment */
125145 int rc; /* Return Code */
125146 int i; /* Iterator variable */
125147 sqlite3_stmt *pDelete; /* SQL statement to delete rows */
125149 rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
125150 for(i=0; rc==SQLITE_OK && i<nReader; i++){
125151 Fts3SegReader *pSegment = apSegment[i];
125152 if( pSegment->iStartBlock ){
125153 sqlite3_bind_int64(pDelete, 1, pSegment->iStartBlock);
125154 sqlite3_bind_int64(pDelete, 2, pSegment->iEndBlock);
125155 sqlite3_step(pDelete);
125156 rc = sqlite3_reset(pDelete);
125159 if( rc!=SQLITE_OK ){
125160 return rc;
125163 assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
125164 if( iLevel==FTS3_SEGCURSOR_ALL ){
125165 rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
125166 if( rc==SQLITE_OK ){
125167 sqlite3_bind_int(pDelete, 1, iIndex*FTS3_SEGDIR_MAXLEVEL);
125168 sqlite3_bind_int(pDelete, 2, (iIndex+1) * FTS3_SEGDIR_MAXLEVEL - 1);
125170 }else{
125171 rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
125172 if( rc==SQLITE_OK ){
125173 sqlite3_bind_int(pDelete, 1, iIndex*FTS3_SEGDIR_MAXLEVEL + iLevel);
125177 if( rc==SQLITE_OK ){
125178 sqlite3_step(pDelete);
125179 rc = sqlite3_reset(pDelete);
125182 return rc;
125186 ** When this function is called, buffer *ppList (size *pnList bytes) contains
125187 ** a position list that may (or may not) feature multiple columns. This
125188 ** function adjusts the pointer *ppList and the length *pnList so that they
125189 ** identify the subset of the position list that corresponds to column iCol.
125191 ** If there are no entries in the input position list for column iCol, then
125192 ** *pnList is set to zero before returning.
125194 static void fts3ColumnFilter(
125195 int iCol, /* Column to filter on */
125196 char **ppList, /* IN/OUT: Pointer to position list */
125197 int *pnList /* IN/OUT: Size of buffer *ppList in bytes */
125199 char *pList = *ppList;
125200 int nList = *pnList;
125201 char *pEnd = &pList[nList];
125202 int iCurrent = 0;
125203 char *p = pList;
125205 assert( iCol>=0 );
125206 while( 1 ){
125207 char c = 0;
125208 while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
125210 if( iCol==iCurrent ){
125211 nList = (int)(p - pList);
125212 break;
125215 nList -= (int)(p - pList);
125216 pList = p;
125217 if( nList==0 ){
125218 break;
125220 p = &pList[1];
125221 p += sqlite3Fts3GetVarint32(p, &iCurrent);
125224 *ppList = pList;
125225 *pnList = nList;
125229 ** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
125230 ** existing data). Grow the buffer if required.
125232 ** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
125233 ** trying to resize the buffer, return SQLITE_NOMEM.
125235 static int fts3MsrBufferData(
125236 Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
125237 char *pList,
125238 int nList
125240 if( nList>pMsr->nBuffer ){
125241 char *pNew;
125242 pMsr->nBuffer = nList*2;
125243 pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
125244 if( !pNew ) return SQLITE_NOMEM;
125245 pMsr->aBuffer = pNew;
125248 memcpy(pMsr->aBuffer, pList, nList);
125249 return SQLITE_OK;
125252 SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
125253 Fts3Table *p, /* Virtual table handle */
125254 Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
125255 sqlite3_int64 *piDocid, /* OUT: Docid value */
125256 char **paPoslist, /* OUT: Pointer to position list */
125257 int *pnPoslist /* OUT: Size of position list in bytes */
125259 int nMerge = pMsr->nAdvance;
125260 Fts3SegReader **apSegment = pMsr->apSegment;
125261 int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
125262 p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
125265 if( nMerge==0 ){
125266 *paPoslist = 0;
125267 return SQLITE_OK;
125270 while( 1 ){
125271 Fts3SegReader *pSeg;
125272 pSeg = pMsr->apSegment[0];
125274 if( pSeg->pOffsetList==0 ){
125275 *paPoslist = 0;
125276 break;
125277 }else{
125278 int rc;
125279 char *pList;
125280 int nList;
125281 int j;
125282 sqlite3_int64 iDocid = apSegment[0]->iDocid;
125284 rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
125285 j = 1;
125286 while( rc==SQLITE_OK
125287 && j<nMerge
125288 && apSegment[j]->pOffsetList
125289 && apSegment[j]->iDocid==iDocid
125291 rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
125294 if( rc!=SQLITE_OK ) return rc;
125295 fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
125297 if( pMsr->iColFilter>=0 ){
125298 fts3ColumnFilter(pMsr->iColFilter, &pList, &nList);
125301 if( nList>0 ){
125302 if( fts3SegReaderIsPending(apSegment[0]) ){
125303 rc = fts3MsrBufferData(pMsr, pList, nList+1);
125304 if( rc!=SQLITE_OK ) return rc;
125305 *paPoslist = pMsr->aBuffer;
125306 assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
125307 }else{
125308 *paPoslist = pList;
125310 *piDocid = iDocid;
125311 *pnPoslist = nList;
125312 break;
125317 return SQLITE_OK;
125320 static int fts3SegReaderStart(
125321 Fts3Table *p, /* Virtual table handle */
125322 Fts3MultiSegReader *pCsr, /* Cursor object */
125323 const char *zTerm, /* Term searched for (or NULL) */
125324 int nTerm /* Length of zTerm in bytes */
125326 int i;
125327 int nSeg = pCsr->nSegment;
125329 /* If the Fts3SegFilter defines a specific term (or term prefix) to search
125330 ** for, then advance each segment iterator until it points to a term of
125331 ** equal or greater value than the specified term. This prevents many
125332 ** unnecessary merge/sort operations for the case where single segment
125333 ** b-tree leaf nodes contain more than one term.
125335 for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
125336 Fts3SegReader *pSeg = pCsr->apSegment[i];
125338 int rc = fts3SegReaderNext(p, pSeg, 0);
125339 if( rc!=SQLITE_OK ) return rc;
125340 }while( zTerm && fts3SegReaderTermCmp(pSeg, zTerm, nTerm)<0 );
125342 fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
125344 return SQLITE_OK;
125347 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
125348 Fts3Table *p, /* Virtual table handle */
125349 Fts3MultiSegReader *pCsr, /* Cursor object */
125350 Fts3SegFilter *pFilter /* Restrictions on range of iteration */
125352 pCsr->pFilter = pFilter;
125353 return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
125356 SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
125357 Fts3Table *p, /* Virtual table handle */
125358 Fts3MultiSegReader *pCsr, /* Cursor object */
125359 int iCol, /* Column to match on. */
125360 const char *zTerm, /* Term to iterate through a doclist for */
125361 int nTerm /* Number of bytes in zTerm */
125363 int i;
125364 int rc;
125365 int nSegment = pCsr->nSegment;
125366 int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
125367 p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
125370 assert( pCsr->pFilter==0 );
125371 assert( zTerm && nTerm>0 );
125373 /* Advance each segment iterator until it points to the term zTerm/nTerm. */
125374 rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
125375 if( rc!=SQLITE_OK ) return rc;
125377 /* Determine how many of the segments actually point to zTerm/nTerm. */
125378 for(i=0; i<nSegment; i++){
125379 Fts3SegReader *pSeg = pCsr->apSegment[i];
125380 if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
125381 break;
125384 pCsr->nAdvance = i;
125386 /* Advance each of the segments to point to the first docid. */
125387 for(i=0; i<pCsr->nAdvance; i++){
125388 rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
125389 if( rc!=SQLITE_OK ) return rc;
125391 fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
125393 assert( iCol<0 || iCol<p->nColumn );
125394 pCsr->iColFilter = iCol;
125396 return SQLITE_OK;
125400 ** This function is called on a MultiSegReader that has been started using
125401 ** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
125402 ** have been made. Calling this function puts the MultiSegReader in such
125403 ** a state that if the next two calls are:
125405 ** sqlite3Fts3SegReaderStart()
125406 ** sqlite3Fts3SegReaderStep()
125408 ** then the entire doclist for the term is available in
125409 ** MultiSegReader.aDoclist/nDoclist.
125411 SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
125412 int i; /* Used to iterate through segment-readers */
125414 assert( pCsr->zTerm==0 );
125415 assert( pCsr->nTerm==0 );
125416 assert( pCsr->aDoclist==0 );
125417 assert( pCsr->nDoclist==0 );
125419 pCsr->nAdvance = 0;
125420 pCsr->bRestart = 1;
125421 for(i=0; i<pCsr->nSegment; i++){
125422 pCsr->apSegment[i]->pOffsetList = 0;
125423 pCsr->apSegment[i]->nOffsetList = 0;
125424 pCsr->apSegment[i]->iDocid = 0;
125427 return SQLITE_OK;
125431 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
125432 Fts3Table *p, /* Virtual table handle */
125433 Fts3MultiSegReader *pCsr /* Cursor object */
125435 int rc = SQLITE_OK;
125437 int isIgnoreEmpty = (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
125438 int isRequirePos = (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
125439 int isColFilter = (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
125440 int isPrefix = (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
125441 int isScan = (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
125442 int isFirst = (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
125444 Fts3SegReader **apSegment = pCsr->apSegment;
125445 int nSegment = pCsr->nSegment;
125446 Fts3SegFilter *pFilter = pCsr->pFilter;
125447 int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
125448 p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
125451 if( pCsr->nSegment==0 ) return SQLITE_OK;
125454 int nMerge;
125455 int i;
125457 /* Advance the first pCsr->nAdvance entries in the apSegment[] array
125458 ** forward. Then sort the list in order of current term again.
125460 for(i=0; i<pCsr->nAdvance; i++){
125461 rc = fts3SegReaderNext(p, apSegment[i], 0);
125462 if( rc!=SQLITE_OK ) return rc;
125464 fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
125465 pCsr->nAdvance = 0;
125467 /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
125468 assert( rc==SQLITE_OK );
125469 if( apSegment[0]->aNode==0 ) break;
125471 pCsr->nTerm = apSegment[0]->nTerm;
125472 pCsr->zTerm = apSegment[0]->zTerm;
125474 /* If this is a prefix-search, and if the term that apSegment[0] points
125475 ** to does not share a suffix with pFilter->zTerm/nTerm, then all
125476 ** required callbacks have been made. In this case exit early.
125478 ** Similarly, if this is a search for an exact match, and the first term
125479 ** of segment apSegment[0] is not a match, exit early.
125481 if( pFilter->zTerm && !isScan ){
125482 if( pCsr->nTerm<pFilter->nTerm
125483 || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
125484 || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
125486 break;
125490 nMerge = 1;
125491 while( nMerge<nSegment
125492 && apSegment[nMerge]->aNode
125493 && apSegment[nMerge]->nTerm==pCsr->nTerm
125494 && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
125496 nMerge++;
125499 assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
125500 if( nMerge==1
125501 && !isIgnoreEmpty
125502 && !isFirst
125503 && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
125505 pCsr->nDoclist = apSegment[0]->nDoclist;
125506 if( fts3SegReaderIsPending(apSegment[0]) ){
125507 rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
125508 pCsr->aDoclist = pCsr->aBuffer;
125509 }else{
125510 pCsr->aDoclist = apSegment[0]->aDoclist;
125512 if( rc==SQLITE_OK ) rc = SQLITE_ROW;
125513 }else{
125514 int nDoclist = 0; /* Size of doclist */
125515 sqlite3_int64 iPrev = 0; /* Previous docid stored in doclist */
125517 /* The current term of the first nMerge entries in the array
125518 ** of Fts3SegReader objects is the same. The doclists must be merged
125519 ** and a single term returned with the merged doclist.
125521 for(i=0; i<nMerge; i++){
125522 fts3SegReaderFirstDocid(p, apSegment[i]);
125524 fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
125525 while( apSegment[0]->pOffsetList ){
125526 int j; /* Number of segments that share a docid */
125527 char *pList;
125528 int nList;
125529 int nByte;
125530 sqlite3_int64 iDocid = apSegment[0]->iDocid;
125531 fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
125532 j = 1;
125533 while( j<nMerge
125534 && apSegment[j]->pOffsetList
125535 && apSegment[j]->iDocid==iDocid
125537 fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
125541 if( isColFilter ){
125542 fts3ColumnFilter(pFilter->iCol, &pList, &nList);
125545 if( !isIgnoreEmpty || nList>0 ){
125547 /* Calculate the 'docid' delta value to write into the merged
125548 ** doclist. */
125549 sqlite3_int64 iDelta;
125550 if( p->bDescIdx && nDoclist>0 ){
125551 iDelta = iPrev - iDocid;
125552 }else{
125553 iDelta = iDocid - iPrev;
125555 assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
125556 assert( nDoclist>0 || iDelta==iDocid );
125558 nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
125559 if( nDoclist+nByte>pCsr->nBuffer ){
125560 char *aNew;
125561 pCsr->nBuffer = (nDoclist+nByte)*2;
125562 aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
125563 if( !aNew ){
125564 return SQLITE_NOMEM;
125566 pCsr->aBuffer = aNew;
125569 if( isFirst ){
125570 char *a = &pCsr->aBuffer[nDoclist];
125571 int nWrite;
125573 nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
125574 if( nWrite ){
125575 iPrev = iDocid;
125576 nDoclist += nWrite;
125578 }else{
125579 nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
125580 iPrev = iDocid;
125581 if( isRequirePos ){
125582 memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
125583 nDoclist += nList;
125584 pCsr->aBuffer[nDoclist++] = '\0';
125589 fts3SegReaderSort(apSegment, nMerge, j, xCmp);
125591 if( nDoclist>0 ){
125592 pCsr->aDoclist = pCsr->aBuffer;
125593 pCsr->nDoclist = nDoclist;
125594 rc = SQLITE_ROW;
125597 pCsr->nAdvance = nMerge;
125598 }while( rc==SQLITE_OK );
125600 return rc;
125604 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
125605 Fts3MultiSegReader *pCsr /* Cursor object */
125607 if( pCsr ){
125608 int i;
125609 for(i=0; i<pCsr->nSegment; i++){
125610 sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
125612 sqlite3_free(pCsr->apSegment);
125613 sqlite3_free(pCsr->aBuffer);
125615 pCsr->nSegment = 0;
125616 pCsr->apSegment = 0;
125617 pCsr->aBuffer = 0;
125622 ** Merge all level iLevel segments in the database into a single
125623 ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
125624 ** single segment with a level equal to the numerically largest level
125625 ** currently present in the database.
125627 ** If this function is called with iLevel<0, but there is only one
125628 ** segment in the database, SQLITE_DONE is returned immediately.
125629 ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
125630 ** an SQLite error code is returned.
125632 static int fts3SegmentMerge(Fts3Table *p, int iIndex, int iLevel){
125633 int rc; /* Return code */
125634 int iIdx = 0; /* Index of new segment */
125635 int iNewLevel = 0; /* Level/index to create new segment at */
125636 SegmentWriter *pWriter = 0; /* Used to write the new, merged, segment */
125637 Fts3SegFilter filter; /* Segment term filter condition */
125638 Fts3MultiSegReader csr; /* Cursor to iterate through level(s) */
125639 int bIgnoreEmpty = 0; /* True to ignore empty segments */
125641 assert( iLevel==FTS3_SEGCURSOR_ALL
125642 || iLevel==FTS3_SEGCURSOR_PENDING
125643 || iLevel>=0
125645 assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
125646 assert( iIndex>=0 && iIndex<p->nIndex );
125648 rc = sqlite3Fts3SegReaderCursor(p, iIndex, iLevel, 0, 0, 1, 0, &csr);
125649 if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
125651 if( iLevel==FTS3_SEGCURSOR_ALL ){
125652 /* This call is to merge all segments in the database to a single
125653 ** segment. The level of the new segment is equal to the the numerically
125654 ** greatest segment level currently present in the database for this
125655 ** index. The idx of the new segment is always 0. */
125656 if( csr.nSegment==1 ){
125657 rc = SQLITE_DONE;
125658 goto finished;
125660 rc = fts3SegmentMaxLevel(p, iIndex, &iNewLevel);
125661 bIgnoreEmpty = 1;
125663 }else if( iLevel==FTS3_SEGCURSOR_PENDING ){
125664 iNewLevel = iIndex * FTS3_SEGDIR_MAXLEVEL;
125665 rc = fts3AllocateSegdirIdx(p, iIndex, 0, &iIdx);
125666 }else{
125667 /* This call is to merge all segments at level iLevel. find the next
125668 ** available segment index at level iLevel+1. The call to
125669 ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
125670 ** a single iLevel+2 segment if necessary. */
125671 rc = fts3AllocateSegdirIdx(p, iIndex, iLevel+1, &iIdx);
125672 iNewLevel = iIndex * FTS3_SEGDIR_MAXLEVEL + iLevel+1;
125674 if( rc!=SQLITE_OK ) goto finished;
125675 assert( csr.nSegment>0 );
125676 assert( iNewLevel>=(iIndex*FTS3_SEGDIR_MAXLEVEL) );
125677 assert( iNewLevel<((iIndex+1)*FTS3_SEGDIR_MAXLEVEL) );
125679 memset(&filter, 0, sizeof(Fts3SegFilter));
125680 filter.flags = FTS3_SEGMENT_REQUIRE_POS;
125681 filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
125683 rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
125684 while( SQLITE_OK==rc ){
125685 rc = sqlite3Fts3SegReaderStep(p, &csr);
125686 if( rc!=SQLITE_ROW ) break;
125687 rc = fts3SegWriterAdd(p, &pWriter, 1,
125688 csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
125690 if( rc!=SQLITE_OK ) goto finished;
125691 assert( pWriter );
125693 if( iLevel!=FTS3_SEGCURSOR_PENDING ){
125694 rc = fts3DeleteSegdir(p, iIndex, iLevel, csr.apSegment, csr.nSegment);
125695 if( rc!=SQLITE_OK ) goto finished;
125697 rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
125699 finished:
125700 fts3SegWriterFree(pWriter);
125701 sqlite3Fts3SegReaderFinish(&csr);
125702 return rc;
125707 ** Flush the contents of pendingTerms to level 0 segments.
125709 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
125710 int rc = SQLITE_OK;
125711 int i;
125712 for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
125713 rc = fts3SegmentMerge(p, i, FTS3_SEGCURSOR_PENDING);
125714 if( rc==SQLITE_DONE ) rc = SQLITE_OK;
125716 sqlite3Fts3PendingTermsClear(p);
125717 return rc;
125721 ** Encode N integers as varints into a blob.
125723 static void fts3EncodeIntArray(
125724 int N, /* The number of integers to encode */
125725 u32 *a, /* The integer values */
125726 char *zBuf, /* Write the BLOB here */
125727 int *pNBuf /* Write number of bytes if zBuf[] used here */
125729 int i, j;
125730 for(i=j=0; i<N; i++){
125731 j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
125733 *pNBuf = j;
125737 ** Decode a blob of varints into N integers
125739 static void fts3DecodeIntArray(
125740 int N, /* The number of integers to decode */
125741 u32 *a, /* Write the integer values */
125742 const char *zBuf, /* The BLOB containing the varints */
125743 int nBuf /* size of the BLOB */
125745 int i, j;
125746 UNUSED_PARAMETER(nBuf);
125747 for(i=j=0; i<N; i++){
125748 sqlite3_int64 x;
125749 j += sqlite3Fts3GetVarint(&zBuf[j], &x);
125750 assert(j<=nBuf);
125751 a[i] = (u32)(x & 0xffffffff);
125756 ** Insert the sizes (in tokens) for each column of the document
125757 ** with docid equal to p->iPrevDocid. The sizes are encoded as
125758 ** a blob of varints.
125760 static void fts3InsertDocsize(
125761 int *pRC, /* Result code */
125762 Fts3Table *p, /* Table into which to insert */
125763 u32 *aSz /* Sizes of each column, in tokens */
125765 char *pBlob; /* The BLOB encoding of the document size */
125766 int nBlob; /* Number of bytes in the BLOB */
125767 sqlite3_stmt *pStmt; /* Statement used to insert the encoding */
125768 int rc; /* Result code from subfunctions */
125770 if( *pRC ) return;
125771 pBlob = sqlite3_malloc( 10*p->nColumn );
125772 if( pBlob==0 ){
125773 *pRC = SQLITE_NOMEM;
125774 return;
125776 fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
125777 rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
125778 if( rc ){
125779 sqlite3_free(pBlob);
125780 *pRC = rc;
125781 return;
125783 sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
125784 sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
125785 sqlite3_step(pStmt);
125786 *pRC = sqlite3_reset(pStmt);
125790 ** Record 0 of the %_stat table contains a blob consisting of N varints,
125791 ** where N is the number of user defined columns in the fts3 table plus
125792 ** two. If nCol is the number of user defined columns, then values of the
125793 ** varints are set as follows:
125795 ** Varint 0: Total number of rows in the table.
125797 ** Varint 1..nCol: For each column, the total number of tokens stored in
125798 ** the column for all rows of the table.
125800 ** Varint 1+nCol: The total size, in bytes, of all text values in all
125801 ** columns of all rows of the table.
125804 static void fts3UpdateDocTotals(
125805 int *pRC, /* The result code */
125806 Fts3Table *p, /* Table being updated */
125807 u32 *aSzIns, /* Size increases */
125808 u32 *aSzDel, /* Size decreases */
125809 int nChng /* Change in the number of documents */
125811 char *pBlob; /* Storage for BLOB written into %_stat */
125812 int nBlob; /* Size of BLOB written into %_stat */
125813 u32 *a; /* Array of integers that becomes the BLOB */
125814 sqlite3_stmt *pStmt; /* Statement for reading and writing */
125815 int i; /* Loop counter */
125816 int rc; /* Result code from subfunctions */
125818 const int nStat = p->nColumn+2;
125820 if( *pRC ) return;
125821 a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
125822 if( a==0 ){
125823 *pRC = SQLITE_NOMEM;
125824 return;
125826 pBlob = (char*)&a[nStat];
125827 rc = fts3SqlStmt(p, SQL_SELECT_DOCTOTAL, &pStmt, 0);
125828 if( rc ){
125829 sqlite3_free(a);
125830 *pRC = rc;
125831 return;
125833 if( sqlite3_step(pStmt)==SQLITE_ROW ){
125834 fts3DecodeIntArray(nStat, a,
125835 sqlite3_column_blob(pStmt, 0),
125836 sqlite3_column_bytes(pStmt, 0));
125837 }else{
125838 memset(a, 0, sizeof(u32)*(nStat) );
125840 sqlite3_reset(pStmt);
125841 if( nChng<0 && a[0]<(u32)(-nChng) ){
125842 a[0] = 0;
125843 }else{
125844 a[0] += nChng;
125846 for(i=0; i<p->nColumn+1; i++){
125847 u32 x = a[i+1];
125848 if( x+aSzIns[i] < aSzDel[i] ){
125849 x = 0;
125850 }else{
125851 x = x + aSzIns[i] - aSzDel[i];
125853 a[i+1] = x;
125855 fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
125856 rc = fts3SqlStmt(p, SQL_REPLACE_DOCTOTAL, &pStmt, 0);
125857 if( rc ){
125858 sqlite3_free(a);
125859 *pRC = rc;
125860 return;
125862 sqlite3_bind_blob(pStmt, 1, pBlob, nBlob, SQLITE_STATIC);
125863 sqlite3_step(pStmt);
125864 *pRC = sqlite3_reset(pStmt);
125865 sqlite3_free(a);
125868 static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
125869 int i;
125870 int bSeenDone = 0;
125871 int rc = SQLITE_OK;
125872 for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
125873 rc = fts3SegmentMerge(p, i, FTS3_SEGCURSOR_ALL);
125874 if( rc==SQLITE_DONE ){
125875 bSeenDone = 1;
125876 rc = SQLITE_OK;
125879 sqlite3Fts3SegmentsClose(p);
125880 sqlite3Fts3PendingTermsClear(p);
125882 return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
125886 ** This function is called when the user executes the following statement:
125888 ** INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
125890 ** The entire FTS index is discarded and rebuilt. If the table is one
125891 ** created using the content=xxx option, then the new index is based on
125892 ** the current contents of the xxx table. Otherwise, it is rebuilt based
125893 ** on the contents of the %_content table.
125895 static int fts3DoRebuild(Fts3Table *p){
125896 int rc; /* Return Code */
125898 rc = fts3DeleteAll(p, 0);
125899 if( rc==SQLITE_OK ){
125900 u32 *aSz = 0;
125901 u32 *aSzIns = 0;
125902 u32 *aSzDel = 0;
125903 sqlite3_stmt *pStmt = 0;
125904 int nEntry = 0;
125906 /* Compose and prepare an SQL statement to loop through the content table */
125907 char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
125908 if( !zSql ){
125909 rc = SQLITE_NOMEM;
125910 }else{
125911 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
125912 sqlite3_free(zSql);
125915 if( rc==SQLITE_OK ){
125916 int nByte = sizeof(u32) * (p->nColumn+1)*3;
125917 aSz = (u32 *)sqlite3_malloc(nByte);
125918 if( aSz==0 ){
125919 rc = SQLITE_NOMEM;
125920 }else{
125921 memset(aSz, 0, nByte);
125922 aSzIns = &aSz[p->nColumn+1];
125923 aSzDel = &aSzIns[p->nColumn+1];
125927 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
125928 int iCol;
125929 rc = fts3PendingTermsDocid(p, sqlite3_column_int64(pStmt, 0));
125930 aSz[p->nColumn] = 0;
125931 for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
125932 const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
125933 rc = fts3PendingTermsAdd(p, z, iCol, &aSz[iCol]);
125934 aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
125936 if( p->bHasDocsize ){
125937 fts3InsertDocsize(&rc, p, aSz);
125939 if( rc!=SQLITE_OK ){
125940 sqlite3_finalize(pStmt);
125941 pStmt = 0;
125942 }else{
125943 nEntry++;
125944 for(iCol=0; iCol<=p->nColumn; iCol++){
125945 aSzIns[iCol] += aSz[iCol];
125949 if( p->bHasStat ){
125950 fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
125952 sqlite3_free(aSz);
125954 if( pStmt ){
125955 int rc2 = sqlite3_finalize(pStmt);
125956 if( rc==SQLITE_OK ){
125957 rc = rc2;
125962 return rc;
125966 ** Handle a 'special' INSERT of the form:
125968 ** "INSERT INTO tbl(tbl) VALUES(<expr>)"
125970 ** Argument pVal contains the result of <expr>. Currently the only
125971 ** meaningful value to insert is the text 'optimize'.
125973 static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
125974 int rc; /* Return Code */
125975 const char *zVal = (const char *)sqlite3_value_text(pVal);
125976 int nVal = sqlite3_value_bytes(pVal);
125978 if( !zVal ){
125979 return SQLITE_NOMEM;
125980 }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
125981 rc = fts3DoOptimize(p, 0);
125982 }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
125983 rc = fts3DoRebuild(p);
125984 #ifdef SQLITE_TEST
125985 }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
125986 p->nNodeSize = atoi(&zVal[9]);
125987 rc = SQLITE_OK;
125988 }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
125989 p->nMaxPendingData = atoi(&zVal[11]);
125990 rc = SQLITE_OK;
125991 #endif
125992 }else{
125993 rc = SQLITE_ERROR;
125996 return rc;
126000 ** Delete all cached deferred doclists. Deferred doclists are cached
126001 ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
126003 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
126004 Fts3DeferredToken *pDef;
126005 for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
126006 fts3PendingListDelete(pDef->pList);
126007 pDef->pList = 0;
126012 ** Free all entries in the pCsr->pDeffered list. Entries are added to
126013 ** this list using sqlite3Fts3DeferToken().
126015 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
126016 Fts3DeferredToken *pDef;
126017 Fts3DeferredToken *pNext;
126018 for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
126019 pNext = pDef->pNext;
126020 fts3PendingListDelete(pDef->pList);
126021 sqlite3_free(pDef);
126023 pCsr->pDeferred = 0;
126027 ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
126028 ** based on the row that pCsr currently points to.
126030 ** A deferred-doclist is like any other doclist with position information
126031 ** included, except that it only contains entries for a single row of the
126032 ** table, not for all rows.
126034 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
126035 int rc = SQLITE_OK; /* Return code */
126036 if( pCsr->pDeferred ){
126037 int i; /* Used to iterate through table columns */
126038 sqlite3_int64 iDocid; /* Docid of the row pCsr points to */
126039 Fts3DeferredToken *pDef; /* Used to iterate through deferred tokens */
126041 Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
126042 sqlite3_tokenizer *pT = p->pTokenizer;
126043 sqlite3_tokenizer_module const *pModule = pT->pModule;
126045 assert( pCsr->isRequireSeek==0 );
126046 iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
126048 for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
126049 const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
126050 sqlite3_tokenizer_cursor *pTC = 0;
126052 rc = pModule->xOpen(pT, zText, -1, &pTC);
126053 while( rc==SQLITE_OK ){
126054 char const *zToken; /* Buffer containing token */
126055 int nToken; /* Number of bytes in token */
126056 int iDum1, iDum2; /* Dummy variables */
126057 int iPos; /* Position of token in zText */
126059 pTC->pTokenizer = pT;
126060 rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
126061 for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
126062 Fts3PhraseToken *pPT = pDef->pToken;
126063 if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
126064 && (pPT->bFirst==0 || iPos==0)
126065 && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
126066 && (0==memcmp(zToken, pPT->z, pPT->n))
126068 fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
126072 if( pTC ) pModule->xClose(pTC);
126073 if( rc==SQLITE_DONE ) rc = SQLITE_OK;
126076 for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
126077 if( pDef->pList ){
126078 rc = fts3PendingListAppendVarint(&pDef->pList, 0);
126083 return rc;
126086 SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
126087 Fts3DeferredToken *p,
126088 char **ppData,
126089 int *pnData
126091 char *pRet;
126092 int nSkip;
126093 sqlite3_int64 dummy;
126095 *ppData = 0;
126096 *pnData = 0;
126098 if( p->pList==0 ){
126099 return SQLITE_OK;
126102 pRet = (char *)sqlite3_malloc(p->pList->nData);
126103 if( !pRet ) return SQLITE_NOMEM;
126105 nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
126106 *pnData = p->pList->nData - nSkip;
126107 *ppData = pRet;
126109 memcpy(pRet, &p->pList->aData[nSkip], *pnData);
126110 return SQLITE_OK;
126114 ** Add an entry for token pToken to the pCsr->pDeferred list.
126116 SQLITE_PRIVATE int sqlite3Fts3DeferToken(
126117 Fts3Cursor *pCsr, /* Fts3 table cursor */
126118 Fts3PhraseToken *pToken, /* Token to defer */
126119 int iCol /* Column that token must appear in (or -1) */
126121 Fts3DeferredToken *pDeferred;
126122 pDeferred = sqlite3_malloc(sizeof(*pDeferred));
126123 if( !pDeferred ){
126124 return SQLITE_NOMEM;
126126 memset(pDeferred, 0, sizeof(*pDeferred));
126127 pDeferred->pToken = pToken;
126128 pDeferred->pNext = pCsr->pDeferred;
126129 pDeferred->iCol = iCol;
126130 pCsr->pDeferred = pDeferred;
126132 assert( pToken->pDeferred==0 );
126133 pToken->pDeferred = pDeferred;
126135 return SQLITE_OK;
126139 ** SQLite value pRowid contains the rowid of a row that may or may not be
126140 ** present in the FTS3 table. If it is, delete it and adjust the contents
126141 ** of subsiduary data structures accordingly.
126143 static int fts3DeleteByRowid(
126144 Fts3Table *p,
126145 sqlite3_value *pRowid,
126146 int *pnDoc,
126147 u32 *aSzDel
126149 int isEmpty = 0;
126150 int rc = fts3IsEmpty(p, pRowid, &isEmpty);
126151 if( rc==SQLITE_OK ){
126152 if( isEmpty ){
126153 /* Deleting this row means the whole table is empty. In this case
126154 ** delete the contents of all three tables and throw away any
126155 ** data in the pendingTerms hash table. */
126156 rc = fts3DeleteAll(p, 1);
126157 *pnDoc = *pnDoc - 1;
126158 }else{
126159 sqlite3_int64 iRemove = sqlite3_value_int64(pRowid);
126160 rc = fts3PendingTermsDocid(p, iRemove);
126161 fts3DeleteTerms(&rc, p, pRowid, aSzDel);
126162 if( p->zContentTbl==0 ){
126163 fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
126164 if( sqlite3_changes(p->db) ) *pnDoc = *pnDoc - 1;
126165 }else{
126166 *pnDoc = *pnDoc - 1;
126168 if( p->bHasDocsize ){
126169 fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
126174 return rc;
126178 ** This function does the work for the xUpdate method of FTS3 virtual
126179 ** tables.
126181 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
126182 sqlite3_vtab *pVtab, /* FTS3 vtab object */
126183 int nArg, /* Size of argument array */
126184 sqlite3_value **apVal, /* Array of arguments */
126185 sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
126187 Fts3Table *p = (Fts3Table *)pVtab;
126188 int rc = SQLITE_OK; /* Return Code */
126189 int isRemove = 0; /* True for an UPDATE or DELETE */
126190 u32 *aSzIns = 0; /* Sizes of inserted documents */
126191 u32 *aSzDel; /* Sizes of deleted documents */
126192 int nChng = 0; /* Net change in number of documents */
126193 int bInsertDone = 0;
126195 assert( p->pSegments==0 );
126197 /* Check for a "special" INSERT operation. One of the form:
126199 ** INSERT INTO xyz(xyz) VALUES('command');
126201 if( nArg>1
126202 && sqlite3_value_type(apVal[0])==SQLITE_NULL
126203 && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL
126205 rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
126206 goto update_out;
126209 /* Allocate space to hold the change in document sizes */
126210 aSzIns = sqlite3_malloc( sizeof(aSzIns[0])*(p->nColumn+1)*2 );
126211 if( aSzIns==0 ){
126212 rc = SQLITE_NOMEM;
126213 goto update_out;
126215 aSzDel = &aSzIns[p->nColumn+1];
126216 memset(aSzIns, 0, sizeof(aSzIns[0])*(p->nColumn+1)*2);
126218 /* If this is an INSERT operation, or an UPDATE that modifies the rowid
126219 ** value, then this operation requires constraint handling.
126221 ** If the on-conflict mode is REPLACE, this means that the existing row
126222 ** should be deleted from the database before inserting the new row. Or,
126223 ** if the on-conflict mode is other than REPLACE, then this method must
126224 ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
126225 ** modify the database file.
126227 if( nArg>1 && p->zContentTbl==0 ){
126228 /* Find the value object that holds the new rowid value. */
126229 sqlite3_value *pNewRowid = apVal[3+p->nColumn];
126230 if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
126231 pNewRowid = apVal[1];
126234 if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && (
126235 sqlite3_value_type(apVal[0])==SQLITE_NULL
126236 || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
126238 /* The new rowid is not NULL (in this case the rowid will be
126239 ** automatically assigned and there is no chance of a conflict), and
126240 ** the statement is either an INSERT or an UPDATE that modifies the
126241 ** rowid column. So if the conflict mode is REPLACE, then delete any
126242 ** existing row with rowid=pNewRowid.
126244 ** Or, if the conflict mode is not REPLACE, insert the new record into
126245 ** the %_content table. If we hit the duplicate rowid constraint (or any
126246 ** other error) while doing so, return immediately.
126248 ** This branch may also run if pNewRowid contains a value that cannot
126249 ** be losslessly converted to an integer. In this case, the eventual
126250 ** call to fts3InsertData() (either just below or further on in this
126251 ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is
126252 ** invoked, it will delete zero rows (since no row will have
126253 ** docid=$pNewRowid if $pNewRowid is not an integer value).
126255 if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
126256 rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
126257 }else{
126258 rc = fts3InsertData(p, apVal, pRowid);
126259 bInsertDone = 1;
126263 if( rc!=SQLITE_OK ){
126264 goto update_out;
126267 /* If this is a DELETE or UPDATE operation, remove the old record. */
126268 if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
126269 assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
126270 rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
126271 isRemove = 1;
126274 /* If this is an INSERT or UPDATE operation, insert the new record. */
126275 if( nArg>1 && rc==SQLITE_OK ){
126276 if( bInsertDone==0 ){
126277 rc = fts3InsertData(p, apVal, pRowid);
126278 if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
126279 rc = FTS_CORRUPT_VTAB;
126282 if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){
126283 rc = fts3PendingTermsDocid(p, *pRowid);
126285 if( rc==SQLITE_OK ){
126286 assert( p->iPrevDocid==*pRowid );
126287 rc = fts3InsertTerms(p, apVal, aSzIns);
126289 if( p->bHasDocsize ){
126290 fts3InsertDocsize(&rc, p, aSzIns);
126292 nChng++;
126295 if( p->bHasStat ){
126296 fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
126299 update_out:
126300 sqlite3_free(aSzIns);
126301 sqlite3Fts3SegmentsClose(p);
126302 return rc;
126306 ** Flush any data in the pending-terms hash table to disk. If successful,
126307 ** merge all segments in the database (including the new segment, if
126308 ** there was any data to flush) into a single segment.
126310 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
126311 int rc;
126312 rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
126313 if( rc==SQLITE_OK ){
126314 rc = fts3DoOptimize(p, 1);
126315 if( rc==SQLITE_OK || rc==SQLITE_DONE ){
126316 int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
126317 if( rc2!=SQLITE_OK ) rc = rc2;
126318 }else{
126319 sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
126320 sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
126323 sqlite3Fts3SegmentsClose(p);
126324 return rc;
126327 #endif
126329 /************** End of fts3_write.c ******************************************/
126330 /************** Begin file fts3_snippet.c ************************************/
126332 ** 2009 Oct 23
126334 ** The author disclaims copyright to this source code. In place of
126335 ** a legal notice, here is a blessing:
126337 ** May you do good and not evil.
126338 ** May you find forgiveness for yourself and forgive others.
126339 ** May you share freely, never taking more than you give.
126341 ******************************************************************************
126344 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
126346 /* #include <string.h> */
126347 /* #include <assert.h> */
126350 ** Characters that may appear in the second argument to matchinfo().
126352 #define FTS3_MATCHINFO_NPHRASE 'p' /* 1 value */
126353 #define FTS3_MATCHINFO_NCOL 'c' /* 1 value */
126354 #define FTS3_MATCHINFO_NDOC 'n' /* 1 value */
126355 #define FTS3_MATCHINFO_AVGLENGTH 'a' /* nCol values */
126356 #define FTS3_MATCHINFO_LENGTH 'l' /* nCol values */
126357 #define FTS3_MATCHINFO_LCS 's' /* nCol values */
126358 #define FTS3_MATCHINFO_HITS 'x' /* 3*nCol*nPhrase values */
126361 ** The default value for the second argument to matchinfo().
126363 #define FTS3_MATCHINFO_DEFAULT "pcx"
126367 ** Used as an fts3ExprIterate() context when loading phrase doclists to
126368 ** Fts3Expr.aDoclist[]/nDoclist.
126370 typedef struct LoadDoclistCtx LoadDoclistCtx;
126371 struct LoadDoclistCtx {
126372 Fts3Cursor *pCsr; /* FTS3 Cursor */
126373 int nPhrase; /* Number of phrases seen so far */
126374 int nToken; /* Number of tokens seen so far */
126378 ** The following types are used as part of the implementation of the
126379 ** fts3BestSnippet() routine.
126381 typedef struct SnippetIter SnippetIter;
126382 typedef struct SnippetPhrase SnippetPhrase;
126383 typedef struct SnippetFragment SnippetFragment;
126385 struct SnippetIter {
126386 Fts3Cursor *pCsr; /* Cursor snippet is being generated from */
126387 int iCol; /* Extract snippet from this column */
126388 int nSnippet; /* Requested snippet length (in tokens) */
126389 int nPhrase; /* Number of phrases in query */
126390 SnippetPhrase *aPhrase; /* Array of size nPhrase */
126391 int iCurrent; /* First token of current snippet */
126394 struct SnippetPhrase {
126395 int nToken; /* Number of tokens in phrase */
126396 char *pList; /* Pointer to start of phrase position list */
126397 int iHead; /* Next value in position list */
126398 char *pHead; /* Position list data following iHead */
126399 int iTail; /* Next value in trailing position list */
126400 char *pTail; /* Position list data following iTail */
126403 struct SnippetFragment {
126404 int iCol; /* Column snippet is extracted from */
126405 int iPos; /* Index of first token in snippet */
126406 u64 covered; /* Mask of query phrases covered */
126407 u64 hlmask; /* Mask of snippet terms to highlight */
126411 ** This type is used as an fts3ExprIterate() context object while
126412 ** accumulating the data returned by the matchinfo() function.
126414 typedef struct MatchInfo MatchInfo;
126415 struct MatchInfo {
126416 Fts3Cursor *pCursor; /* FTS3 Cursor */
126417 int nCol; /* Number of columns in table */
126418 int nPhrase; /* Number of matchable phrases in query */
126419 sqlite3_int64 nDoc; /* Number of docs in database */
126420 u32 *aMatchinfo; /* Pre-allocated buffer */
126426 ** The snippet() and offsets() functions both return text values. An instance
126427 ** of the following structure is used to accumulate those values while the
126428 ** functions are running. See fts3StringAppend() for details.
126430 typedef struct StrBuffer StrBuffer;
126431 struct StrBuffer {
126432 char *z; /* Pointer to buffer containing string */
126433 int n; /* Length of z in bytes (excl. nul-term) */
126434 int nAlloc; /* Allocated size of buffer z in bytes */
126439 ** This function is used to help iterate through a position-list. A position
126440 ** list is a list of unique integers, sorted from smallest to largest. Each
126441 ** element of the list is represented by an FTS3 varint that takes the value
126442 ** of the difference between the current element and the previous one plus
126443 ** two. For example, to store the position-list:
126445 ** 4 9 113
126447 ** the three varints:
126449 ** 6 7 106
126451 ** are encoded.
126453 ** When this function is called, *pp points to the start of an element of
126454 ** the list. *piPos contains the value of the previous entry in the list.
126455 ** After it returns, *piPos contains the value of the next element of the
126456 ** list and *pp is advanced to the following varint.
126458 static void fts3GetDeltaPosition(char **pp, int *piPos){
126459 int iVal;
126460 *pp += sqlite3Fts3GetVarint32(*pp, &iVal);
126461 *piPos += (iVal-2);
126465 ** Helper function for fts3ExprIterate() (see below).
126467 static int fts3ExprIterate2(
126468 Fts3Expr *pExpr, /* Expression to iterate phrases of */
126469 int *piPhrase, /* Pointer to phrase counter */
126470 int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
126471 void *pCtx /* Second argument to pass to callback */
126473 int rc; /* Return code */
126474 int eType = pExpr->eType; /* Type of expression node pExpr */
126476 if( eType!=FTSQUERY_PHRASE ){
126477 assert( pExpr->pLeft && pExpr->pRight );
126478 rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
126479 if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
126480 rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
126482 }else{
126483 rc = x(pExpr, *piPhrase, pCtx);
126484 (*piPhrase)++;
126486 return rc;
126490 ** Iterate through all phrase nodes in an FTS3 query, except those that
126491 ** are part of a sub-tree that is the right-hand-side of a NOT operator.
126492 ** For each phrase node found, the supplied callback function is invoked.
126494 ** If the callback function returns anything other than SQLITE_OK,
126495 ** the iteration is abandoned and the error code returned immediately.
126496 ** Otherwise, SQLITE_OK is returned after a callback has been made for
126497 ** all eligible phrase nodes.
126499 static int fts3ExprIterate(
126500 Fts3Expr *pExpr, /* Expression to iterate phrases of */
126501 int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
126502 void *pCtx /* Second argument to pass to callback */
126504 int iPhrase = 0; /* Variable used as the phrase counter */
126505 return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
126509 ** This is an fts3ExprIterate() callback used while loading the doclists
126510 ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
126511 ** fts3ExprLoadDoclists().
126513 static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
126514 int rc = SQLITE_OK;
126515 Fts3Phrase *pPhrase = pExpr->pPhrase;
126516 LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
126518 UNUSED_PARAMETER(iPhrase);
126520 p->nPhrase++;
126521 p->nToken += pPhrase->nToken;
126523 return rc;
126527 ** Load the doclists for each phrase in the query associated with FTS3 cursor
126528 ** pCsr.
126530 ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
126531 ** phrases in the expression (all phrases except those directly or
126532 ** indirectly descended from the right-hand-side of a NOT operator). If
126533 ** pnToken is not NULL, then it is set to the number of tokens in all
126534 ** matchable phrases of the expression.
126536 static int fts3ExprLoadDoclists(
126537 Fts3Cursor *pCsr, /* Fts3 cursor for current query */
126538 int *pnPhrase, /* OUT: Number of phrases in query */
126539 int *pnToken /* OUT: Number of tokens in query */
126541 int rc; /* Return Code */
126542 LoadDoclistCtx sCtx = {0,0,0}; /* Context for fts3ExprIterate() */
126543 sCtx.pCsr = pCsr;
126544 rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
126545 if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
126546 if( pnToken ) *pnToken = sCtx.nToken;
126547 return rc;
126550 static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
126551 (*(int *)ctx)++;
126552 UNUSED_PARAMETER(pExpr);
126553 UNUSED_PARAMETER(iPhrase);
126554 return SQLITE_OK;
126556 static int fts3ExprPhraseCount(Fts3Expr *pExpr){
126557 int nPhrase = 0;
126558 (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
126559 return nPhrase;
126563 ** Advance the position list iterator specified by the first two
126564 ** arguments so that it points to the first element with a value greater
126565 ** than or equal to parameter iNext.
126567 static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
126568 char *pIter = *ppIter;
126569 if( pIter ){
126570 int iIter = *piIter;
126572 while( iIter<iNext ){
126573 if( 0==(*pIter & 0xFE) ){
126574 iIter = -1;
126575 pIter = 0;
126576 break;
126578 fts3GetDeltaPosition(&pIter, &iIter);
126581 *piIter = iIter;
126582 *ppIter = pIter;
126587 ** Advance the snippet iterator to the next candidate snippet.
126589 static int fts3SnippetNextCandidate(SnippetIter *pIter){
126590 int i; /* Loop counter */
126592 if( pIter->iCurrent<0 ){
126593 /* The SnippetIter object has just been initialized. The first snippet
126594 ** candidate always starts at offset 0 (even if this candidate has a
126595 ** score of 0.0).
126597 pIter->iCurrent = 0;
126599 /* Advance the 'head' iterator of each phrase to the first offset that
126600 ** is greater than or equal to (iNext+nSnippet).
126602 for(i=0; i<pIter->nPhrase; i++){
126603 SnippetPhrase *pPhrase = &pIter->aPhrase[i];
126604 fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
126606 }else{
126607 int iStart;
126608 int iEnd = 0x7FFFFFFF;
126610 for(i=0; i<pIter->nPhrase; i++){
126611 SnippetPhrase *pPhrase = &pIter->aPhrase[i];
126612 if( pPhrase->pHead && pPhrase->iHead<iEnd ){
126613 iEnd = pPhrase->iHead;
126616 if( iEnd==0x7FFFFFFF ){
126617 return 1;
126620 pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
126621 for(i=0; i<pIter->nPhrase; i++){
126622 SnippetPhrase *pPhrase = &pIter->aPhrase[i];
126623 fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
126624 fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
126628 return 0;
126632 ** Retrieve information about the current candidate snippet of snippet
126633 ** iterator pIter.
126635 static void fts3SnippetDetails(
126636 SnippetIter *pIter, /* Snippet iterator */
126637 u64 mCovered, /* Bitmask of phrases already covered */
126638 int *piToken, /* OUT: First token of proposed snippet */
126639 int *piScore, /* OUT: "Score" for this snippet */
126640 u64 *pmCover, /* OUT: Bitmask of phrases covered */
126641 u64 *pmHighlight /* OUT: Bitmask of terms to highlight */
126643 int iStart = pIter->iCurrent; /* First token of snippet */
126644 int iScore = 0; /* Score of this snippet */
126645 int i; /* Loop counter */
126646 u64 mCover = 0; /* Mask of phrases covered by this snippet */
126647 u64 mHighlight = 0; /* Mask of tokens to highlight in snippet */
126649 for(i=0; i<pIter->nPhrase; i++){
126650 SnippetPhrase *pPhrase = &pIter->aPhrase[i];
126651 if( pPhrase->pTail ){
126652 char *pCsr = pPhrase->pTail;
126653 int iCsr = pPhrase->iTail;
126655 while( iCsr<(iStart+pIter->nSnippet) ){
126656 int j;
126657 u64 mPhrase = (u64)1 << i;
126658 u64 mPos = (u64)1 << (iCsr - iStart);
126659 assert( iCsr>=iStart );
126660 if( (mCover|mCovered)&mPhrase ){
126661 iScore++;
126662 }else{
126663 iScore += 1000;
126665 mCover |= mPhrase;
126667 for(j=0; j<pPhrase->nToken; j++){
126668 mHighlight |= (mPos>>j);
126671 if( 0==(*pCsr & 0x0FE) ) break;
126672 fts3GetDeltaPosition(&pCsr, &iCsr);
126677 /* Set the output variables before returning. */
126678 *piToken = iStart;
126679 *piScore = iScore;
126680 *pmCover = mCover;
126681 *pmHighlight = mHighlight;
126685 ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
126686 ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
126688 static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
126689 SnippetIter *p = (SnippetIter *)ctx;
126690 SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
126691 char *pCsr;
126693 pPhrase->nToken = pExpr->pPhrase->nToken;
126695 pCsr = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol);
126696 if( pCsr ){
126697 int iFirst = 0;
126698 pPhrase->pList = pCsr;
126699 fts3GetDeltaPosition(&pCsr, &iFirst);
126700 assert( iFirst>=0 );
126701 pPhrase->pHead = pCsr;
126702 pPhrase->pTail = pCsr;
126703 pPhrase->iHead = iFirst;
126704 pPhrase->iTail = iFirst;
126705 }else{
126706 assert( pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0 );
126709 return SQLITE_OK;
126713 ** Select the fragment of text consisting of nFragment contiguous tokens
126714 ** from column iCol that represent the "best" snippet. The best snippet
126715 ** is the snippet with the highest score, where scores are calculated
126716 ** by adding:
126718 ** (a) +1 point for each occurence of a matchable phrase in the snippet.
126720 ** (b) +1000 points for the first occurence of each matchable phrase in
126721 ** the snippet for which the corresponding mCovered bit is not set.
126723 ** The selected snippet parameters are stored in structure *pFragment before
126724 ** returning. The score of the selected snippet is stored in *piScore
126725 ** before returning.
126727 static int fts3BestSnippet(
126728 int nSnippet, /* Desired snippet length */
126729 Fts3Cursor *pCsr, /* Cursor to create snippet for */
126730 int iCol, /* Index of column to create snippet from */
126731 u64 mCovered, /* Mask of phrases already covered */
126732 u64 *pmSeen, /* IN/OUT: Mask of phrases seen */
126733 SnippetFragment *pFragment, /* OUT: Best snippet found */
126734 int *piScore /* OUT: Score of snippet pFragment */
126736 int rc; /* Return Code */
126737 int nList; /* Number of phrases in expression */
126738 SnippetIter sIter; /* Iterates through snippet candidates */
126739 int nByte; /* Number of bytes of space to allocate */
126740 int iBestScore = -1; /* Best snippet score found so far */
126741 int i; /* Loop counter */
126743 memset(&sIter, 0, sizeof(sIter));
126745 /* Iterate through the phrases in the expression to count them. The same
126746 ** callback makes sure the doclists are loaded for each phrase.
126748 rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
126749 if( rc!=SQLITE_OK ){
126750 return rc;
126753 /* Now that it is known how many phrases there are, allocate and zero
126754 ** the required space using malloc().
126756 nByte = sizeof(SnippetPhrase) * nList;
126757 sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
126758 if( !sIter.aPhrase ){
126759 return SQLITE_NOMEM;
126761 memset(sIter.aPhrase, 0, nByte);
126763 /* Initialize the contents of the SnippetIter object. Then iterate through
126764 ** the set of phrases in the expression to populate the aPhrase[] array.
126766 sIter.pCsr = pCsr;
126767 sIter.iCol = iCol;
126768 sIter.nSnippet = nSnippet;
126769 sIter.nPhrase = nList;
126770 sIter.iCurrent = -1;
126771 (void)fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sIter);
126773 /* Set the *pmSeen output variable. */
126774 for(i=0; i<nList; i++){
126775 if( sIter.aPhrase[i].pHead ){
126776 *pmSeen |= (u64)1 << i;
126780 /* Loop through all candidate snippets. Store the best snippet in
126781 ** *pFragment. Store its associated 'score' in iBestScore.
126783 pFragment->iCol = iCol;
126784 while( !fts3SnippetNextCandidate(&sIter) ){
126785 int iPos;
126786 int iScore;
126787 u64 mCover;
126788 u64 mHighlight;
126789 fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover, &mHighlight);
126790 assert( iScore>=0 );
126791 if( iScore>iBestScore ){
126792 pFragment->iPos = iPos;
126793 pFragment->hlmask = mHighlight;
126794 pFragment->covered = mCover;
126795 iBestScore = iScore;
126799 sqlite3_free(sIter.aPhrase);
126800 *piScore = iBestScore;
126801 return SQLITE_OK;
126806 ** Append a string to the string-buffer passed as the first argument.
126808 ** If nAppend is negative, then the length of the string zAppend is
126809 ** determined using strlen().
126811 static int fts3StringAppend(
126812 StrBuffer *pStr, /* Buffer to append to */
126813 const char *zAppend, /* Pointer to data to append to buffer */
126814 int nAppend /* Size of zAppend in bytes (or -1) */
126816 if( nAppend<0 ){
126817 nAppend = (int)strlen(zAppend);
126820 /* If there is insufficient space allocated at StrBuffer.z, use realloc()
126821 ** to grow the buffer until so that it is big enough to accomadate the
126822 ** appended data.
126824 if( pStr->n+nAppend+1>=pStr->nAlloc ){
126825 int nAlloc = pStr->nAlloc+nAppend+100;
126826 char *zNew = sqlite3_realloc(pStr->z, nAlloc);
126827 if( !zNew ){
126828 return SQLITE_NOMEM;
126830 pStr->z = zNew;
126831 pStr->nAlloc = nAlloc;
126834 /* Append the data to the string buffer. */
126835 memcpy(&pStr->z[pStr->n], zAppend, nAppend);
126836 pStr->n += nAppend;
126837 pStr->z[pStr->n] = '\0';
126839 return SQLITE_OK;
126843 ** The fts3BestSnippet() function often selects snippets that end with a
126844 ** query term. That is, the final term of the snippet is always a term
126845 ** that requires highlighting. For example, if 'X' is a highlighted term
126846 ** and '.' is a non-highlighted term, BestSnippet() may select:
126848 ** ........X.....X
126850 ** This function "shifts" the beginning of the snippet forward in the
126851 ** document so that there are approximately the same number of
126852 ** non-highlighted terms to the right of the final highlighted term as there
126853 ** are to the left of the first highlighted term. For example, to this:
126855 ** ....X.....X....
126857 ** This is done as part of extracting the snippet text, not when selecting
126858 ** the snippet. Snippet selection is done based on doclists only, so there
126859 ** is no way for fts3BestSnippet() to know whether or not the document
126860 ** actually contains terms that follow the final highlighted term.
126862 static int fts3SnippetShift(
126863 Fts3Table *pTab, /* FTS3 table snippet comes from */
126864 int nSnippet, /* Number of tokens desired for snippet */
126865 const char *zDoc, /* Document text to extract snippet from */
126866 int nDoc, /* Size of buffer zDoc in bytes */
126867 int *piPos, /* IN/OUT: First token of snippet */
126868 u64 *pHlmask /* IN/OUT: Mask of tokens to highlight */
126870 u64 hlmask = *pHlmask; /* Local copy of initial highlight-mask */
126872 if( hlmask ){
126873 int nLeft; /* Tokens to the left of first highlight */
126874 int nRight; /* Tokens to the right of last highlight */
126875 int nDesired; /* Ideal number of tokens to shift forward */
126877 for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
126878 for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
126879 nDesired = (nLeft-nRight)/2;
126881 /* Ideally, the start of the snippet should be pushed forward in the
126882 ** document nDesired tokens. This block checks if there are actually
126883 ** nDesired tokens to the right of the snippet. If so, *piPos and
126884 ** *pHlMask are updated to shift the snippet nDesired tokens to the
126885 ** right. Otherwise, the snippet is shifted by the number of tokens
126886 ** available.
126888 if( nDesired>0 ){
126889 int nShift; /* Number of tokens to shift snippet by */
126890 int iCurrent = 0; /* Token counter */
126891 int rc; /* Return Code */
126892 sqlite3_tokenizer_module *pMod;
126893 sqlite3_tokenizer_cursor *pC;
126894 pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
126896 /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
126897 ** or more tokens in zDoc/nDoc.
126899 rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
126900 if( rc!=SQLITE_OK ){
126901 return rc;
126903 pC->pTokenizer = pTab->pTokenizer;
126904 while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
126905 const char *ZDUMMY; int DUMMY1, DUMMY2, DUMMY3;
126906 rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
126908 pMod->xClose(pC);
126909 if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
126911 nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
126912 assert( nShift<=nDesired );
126913 if( nShift>0 ){
126914 *piPos += nShift;
126915 *pHlmask = hlmask >> nShift;
126919 return SQLITE_OK;
126923 ** Extract the snippet text for fragment pFragment from cursor pCsr and
126924 ** append it to string buffer pOut.
126926 static int fts3SnippetText(
126927 Fts3Cursor *pCsr, /* FTS3 Cursor */
126928 SnippetFragment *pFragment, /* Snippet to extract */
126929 int iFragment, /* Fragment number */
126930 int isLast, /* True for final fragment in snippet */
126931 int nSnippet, /* Number of tokens in extracted snippet */
126932 const char *zOpen, /* String inserted before highlighted term */
126933 const char *zClose, /* String inserted after highlighted term */
126934 const char *zEllipsis, /* String inserted between snippets */
126935 StrBuffer *pOut /* Write output here */
126937 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
126938 int rc; /* Return code */
126939 const char *zDoc; /* Document text to extract snippet from */
126940 int nDoc; /* Size of zDoc in bytes */
126941 int iCurrent = 0; /* Current token number of document */
126942 int iEnd = 0; /* Byte offset of end of current token */
126943 int isShiftDone = 0; /* True after snippet is shifted */
126944 int iPos = pFragment->iPos; /* First token of snippet */
126945 u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
126946 int iCol = pFragment->iCol+1; /* Query column to extract text from */
126947 sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
126948 sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor open on zDoc/nDoc */
126949 const char *ZDUMMY; /* Dummy argument used with tokenizer */
126950 int DUMMY1; /* Dummy argument used with tokenizer */
126952 zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
126953 if( zDoc==0 ){
126954 if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
126955 return SQLITE_NOMEM;
126957 return SQLITE_OK;
126959 nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
126961 /* Open a token cursor on the document. */
126962 pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
126963 rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
126964 if( rc!=SQLITE_OK ){
126965 return rc;
126967 pC->pTokenizer = pTab->pTokenizer;
126969 while( rc==SQLITE_OK ){
126970 int iBegin; /* Offset in zDoc of start of token */
126971 int iFin; /* Offset in zDoc of end of token */
126972 int isHighlight; /* True for highlighted terms */
126974 rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
126975 if( rc!=SQLITE_OK ){
126976 if( rc==SQLITE_DONE ){
126977 /* Special case - the last token of the snippet is also the last token
126978 ** of the column. Append any punctuation that occurred between the end
126979 ** of the previous token and the end of the document to the output.
126980 ** Then break out of the loop. */
126981 rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
126983 break;
126985 if( iCurrent<iPos ){ continue; }
126987 if( !isShiftDone ){
126988 int n = nDoc - iBegin;
126989 rc = fts3SnippetShift(pTab, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask);
126990 isShiftDone = 1;
126992 /* Now that the shift has been done, check if the initial "..." are
126993 ** required. They are required if (a) this is not the first fragment,
126994 ** or (b) this fragment does not begin at position 0 of its column.
126996 if( rc==SQLITE_OK && (iPos>0 || iFragment>0) ){
126997 rc = fts3StringAppend(pOut, zEllipsis, -1);
126999 if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
127002 if( iCurrent>=(iPos+nSnippet) ){
127003 if( isLast ){
127004 rc = fts3StringAppend(pOut, zEllipsis, -1);
127006 break;
127009 /* Set isHighlight to true if this term should be highlighted. */
127010 isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
127012 if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
127013 if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
127014 if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
127015 if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
127017 iEnd = iFin;
127020 pMod->xClose(pC);
127021 return rc;
127026 ** This function is used to count the entries in a column-list (a
127027 ** delta-encoded list of term offsets within a single column of a single
127028 ** row). When this function is called, *ppCollist should point to the
127029 ** beginning of the first varint in the column-list (the varint that
127030 ** contains the position of the first matching term in the column data).
127031 ** Before returning, *ppCollist is set to point to the first byte after
127032 ** the last varint in the column-list (either the 0x00 signifying the end
127033 ** of the position-list, or the 0x01 that precedes the column number of
127034 ** the next column in the position-list).
127036 ** The number of elements in the column-list is returned.
127038 static int fts3ColumnlistCount(char **ppCollist){
127039 char *pEnd = *ppCollist;
127040 char c = 0;
127041 int nEntry = 0;
127043 /* A column-list is terminated by either a 0x01 or 0x00. */
127044 while( 0xFE & (*pEnd | c) ){
127045 c = *pEnd++ & 0x80;
127046 if( !c ) nEntry++;
127049 *ppCollist = pEnd;
127050 return nEntry;
127054 ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
127055 ** for a single query.
127057 ** fts3ExprIterate() callback to load the 'global' elements of a
127058 ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
127059 ** of the matchinfo array that are constant for all rows returned by the
127060 ** current query.
127062 ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
127063 ** function populates Matchinfo.aMatchinfo[] as follows:
127065 ** for(iCol=0; iCol<nCol; iCol++){
127066 ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
127067 ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
127070 ** where X is the number of matches for phrase iPhrase is column iCol of all
127071 ** rows of the table. Y is the number of rows for which column iCol contains
127072 ** at least one instance of phrase iPhrase.
127074 ** If the phrase pExpr consists entirely of deferred tokens, then all X and
127075 ** Y values are set to nDoc, where nDoc is the number of documents in the
127076 ** file system. This is done because the full-text index doclist is required
127077 ** to calculate these values properly, and the full-text index doclist is
127078 ** not available for deferred tokens.
127080 static int fts3ExprGlobalHitsCb(
127081 Fts3Expr *pExpr, /* Phrase expression node */
127082 int iPhrase, /* Phrase number (numbered from zero) */
127083 void *pCtx /* Pointer to MatchInfo structure */
127085 MatchInfo *p = (MatchInfo *)pCtx;
127086 return sqlite3Fts3EvalPhraseStats(
127087 p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
127092 ** fts3ExprIterate() callback used to collect the "local" part of the
127093 ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
127094 ** array that are different for each row returned by the query.
127096 static int fts3ExprLocalHitsCb(
127097 Fts3Expr *pExpr, /* Phrase expression node */
127098 int iPhrase, /* Phrase number */
127099 void *pCtx /* Pointer to MatchInfo structure */
127101 MatchInfo *p = (MatchInfo *)pCtx;
127102 int iStart = iPhrase * p->nCol * 3;
127103 int i;
127105 for(i=0; i<p->nCol; i++){
127106 char *pCsr;
127107 pCsr = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i);
127108 if( pCsr ){
127109 p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
127110 }else{
127111 p->aMatchinfo[iStart+i*3] = 0;
127115 return SQLITE_OK;
127118 static int fts3MatchinfoCheck(
127119 Fts3Table *pTab,
127120 char cArg,
127121 char **pzErr
127123 if( (cArg==FTS3_MATCHINFO_NPHRASE)
127124 || (cArg==FTS3_MATCHINFO_NCOL)
127125 || (cArg==FTS3_MATCHINFO_NDOC && pTab->bHasStat)
127126 || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bHasStat)
127127 || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
127128 || (cArg==FTS3_MATCHINFO_LCS)
127129 || (cArg==FTS3_MATCHINFO_HITS)
127131 return SQLITE_OK;
127133 *pzErr = sqlite3_mprintf("unrecognized matchinfo request: %c", cArg);
127134 return SQLITE_ERROR;
127137 static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
127138 int nVal; /* Number of integers output by cArg */
127140 switch( cArg ){
127141 case FTS3_MATCHINFO_NDOC:
127142 case FTS3_MATCHINFO_NPHRASE:
127143 case FTS3_MATCHINFO_NCOL:
127144 nVal = 1;
127145 break;
127147 case FTS3_MATCHINFO_AVGLENGTH:
127148 case FTS3_MATCHINFO_LENGTH:
127149 case FTS3_MATCHINFO_LCS:
127150 nVal = pInfo->nCol;
127151 break;
127153 default:
127154 assert( cArg==FTS3_MATCHINFO_HITS );
127155 nVal = pInfo->nCol * pInfo->nPhrase * 3;
127156 break;
127159 return nVal;
127162 static int fts3MatchinfoSelectDoctotal(
127163 Fts3Table *pTab,
127164 sqlite3_stmt **ppStmt,
127165 sqlite3_int64 *pnDoc,
127166 const char **paLen
127168 sqlite3_stmt *pStmt;
127169 const char *a;
127170 sqlite3_int64 nDoc;
127172 if( !*ppStmt ){
127173 int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
127174 if( rc!=SQLITE_OK ) return rc;
127176 pStmt = *ppStmt;
127177 assert( sqlite3_data_count(pStmt)==1 );
127179 a = sqlite3_column_blob(pStmt, 0);
127180 a += sqlite3Fts3GetVarint(a, &nDoc);
127181 if( nDoc==0 ) return FTS_CORRUPT_VTAB;
127182 *pnDoc = (u32)nDoc;
127184 if( paLen ) *paLen = a;
127185 return SQLITE_OK;
127189 ** An instance of the following structure is used to store state while
127190 ** iterating through a multi-column position-list corresponding to the
127191 ** hits for a single phrase on a single row in order to calculate the
127192 ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
127194 typedef struct LcsIterator LcsIterator;
127195 struct LcsIterator {
127196 Fts3Expr *pExpr; /* Pointer to phrase expression */
127197 int iPosOffset; /* Tokens count up to end of this phrase */
127198 char *pRead; /* Cursor used to iterate through aDoclist */
127199 int iPos; /* Current position */
127203 ** If LcsIterator.iCol is set to the following value, the iterator has
127204 ** finished iterating through all offsets for all columns.
127206 #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
127208 static int fts3MatchinfoLcsCb(
127209 Fts3Expr *pExpr, /* Phrase expression node */
127210 int iPhrase, /* Phrase number (numbered from zero) */
127211 void *pCtx /* Pointer to MatchInfo structure */
127213 LcsIterator *aIter = (LcsIterator *)pCtx;
127214 aIter[iPhrase].pExpr = pExpr;
127215 return SQLITE_OK;
127219 ** Advance the iterator passed as an argument to the next position. Return
127220 ** 1 if the iterator is at EOF or if it now points to the start of the
127221 ** position list for the next column.
127223 static int fts3LcsIteratorAdvance(LcsIterator *pIter){
127224 char *pRead = pIter->pRead;
127225 sqlite3_int64 iRead;
127226 int rc = 0;
127228 pRead += sqlite3Fts3GetVarint(pRead, &iRead);
127229 if( iRead==0 || iRead==1 ){
127230 pRead = 0;
127231 rc = 1;
127232 }else{
127233 pIter->iPos += (int)(iRead-2);
127236 pIter->pRead = pRead;
127237 return rc;
127241 ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
127243 ** If the call is successful, the longest-common-substring lengths for each
127244 ** column are written into the first nCol elements of the pInfo->aMatchinfo[]
127245 ** array before returning. SQLITE_OK is returned in this case.
127247 ** Otherwise, if an error occurs, an SQLite error code is returned and the
127248 ** data written to the first nCol elements of pInfo->aMatchinfo[] is
127249 ** undefined.
127251 static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
127252 LcsIterator *aIter;
127253 int i;
127254 int iCol;
127255 int nToken = 0;
127257 /* Allocate and populate the array of LcsIterator objects. The array
127258 ** contains one element for each matchable phrase in the query.
127260 aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
127261 if( !aIter ) return SQLITE_NOMEM;
127262 memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
127263 (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
127265 for(i=0; i<pInfo->nPhrase; i++){
127266 LcsIterator *pIter = &aIter[i];
127267 nToken -= pIter->pExpr->pPhrase->nToken;
127268 pIter->iPosOffset = nToken;
127271 for(iCol=0; iCol<pInfo->nCol; iCol++){
127272 int nLcs = 0; /* LCS value for this column */
127273 int nLive = 0; /* Number of iterators in aIter not at EOF */
127275 for(i=0; i<pInfo->nPhrase; i++){
127276 LcsIterator *pIt = &aIter[i];
127277 pIt->pRead = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol);
127278 if( pIt->pRead ){
127279 pIt->iPos = pIt->iPosOffset;
127280 fts3LcsIteratorAdvance(&aIter[i]);
127281 nLive++;
127285 while( nLive>0 ){
127286 LcsIterator *pAdv = 0; /* The iterator to advance by one position */
127287 int nThisLcs = 0; /* LCS for the current iterator positions */
127289 for(i=0; i<pInfo->nPhrase; i++){
127290 LcsIterator *pIter = &aIter[i];
127291 if( pIter->pRead==0 ){
127292 /* This iterator is already at EOF for this column. */
127293 nThisLcs = 0;
127294 }else{
127295 if( pAdv==0 || pIter->iPos<pAdv->iPos ){
127296 pAdv = pIter;
127298 if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
127299 nThisLcs++;
127300 }else{
127301 nThisLcs = 1;
127303 if( nThisLcs>nLcs ) nLcs = nThisLcs;
127306 if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
127309 pInfo->aMatchinfo[iCol] = nLcs;
127312 sqlite3_free(aIter);
127313 return SQLITE_OK;
127317 ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
127318 ** be returned by the matchinfo() function. Argument zArg contains the
127319 ** format string passed as the second argument to matchinfo (or the
127320 ** default value "pcx" if no second argument was specified). The format
127321 ** string has already been validated and the pInfo->aMatchinfo[] array
127322 ** is guaranteed to be large enough for the output.
127324 ** If bGlobal is true, then populate all fields of the matchinfo() output.
127325 ** If it is false, then assume that those fields that do not change between
127326 ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
127327 ** have already been populated.
127329 ** Return SQLITE_OK if successful, or an SQLite error code if an error
127330 ** occurs. If a value other than SQLITE_OK is returned, the state the
127331 ** pInfo->aMatchinfo[] buffer is left in is undefined.
127333 static int fts3MatchinfoValues(
127334 Fts3Cursor *pCsr, /* FTS3 cursor object */
127335 int bGlobal, /* True to grab the global stats */
127336 MatchInfo *pInfo, /* Matchinfo context object */
127337 const char *zArg /* Matchinfo format string */
127339 int rc = SQLITE_OK;
127340 int i;
127341 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
127342 sqlite3_stmt *pSelect = 0;
127344 for(i=0; rc==SQLITE_OK && zArg[i]; i++){
127346 switch( zArg[i] ){
127347 case FTS3_MATCHINFO_NPHRASE:
127348 if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
127349 break;
127351 case FTS3_MATCHINFO_NCOL:
127352 if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
127353 break;
127355 case FTS3_MATCHINFO_NDOC:
127356 if( bGlobal ){
127357 sqlite3_int64 nDoc = 0;
127358 rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
127359 pInfo->aMatchinfo[0] = (u32)nDoc;
127361 break;
127363 case FTS3_MATCHINFO_AVGLENGTH:
127364 if( bGlobal ){
127365 sqlite3_int64 nDoc; /* Number of rows in table */
127366 const char *a; /* Aggregate column length array */
127368 rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
127369 if( rc==SQLITE_OK ){
127370 int iCol;
127371 for(iCol=0; iCol<pInfo->nCol; iCol++){
127372 u32 iVal;
127373 sqlite3_int64 nToken;
127374 a += sqlite3Fts3GetVarint(a, &nToken);
127375 iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
127376 pInfo->aMatchinfo[iCol] = iVal;
127380 break;
127382 case FTS3_MATCHINFO_LENGTH: {
127383 sqlite3_stmt *pSelectDocsize = 0;
127384 rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
127385 if( rc==SQLITE_OK ){
127386 int iCol;
127387 const char *a = sqlite3_column_blob(pSelectDocsize, 0);
127388 for(iCol=0; iCol<pInfo->nCol; iCol++){
127389 sqlite3_int64 nToken;
127390 a += sqlite3Fts3GetVarint(a, &nToken);
127391 pInfo->aMatchinfo[iCol] = (u32)nToken;
127394 sqlite3_reset(pSelectDocsize);
127395 break;
127398 case FTS3_MATCHINFO_LCS:
127399 rc = fts3ExprLoadDoclists(pCsr, 0, 0);
127400 if( rc==SQLITE_OK ){
127401 rc = fts3MatchinfoLcs(pCsr, pInfo);
127403 break;
127405 default: {
127406 Fts3Expr *pExpr;
127407 assert( zArg[i]==FTS3_MATCHINFO_HITS );
127408 pExpr = pCsr->pExpr;
127409 rc = fts3ExprLoadDoclists(pCsr, 0, 0);
127410 if( rc!=SQLITE_OK ) break;
127411 if( bGlobal ){
127412 if( pCsr->pDeferred ){
127413 rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
127414 if( rc!=SQLITE_OK ) break;
127416 rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
127417 if( rc!=SQLITE_OK ) break;
127419 (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
127420 break;
127424 pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
127427 sqlite3_reset(pSelect);
127428 return rc;
127433 ** Populate pCsr->aMatchinfo[] with data for the current row. The
127434 ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
127436 static int fts3GetMatchinfo(
127437 Fts3Cursor *pCsr, /* FTS3 Cursor object */
127438 const char *zArg /* Second argument to matchinfo() function */
127440 MatchInfo sInfo;
127441 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
127442 int rc = SQLITE_OK;
127443 int bGlobal = 0; /* Collect 'global' stats as well as local */
127445 memset(&sInfo, 0, sizeof(MatchInfo));
127446 sInfo.pCursor = pCsr;
127447 sInfo.nCol = pTab->nColumn;
127449 /* If there is cached matchinfo() data, but the format string for the
127450 ** cache does not match the format string for this request, discard
127451 ** the cached data. */
127452 if( pCsr->zMatchinfo && strcmp(pCsr->zMatchinfo, zArg) ){
127453 assert( pCsr->aMatchinfo );
127454 sqlite3_free(pCsr->aMatchinfo);
127455 pCsr->zMatchinfo = 0;
127456 pCsr->aMatchinfo = 0;
127459 /* If Fts3Cursor.aMatchinfo[] is NULL, then this is the first time the
127460 ** matchinfo function has been called for this query. In this case
127461 ** allocate the array used to accumulate the matchinfo data and
127462 ** initialize those elements that are constant for every row.
127464 if( pCsr->aMatchinfo==0 ){
127465 int nMatchinfo = 0; /* Number of u32 elements in match-info */
127466 int nArg; /* Bytes in zArg */
127467 int i; /* Used to iterate through zArg */
127469 /* Determine the number of phrases in the query */
127470 pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
127471 sInfo.nPhrase = pCsr->nPhrase;
127473 /* Determine the number of integers in the buffer returned by this call. */
127474 for(i=0; zArg[i]; i++){
127475 nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
127478 /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
127479 nArg = (int)strlen(zArg);
127480 pCsr->aMatchinfo = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo + nArg + 1);
127481 if( !pCsr->aMatchinfo ) return SQLITE_NOMEM;
127483 pCsr->zMatchinfo = (char *)&pCsr->aMatchinfo[nMatchinfo];
127484 pCsr->nMatchinfo = nMatchinfo;
127485 memcpy(pCsr->zMatchinfo, zArg, nArg+1);
127486 memset(pCsr->aMatchinfo, 0, sizeof(u32)*nMatchinfo);
127487 pCsr->isMatchinfoNeeded = 1;
127488 bGlobal = 1;
127491 sInfo.aMatchinfo = pCsr->aMatchinfo;
127492 sInfo.nPhrase = pCsr->nPhrase;
127493 if( pCsr->isMatchinfoNeeded ){
127494 rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
127495 pCsr->isMatchinfoNeeded = 0;
127498 return rc;
127502 ** Implementation of snippet() function.
127504 SQLITE_PRIVATE void sqlite3Fts3Snippet(
127505 sqlite3_context *pCtx, /* SQLite function call context */
127506 Fts3Cursor *pCsr, /* Cursor object */
127507 const char *zStart, /* Snippet start text - "<b>" */
127508 const char *zEnd, /* Snippet end text - "</b>" */
127509 const char *zEllipsis, /* Snippet ellipsis text - "<b>...</b>" */
127510 int iCol, /* Extract snippet from this column */
127511 int nToken /* Approximate number of tokens in snippet */
127513 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
127514 int rc = SQLITE_OK;
127515 int i;
127516 StrBuffer res = {0, 0, 0};
127518 /* The returned text includes up to four fragments of text extracted from
127519 ** the data in the current row. The first iteration of the for(...) loop
127520 ** below attempts to locate a single fragment of text nToken tokens in
127521 ** size that contains at least one instance of all phrases in the query
127522 ** expression that appear in the current row. If such a fragment of text
127523 ** cannot be found, the second iteration of the loop attempts to locate
127524 ** a pair of fragments, and so on.
127526 int nSnippet = 0; /* Number of fragments in this snippet */
127527 SnippetFragment aSnippet[4]; /* Maximum of 4 fragments per snippet */
127528 int nFToken = -1; /* Number of tokens in each fragment */
127530 if( !pCsr->pExpr ){
127531 sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
127532 return;
127535 for(nSnippet=1; 1; nSnippet++){
127537 int iSnip; /* Loop counter 0..nSnippet-1 */
127538 u64 mCovered = 0; /* Bitmask of phrases covered by snippet */
127539 u64 mSeen = 0; /* Bitmask of phrases seen by BestSnippet() */
127541 if( nToken>=0 ){
127542 nFToken = (nToken+nSnippet-1) / nSnippet;
127543 }else{
127544 nFToken = -1 * nToken;
127547 for(iSnip=0; iSnip<nSnippet; iSnip++){
127548 int iBestScore = -1; /* Best score of columns checked so far */
127549 int iRead; /* Used to iterate through columns */
127550 SnippetFragment *pFragment = &aSnippet[iSnip];
127552 memset(pFragment, 0, sizeof(*pFragment));
127554 /* Loop through all columns of the table being considered for snippets.
127555 ** If the iCol argument to this function was negative, this means all
127556 ** columns of the FTS3 table. Otherwise, only column iCol is considered.
127558 for(iRead=0; iRead<pTab->nColumn; iRead++){
127559 SnippetFragment sF = {0, 0, 0, 0};
127560 int iS;
127561 if( iCol>=0 && iRead!=iCol ) continue;
127563 /* Find the best snippet of nFToken tokens in column iRead. */
127564 rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
127565 if( rc!=SQLITE_OK ){
127566 goto snippet_out;
127568 if( iS>iBestScore ){
127569 *pFragment = sF;
127570 iBestScore = iS;
127574 mCovered |= pFragment->covered;
127577 /* If all query phrases seen by fts3BestSnippet() are present in at least
127578 ** one of the nSnippet snippet fragments, break out of the loop.
127580 assert( (mCovered&mSeen)==mCovered );
127581 if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
127584 assert( nFToken>0 );
127586 for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
127587 rc = fts3SnippetText(pCsr, &aSnippet[i],
127588 i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
127592 snippet_out:
127593 sqlite3Fts3SegmentsClose(pTab);
127594 if( rc!=SQLITE_OK ){
127595 sqlite3_result_error_code(pCtx, rc);
127596 sqlite3_free(res.z);
127597 }else{
127598 sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
127603 typedef struct TermOffset TermOffset;
127604 typedef struct TermOffsetCtx TermOffsetCtx;
127606 struct TermOffset {
127607 char *pList; /* Position-list */
127608 int iPos; /* Position just read from pList */
127609 int iOff; /* Offset of this term from read positions */
127612 struct TermOffsetCtx {
127613 Fts3Cursor *pCsr;
127614 int iCol; /* Column of table to populate aTerm for */
127615 int iTerm;
127616 sqlite3_int64 iDocid;
127617 TermOffset *aTerm;
127621 ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
127623 static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
127624 TermOffsetCtx *p = (TermOffsetCtx *)ctx;
127625 int nTerm; /* Number of tokens in phrase */
127626 int iTerm; /* For looping through nTerm phrase terms */
127627 char *pList; /* Pointer to position list for phrase */
127628 int iPos = 0; /* First position in position-list */
127630 UNUSED_PARAMETER(iPhrase);
127631 pList = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol);
127632 nTerm = pExpr->pPhrase->nToken;
127633 if( pList ){
127634 fts3GetDeltaPosition(&pList, &iPos);
127635 assert( iPos>=0 );
127638 for(iTerm=0; iTerm<nTerm; iTerm++){
127639 TermOffset *pT = &p->aTerm[p->iTerm++];
127640 pT->iOff = nTerm-iTerm-1;
127641 pT->pList = pList;
127642 pT->iPos = iPos;
127645 return SQLITE_OK;
127649 ** Implementation of offsets() function.
127651 SQLITE_PRIVATE void sqlite3Fts3Offsets(
127652 sqlite3_context *pCtx, /* SQLite function call context */
127653 Fts3Cursor *pCsr /* Cursor object */
127655 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
127656 sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
127657 const char *ZDUMMY; /* Dummy argument used with xNext() */
127658 int NDUMMY; /* Dummy argument used with xNext() */
127659 int rc; /* Return Code */
127660 int nToken; /* Number of tokens in query */
127661 int iCol; /* Column currently being processed */
127662 StrBuffer res = {0, 0, 0}; /* Result string */
127663 TermOffsetCtx sCtx; /* Context for fts3ExprTermOffsetInit() */
127665 if( !pCsr->pExpr ){
127666 sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
127667 return;
127670 memset(&sCtx, 0, sizeof(sCtx));
127671 assert( pCsr->isRequireSeek==0 );
127673 /* Count the number of terms in the query */
127674 rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
127675 if( rc!=SQLITE_OK ) goto offsets_out;
127677 /* Allocate the array of TermOffset iterators. */
127678 sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
127679 if( 0==sCtx.aTerm ){
127680 rc = SQLITE_NOMEM;
127681 goto offsets_out;
127683 sCtx.iDocid = pCsr->iPrevId;
127684 sCtx.pCsr = pCsr;
127686 /* Loop through the table columns, appending offset information to
127687 ** string-buffer res for each column.
127689 for(iCol=0; iCol<pTab->nColumn; iCol++){
127690 sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
127691 int iStart;
127692 int iEnd;
127693 int iCurrent;
127694 const char *zDoc;
127695 int nDoc;
127697 /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
127698 ** no way that this operation can fail, so the return code from
127699 ** fts3ExprIterate() can be discarded.
127701 sCtx.iCol = iCol;
127702 sCtx.iTerm = 0;
127703 (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void *)&sCtx);
127705 /* Retreive the text stored in column iCol. If an SQL NULL is stored
127706 ** in column iCol, jump immediately to the next iteration of the loop.
127707 ** If an OOM occurs while retrieving the data (this can happen if SQLite
127708 ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
127709 ** to the caller.
127711 zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
127712 nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
127713 if( zDoc==0 ){
127714 if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
127715 continue;
127717 rc = SQLITE_NOMEM;
127718 goto offsets_out;
127721 /* Initialize a tokenizer iterator to iterate through column iCol. */
127722 rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
127723 if( rc!=SQLITE_OK ) goto offsets_out;
127724 pC->pTokenizer = pTab->pTokenizer;
127726 rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
127727 while( rc==SQLITE_OK ){
127728 int i; /* Used to loop through terms */
127729 int iMinPos = 0x7FFFFFFF; /* Position of next token */
127730 TermOffset *pTerm = 0; /* TermOffset associated with next token */
127732 for(i=0; i<nToken; i++){
127733 TermOffset *pT = &sCtx.aTerm[i];
127734 if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
127735 iMinPos = pT->iPos-pT->iOff;
127736 pTerm = pT;
127740 if( !pTerm ){
127741 /* All offsets for this column have been gathered. */
127742 rc = SQLITE_DONE;
127743 }else{
127744 assert( iCurrent<=iMinPos );
127745 if( 0==(0xFE&*pTerm->pList) ){
127746 pTerm->pList = 0;
127747 }else{
127748 fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
127750 while( rc==SQLITE_OK && iCurrent<iMinPos ){
127751 rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
127753 if( rc==SQLITE_OK ){
127754 char aBuffer[64];
127755 sqlite3_snprintf(sizeof(aBuffer), aBuffer,
127756 "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
127758 rc = fts3StringAppend(&res, aBuffer, -1);
127759 }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
127760 rc = FTS_CORRUPT_VTAB;
127764 if( rc==SQLITE_DONE ){
127765 rc = SQLITE_OK;
127768 pMod->xClose(pC);
127769 if( rc!=SQLITE_OK ) goto offsets_out;
127772 offsets_out:
127773 sqlite3_free(sCtx.aTerm);
127774 assert( rc!=SQLITE_DONE );
127775 sqlite3Fts3SegmentsClose(pTab);
127776 if( rc!=SQLITE_OK ){
127777 sqlite3_result_error_code(pCtx, rc);
127778 sqlite3_free(res.z);
127779 }else{
127780 sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
127782 return;
127786 ** Implementation of matchinfo() function.
127788 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
127789 sqlite3_context *pContext, /* Function call context */
127790 Fts3Cursor *pCsr, /* FTS3 table cursor */
127791 const char *zArg /* Second arg to matchinfo() function */
127793 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
127794 int rc;
127795 int i;
127796 const char *zFormat;
127798 if( zArg ){
127799 for(i=0; zArg[i]; i++){
127800 char *zErr = 0;
127801 if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
127802 sqlite3_result_error(pContext, zErr, -1);
127803 sqlite3_free(zErr);
127804 return;
127807 zFormat = zArg;
127808 }else{
127809 zFormat = FTS3_MATCHINFO_DEFAULT;
127812 if( !pCsr->pExpr ){
127813 sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
127814 return;
127817 /* Retrieve matchinfo() data. */
127818 rc = fts3GetMatchinfo(pCsr, zFormat);
127819 sqlite3Fts3SegmentsClose(pTab);
127821 if( rc!=SQLITE_OK ){
127822 sqlite3_result_error_code(pContext, rc);
127823 }else{
127824 int n = pCsr->nMatchinfo * sizeof(u32);
127825 sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT);
127829 #endif
127831 /************** End of fts3_snippet.c ****************************************/
127832 /************** Begin file rtree.c *******************************************/
127834 ** 2001 September 15
127836 ** The author disclaims copyright to this source code. In place of
127837 ** a legal notice, here is a blessing:
127839 ** May you do good and not evil.
127840 ** May you find forgiveness for yourself and forgive others.
127841 ** May you share freely, never taking more than you give.
127843 *************************************************************************
127844 ** This file contains code for implementations of the r-tree and r*-tree
127845 ** algorithms packaged as an SQLite virtual table module.
127849 ** Database Format of R-Tree Tables
127850 ** --------------------------------
127852 ** The data structure for a single virtual r-tree table is stored in three
127853 ** native SQLite tables declared as follows. In each case, the '%' character
127854 ** in the table name is replaced with the user-supplied name of the r-tree
127855 ** table.
127857 ** CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
127858 ** CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
127859 ** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
127861 ** The data for each node of the r-tree structure is stored in the %_node
127862 ** table. For each node that is not the root node of the r-tree, there is
127863 ** an entry in the %_parent table associating the node with its parent.
127864 ** And for each row of data in the table, there is an entry in the %_rowid
127865 ** table that maps from the entries rowid to the id of the node that it
127866 ** is stored on.
127868 ** The root node of an r-tree always exists, even if the r-tree table is
127869 ** empty. The nodeno of the root node is always 1. All other nodes in the
127870 ** table must be the same size as the root node. The content of each node
127871 ** is formatted as follows:
127873 ** 1. If the node is the root node (node 1), then the first 2 bytes
127874 ** of the node contain the tree depth as a big-endian integer.
127875 ** For non-root nodes, the first 2 bytes are left unused.
127877 ** 2. The next 2 bytes contain the number of entries currently
127878 ** stored in the node.
127880 ** 3. The remainder of the node contains the node entries. Each entry
127881 ** consists of a single 8-byte integer followed by an even number
127882 ** of 4-byte coordinates. For leaf nodes the integer is the rowid
127883 ** of a record. For internal nodes it is the node number of a
127884 ** child page.
127887 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
127890 ** This file contains an implementation of a couple of different variants
127891 ** of the r-tree algorithm. See the README file for further details. The
127892 ** same data-structure is used for all, but the algorithms for insert and
127893 ** delete operations vary. The variants used are selected at compile time
127894 ** by defining the following symbols:
127897 /* Either, both or none of the following may be set to activate
127898 ** r*tree variant algorithms.
127900 #define VARIANT_RSTARTREE_CHOOSESUBTREE 0
127901 #define VARIANT_RSTARTREE_REINSERT 1
127904 ** Exactly one of the following must be set to 1.
127906 #define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0
127907 #define VARIANT_GUTTMAN_LINEAR_SPLIT 0
127908 #define VARIANT_RSTARTREE_SPLIT 1
127910 #define VARIANT_GUTTMAN_SPLIT \
127911 (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT)
127913 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
127914 #define PickNext QuadraticPickNext
127915 #define PickSeeds QuadraticPickSeeds
127916 #define AssignCells splitNodeGuttman
127917 #endif
127918 #if VARIANT_GUTTMAN_LINEAR_SPLIT
127919 #define PickNext LinearPickNext
127920 #define PickSeeds LinearPickSeeds
127921 #define AssignCells splitNodeGuttman
127922 #endif
127923 #if VARIANT_RSTARTREE_SPLIT
127924 #define AssignCells splitNodeStartree
127925 #endif
127927 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
127928 # define NDEBUG 1
127929 #endif
127931 #ifndef SQLITE_CORE
127932 SQLITE_EXTENSION_INIT1
127933 #else
127934 #endif
127936 /* #include <string.h> */
127937 /* #include <assert.h> */
127939 #ifndef SQLITE_AMALGAMATION
127940 #include "sqlite3rtree.h"
127941 typedef sqlite3_int64 i64;
127942 typedef unsigned char u8;
127943 typedef unsigned int u32;
127944 #endif
127946 /* The following macro is used to suppress compiler warnings.
127948 #ifndef UNUSED_PARAMETER
127949 # define UNUSED_PARAMETER(x) (void)(x)
127950 #endif
127952 typedef struct Rtree Rtree;
127953 typedef struct RtreeCursor RtreeCursor;
127954 typedef struct RtreeNode RtreeNode;
127955 typedef struct RtreeCell RtreeCell;
127956 typedef struct RtreeConstraint RtreeConstraint;
127957 typedef struct RtreeMatchArg RtreeMatchArg;
127958 typedef struct RtreeGeomCallback RtreeGeomCallback;
127959 typedef union RtreeCoord RtreeCoord;
127961 /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
127962 #define RTREE_MAX_DIMENSIONS 5
127964 /* Size of hash table Rtree.aHash. This hash table is not expected to
127965 ** ever contain very many entries, so a fixed number of buckets is
127966 ** used.
127968 #define HASHSIZE 128
127971 ** An rtree virtual-table object.
127973 struct Rtree {
127974 sqlite3_vtab base;
127975 sqlite3 *db; /* Host database connection */
127976 int iNodeSize; /* Size in bytes of each node in the node table */
127977 int nDim; /* Number of dimensions */
127978 int nBytesPerCell; /* Bytes consumed per cell */
127979 int iDepth; /* Current depth of the r-tree structure */
127980 char *zDb; /* Name of database containing r-tree table */
127981 char *zName; /* Name of r-tree table */
127982 RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
127983 int nBusy; /* Current number of users of this structure */
127985 /* List of nodes removed during a CondenseTree operation. List is
127986 ** linked together via the pointer normally used for hash chains -
127987 ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
127988 ** headed by the node (leaf nodes have RtreeNode.iNode==0).
127990 RtreeNode *pDeleted;
127991 int iReinsertHeight; /* Height of sub-trees Reinsert() has run on */
127993 /* Statements to read/write/delete a record from xxx_node */
127994 sqlite3_stmt *pReadNode;
127995 sqlite3_stmt *pWriteNode;
127996 sqlite3_stmt *pDeleteNode;
127998 /* Statements to read/write/delete a record from xxx_rowid */
127999 sqlite3_stmt *pReadRowid;
128000 sqlite3_stmt *pWriteRowid;
128001 sqlite3_stmt *pDeleteRowid;
128003 /* Statements to read/write/delete a record from xxx_parent */
128004 sqlite3_stmt *pReadParent;
128005 sqlite3_stmt *pWriteParent;
128006 sqlite3_stmt *pDeleteParent;
128008 int eCoordType;
128011 /* Possible values for eCoordType: */
128012 #define RTREE_COORD_REAL32 0
128013 #define RTREE_COORD_INT32 1
128016 ** The minimum number of cells allowed for a node is a third of the
128017 ** maximum. In Gutman's notation:
128019 ** m = M/3
128021 ** If an R*-tree "Reinsert" operation is required, the same number of
128022 ** cells are removed from the overfull node and reinserted into the tree.
128024 #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
128025 #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
128026 #define RTREE_MAXCELLS 51
128029 ** The smallest possible node-size is (512-64)==448 bytes. And the largest
128030 ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
128031 ** Therefore all non-root nodes must contain at least 3 entries. Since
128032 ** 2^40 is greater than 2^64, an r-tree structure always has a depth of
128033 ** 40 or less.
128035 #define RTREE_MAX_DEPTH 40
128038 ** An rtree cursor object.
128040 struct RtreeCursor {
128041 sqlite3_vtab_cursor base;
128042 RtreeNode *pNode; /* Node cursor is currently pointing at */
128043 int iCell; /* Index of current cell in pNode */
128044 int iStrategy; /* Copy of idxNum search parameter */
128045 int nConstraint; /* Number of entries in aConstraint */
128046 RtreeConstraint *aConstraint; /* Search constraints. */
128049 union RtreeCoord {
128050 float f;
128051 int i;
128055 ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
128056 ** formatted as a double. This macro assumes that local variable pRtree points
128057 ** to the Rtree structure associated with the RtreeCoord.
128059 #define DCOORD(coord) ( \
128060 (pRtree->eCoordType==RTREE_COORD_REAL32) ? \
128061 ((double)coord.f) : \
128062 ((double)coord.i) \
128066 ** A search constraint.
128068 struct RtreeConstraint {
128069 int iCoord; /* Index of constrained coordinate */
128070 int op; /* Constraining operation */
128071 double rValue; /* Constraint value. */
128072 int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
128073 sqlite3_rtree_geometry *pGeom; /* Constraint callback argument for a MATCH */
128076 /* Possible values for RtreeConstraint.op */
128077 #define RTREE_EQ 0x41
128078 #define RTREE_LE 0x42
128079 #define RTREE_LT 0x43
128080 #define RTREE_GE 0x44
128081 #define RTREE_GT 0x45
128082 #define RTREE_MATCH 0x46
128085 ** An rtree structure node.
128087 struct RtreeNode {
128088 RtreeNode *pParent; /* Parent node */
128089 i64 iNode;
128090 int nRef;
128091 int isDirty;
128092 u8 *zData;
128093 RtreeNode *pNext; /* Next node in this hash chain */
128095 #define NCELL(pNode) readInt16(&(pNode)->zData[2])
128098 ** Structure to store a deserialized rtree record.
128100 struct RtreeCell {
128101 i64 iRowid;
128102 RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
128107 ** Value for the first field of every RtreeMatchArg object. The MATCH
128108 ** operator tests that the first field of a blob operand matches this
128109 ** value to avoid operating on invalid blobs (which could cause a segfault).
128111 #define RTREE_GEOMETRY_MAGIC 0x891245AB
128114 ** An instance of this structure must be supplied as a blob argument to
128115 ** the right-hand-side of an SQL MATCH operator used to constrain an
128116 ** r-tree query.
128118 struct RtreeMatchArg {
128119 u32 magic; /* Always RTREE_GEOMETRY_MAGIC */
128120 int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
128121 void *pContext;
128122 int nParam;
128123 double aParam[1];
128127 ** When a geometry callback is created (see sqlite3_rtree_geometry_callback),
128128 ** a single instance of the following structure is allocated. It is used
128129 ** as the context for the user-function created by by s_r_g_c(). The object
128130 ** is eventually deleted by the destructor mechanism provided by
128131 ** sqlite3_create_function_v2() (which is called by s_r_g_c() to create
128132 ** the geometry callback function).
128134 struct RtreeGeomCallback {
128135 int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
128136 void *pContext;
128139 #ifndef MAX
128140 # define MAX(x,y) ((x) < (y) ? (y) : (x))
128141 #endif
128142 #ifndef MIN
128143 # define MIN(x,y) ((x) > (y) ? (y) : (x))
128144 #endif
128147 ** Functions to deserialize a 16 bit integer, 32 bit real number and
128148 ** 64 bit integer. The deserialized value is returned.
128150 static int readInt16(u8 *p){
128151 return (p[0]<<8) + p[1];
128153 static void readCoord(u8 *p, RtreeCoord *pCoord){
128154 u32 i = (
128155 (((u32)p[0]) << 24) +
128156 (((u32)p[1]) << 16) +
128157 (((u32)p[2]) << 8) +
128158 (((u32)p[3]) << 0)
128160 *(u32 *)pCoord = i;
128162 static i64 readInt64(u8 *p){
128163 return (
128164 (((i64)p[0]) << 56) +
128165 (((i64)p[1]) << 48) +
128166 (((i64)p[2]) << 40) +
128167 (((i64)p[3]) << 32) +
128168 (((i64)p[4]) << 24) +
128169 (((i64)p[5]) << 16) +
128170 (((i64)p[6]) << 8) +
128171 (((i64)p[7]) << 0)
128176 ** Functions to serialize a 16 bit integer, 32 bit real number and
128177 ** 64 bit integer. The value returned is the number of bytes written
128178 ** to the argument buffer (always 2, 4 and 8 respectively).
128180 static int writeInt16(u8 *p, int i){
128181 p[0] = (i>> 8)&0xFF;
128182 p[1] = (i>> 0)&0xFF;
128183 return 2;
128185 static int writeCoord(u8 *p, RtreeCoord *pCoord){
128186 u32 i;
128187 assert( sizeof(RtreeCoord)==4 );
128188 assert( sizeof(u32)==4 );
128189 i = *(u32 *)pCoord;
128190 p[0] = (i>>24)&0xFF;
128191 p[1] = (i>>16)&0xFF;
128192 p[2] = (i>> 8)&0xFF;
128193 p[3] = (i>> 0)&0xFF;
128194 return 4;
128196 static int writeInt64(u8 *p, i64 i){
128197 p[0] = (i>>56)&0xFF;
128198 p[1] = (i>>48)&0xFF;
128199 p[2] = (i>>40)&0xFF;
128200 p[3] = (i>>32)&0xFF;
128201 p[4] = (i>>24)&0xFF;
128202 p[5] = (i>>16)&0xFF;
128203 p[6] = (i>> 8)&0xFF;
128204 p[7] = (i>> 0)&0xFF;
128205 return 8;
128209 ** Increment the reference count of node p.
128211 static void nodeReference(RtreeNode *p){
128212 if( p ){
128213 p->nRef++;
128218 ** Clear the content of node p (set all bytes to 0x00).
128220 static void nodeZero(Rtree *pRtree, RtreeNode *p){
128221 memset(&p->zData[2], 0, pRtree->iNodeSize-2);
128222 p->isDirty = 1;
128226 ** Given a node number iNode, return the corresponding key to use
128227 ** in the Rtree.aHash table.
128229 static int nodeHash(i64 iNode){
128230 return (
128231 (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^
128232 (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0)
128233 ) % HASHSIZE;
128237 ** Search the node hash table for node iNode. If found, return a pointer
128238 ** to it. Otherwise, return 0.
128240 static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
128241 RtreeNode *p;
128242 for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
128243 return p;
128247 ** Add node pNode to the node hash table.
128249 static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
128250 int iHash;
128251 assert( pNode->pNext==0 );
128252 iHash = nodeHash(pNode->iNode);
128253 pNode->pNext = pRtree->aHash[iHash];
128254 pRtree->aHash[iHash] = pNode;
128258 ** Remove node pNode from the node hash table.
128260 static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
128261 RtreeNode **pp;
128262 if( pNode->iNode!=0 ){
128263 pp = &pRtree->aHash[nodeHash(pNode->iNode)];
128264 for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
128265 *pp = pNode->pNext;
128266 pNode->pNext = 0;
128271 ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
128272 ** indicating that node has not yet been assigned a node number. It is
128273 ** assigned a node number when nodeWrite() is called to write the
128274 ** node contents out to the database.
128276 static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
128277 RtreeNode *pNode;
128278 pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
128279 if( pNode ){
128280 memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
128281 pNode->zData = (u8 *)&pNode[1];
128282 pNode->nRef = 1;
128283 pNode->pParent = pParent;
128284 pNode->isDirty = 1;
128285 nodeReference(pParent);
128287 return pNode;
128291 ** Obtain a reference to an r-tree node.
128293 static int
128294 nodeAcquire(
128295 Rtree *pRtree, /* R-tree structure */
128296 i64 iNode, /* Node number to load */
128297 RtreeNode *pParent, /* Either the parent node or NULL */
128298 RtreeNode **ppNode /* OUT: Acquired node */
128300 int rc;
128301 int rc2 = SQLITE_OK;
128302 RtreeNode *pNode;
128304 /* Check if the requested node is already in the hash table. If so,
128305 ** increase its reference count and return it.
128307 if( (pNode = nodeHashLookup(pRtree, iNode)) ){
128308 assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
128309 if( pParent && !pNode->pParent ){
128310 nodeReference(pParent);
128311 pNode->pParent = pParent;
128313 pNode->nRef++;
128314 *ppNode = pNode;
128315 return SQLITE_OK;
128318 sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
128319 rc = sqlite3_step(pRtree->pReadNode);
128320 if( rc==SQLITE_ROW ){
128321 const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
128322 if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
128323 pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
128324 if( !pNode ){
128325 rc2 = SQLITE_NOMEM;
128326 }else{
128327 pNode->pParent = pParent;
128328 pNode->zData = (u8 *)&pNode[1];
128329 pNode->nRef = 1;
128330 pNode->iNode = iNode;
128331 pNode->isDirty = 0;
128332 pNode->pNext = 0;
128333 memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
128334 nodeReference(pParent);
128338 rc = sqlite3_reset(pRtree->pReadNode);
128339 if( rc==SQLITE_OK ) rc = rc2;
128341 /* If the root node was just loaded, set pRtree->iDepth to the height
128342 ** of the r-tree structure. A height of zero means all data is stored on
128343 ** the root node. A height of one means the children of the root node
128344 ** are the leaves, and so on. If the depth as specified on the root node
128345 ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
128347 if( pNode && iNode==1 ){
128348 pRtree->iDepth = readInt16(pNode->zData);
128349 if( pRtree->iDepth>RTREE_MAX_DEPTH ){
128350 rc = SQLITE_CORRUPT_VTAB;
128354 /* If no error has occurred so far, check if the "number of entries"
128355 ** field on the node is too large. If so, set the return code to
128356 ** SQLITE_CORRUPT_VTAB.
128358 if( pNode && rc==SQLITE_OK ){
128359 if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
128360 rc = SQLITE_CORRUPT_VTAB;
128364 if( rc==SQLITE_OK ){
128365 if( pNode!=0 ){
128366 nodeHashInsert(pRtree, pNode);
128367 }else{
128368 rc = SQLITE_CORRUPT_VTAB;
128370 *ppNode = pNode;
128371 }else{
128372 sqlite3_free(pNode);
128373 *ppNode = 0;
128376 return rc;
128380 ** Overwrite cell iCell of node pNode with the contents of pCell.
128382 static void nodeOverwriteCell(
128383 Rtree *pRtree,
128384 RtreeNode *pNode,
128385 RtreeCell *pCell,
128386 int iCell
128388 int ii;
128389 u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
128390 p += writeInt64(p, pCell->iRowid);
128391 for(ii=0; ii<(pRtree->nDim*2); ii++){
128392 p += writeCoord(p, &pCell->aCoord[ii]);
128394 pNode->isDirty = 1;
128398 ** Remove cell the cell with index iCell from node pNode.
128400 static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
128401 u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
128402 u8 *pSrc = &pDst[pRtree->nBytesPerCell];
128403 int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
128404 memmove(pDst, pSrc, nByte);
128405 writeInt16(&pNode->zData[2], NCELL(pNode)-1);
128406 pNode->isDirty = 1;
128410 ** Insert the contents of cell pCell into node pNode. If the insert
128411 ** is successful, return SQLITE_OK.
128413 ** If there is not enough free space in pNode, return SQLITE_FULL.
128415 static int
128416 nodeInsertCell(
128417 Rtree *pRtree,
128418 RtreeNode *pNode,
128419 RtreeCell *pCell
128421 int nCell; /* Current number of cells in pNode */
128422 int nMaxCell; /* Maximum number of cells for pNode */
128424 nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
128425 nCell = NCELL(pNode);
128427 assert( nCell<=nMaxCell );
128428 if( nCell<nMaxCell ){
128429 nodeOverwriteCell(pRtree, pNode, pCell, nCell);
128430 writeInt16(&pNode->zData[2], nCell+1);
128431 pNode->isDirty = 1;
128434 return (nCell==nMaxCell);
128438 ** If the node is dirty, write it out to the database.
128440 static int
128441 nodeWrite(Rtree *pRtree, RtreeNode *pNode){
128442 int rc = SQLITE_OK;
128443 if( pNode->isDirty ){
128444 sqlite3_stmt *p = pRtree->pWriteNode;
128445 if( pNode->iNode ){
128446 sqlite3_bind_int64(p, 1, pNode->iNode);
128447 }else{
128448 sqlite3_bind_null(p, 1);
128450 sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
128451 sqlite3_step(p);
128452 pNode->isDirty = 0;
128453 rc = sqlite3_reset(p);
128454 if( pNode->iNode==0 && rc==SQLITE_OK ){
128455 pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
128456 nodeHashInsert(pRtree, pNode);
128459 return rc;
128463 ** Release a reference to a node. If the node is dirty and the reference
128464 ** count drops to zero, the node data is written to the database.
128466 static int
128467 nodeRelease(Rtree *pRtree, RtreeNode *pNode){
128468 int rc = SQLITE_OK;
128469 if( pNode ){
128470 assert( pNode->nRef>0 );
128471 pNode->nRef--;
128472 if( pNode->nRef==0 ){
128473 if( pNode->iNode==1 ){
128474 pRtree->iDepth = -1;
128476 if( pNode->pParent ){
128477 rc = nodeRelease(pRtree, pNode->pParent);
128479 if( rc==SQLITE_OK ){
128480 rc = nodeWrite(pRtree, pNode);
128482 nodeHashDelete(pRtree, pNode);
128483 sqlite3_free(pNode);
128486 return rc;
128490 ** Return the 64-bit integer value associated with cell iCell of
128491 ** node pNode. If pNode is a leaf node, this is a rowid. If it is
128492 ** an internal node, then the 64-bit integer is a child page number.
128494 static i64 nodeGetRowid(
128495 Rtree *pRtree,
128496 RtreeNode *pNode,
128497 int iCell
128499 assert( iCell<NCELL(pNode) );
128500 return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
128504 ** Return coordinate iCoord from cell iCell in node pNode.
128506 static void nodeGetCoord(
128507 Rtree *pRtree,
128508 RtreeNode *pNode,
128509 int iCell,
128510 int iCoord,
128511 RtreeCoord *pCoord /* Space to write result to */
128513 readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
128517 ** Deserialize cell iCell of node pNode. Populate the structure pointed
128518 ** to by pCell with the results.
128520 static void nodeGetCell(
128521 Rtree *pRtree,
128522 RtreeNode *pNode,
128523 int iCell,
128524 RtreeCell *pCell
128526 int ii;
128527 pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
128528 for(ii=0; ii<pRtree->nDim*2; ii++){
128529 nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]);
128534 /* Forward declaration for the function that does the work of
128535 ** the virtual table module xCreate() and xConnect() methods.
128537 static int rtreeInit(
128538 sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
128542 ** Rtree virtual table module xCreate method.
128544 static int rtreeCreate(
128545 sqlite3 *db,
128546 void *pAux,
128547 int argc, const char *const*argv,
128548 sqlite3_vtab **ppVtab,
128549 char **pzErr
128551 return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
128555 ** Rtree virtual table module xConnect method.
128557 static int rtreeConnect(
128558 sqlite3 *db,
128559 void *pAux,
128560 int argc, const char *const*argv,
128561 sqlite3_vtab **ppVtab,
128562 char **pzErr
128564 return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
128568 ** Increment the r-tree reference count.
128570 static void rtreeReference(Rtree *pRtree){
128571 pRtree->nBusy++;
128575 ** Decrement the r-tree reference count. When the reference count reaches
128576 ** zero the structure is deleted.
128578 static void rtreeRelease(Rtree *pRtree){
128579 pRtree->nBusy--;
128580 if( pRtree->nBusy==0 ){
128581 sqlite3_finalize(pRtree->pReadNode);
128582 sqlite3_finalize(pRtree->pWriteNode);
128583 sqlite3_finalize(pRtree->pDeleteNode);
128584 sqlite3_finalize(pRtree->pReadRowid);
128585 sqlite3_finalize(pRtree->pWriteRowid);
128586 sqlite3_finalize(pRtree->pDeleteRowid);
128587 sqlite3_finalize(pRtree->pReadParent);
128588 sqlite3_finalize(pRtree->pWriteParent);
128589 sqlite3_finalize(pRtree->pDeleteParent);
128590 sqlite3_free(pRtree);
128595 ** Rtree virtual table module xDisconnect method.
128597 static int rtreeDisconnect(sqlite3_vtab *pVtab){
128598 rtreeRelease((Rtree *)pVtab);
128599 return SQLITE_OK;
128603 ** Rtree virtual table module xDestroy method.
128605 static int rtreeDestroy(sqlite3_vtab *pVtab){
128606 Rtree *pRtree = (Rtree *)pVtab;
128607 int rc;
128608 char *zCreate = sqlite3_mprintf(
128609 "DROP TABLE '%q'.'%q_node';"
128610 "DROP TABLE '%q'.'%q_rowid';"
128611 "DROP TABLE '%q'.'%q_parent';",
128612 pRtree->zDb, pRtree->zName,
128613 pRtree->zDb, pRtree->zName,
128614 pRtree->zDb, pRtree->zName
128616 if( !zCreate ){
128617 rc = SQLITE_NOMEM;
128618 }else{
128619 rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
128620 sqlite3_free(zCreate);
128622 if( rc==SQLITE_OK ){
128623 rtreeRelease(pRtree);
128626 return rc;
128630 ** Rtree virtual table module xOpen method.
128632 static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
128633 int rc = SQLITE_NOMEM;
128634 RtreeCursor *pCsr;
128636 pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
128637 if( pCsr ){
128638 memset(pCsr, 0, sizeof(RtreeCursor));
128639 pCsr->base.pVtab = pVTab;
128640 rc = SQLITE_OK;
128642 *ppCursor = (sqlite3_vtab_cursor *)pCsr;
128644 return rc;
128649 ** Free the RtreeCursor.aConstraint[] array and its contents.
128651 static void freeCursorConstraints(RtreeCursor *pCsr){
128652 if( pCsr->aConstraint ){
128653 int i; /* Used to iterate through constraint array */
128654 for(i=0; i<pCsr->nConstraint; i++){
128655 sqlite3_rtree_geometry *pGeom = pCsr->aConstraint[i].pGeom;
128656 if( pGeom ){
128657 if( pGeom->xDelUser ) pGeom->xDelUser(pGeom->pUser);
128658 sqlite3_free(pGeom);
128661 sqlite3_free(pCsr->aConstraint);
128662 pCsr->aConstraint = 0;
128667 ** Rtree virtual table module xClose method.
128669 static int rtreeClose(sqlite3_vtab_cursor *cur){
128670 Rtree *pRtree = (Rtree *)(cur->pVtab);
128671 int rc;
128672 RtreeCursor *pCsr = (RtreeCursor *)cur;
128673 freeCursorConstraints(pCsr);
128674 rc = nodeRelease(pRtree, pCsr->pNode);
128675 sqlite3_free(pCsr);
128676 return rc;
128680 ** Rtree virtual table module xEof method.
128682 ** Return non-zero if the cursor does not currently point to a valid
128683 ** record (i.e if the scan has finished), or zero otherwise.
128685 static int rtreeEof(sqlite3_vtab_cursor *cur){
128686 RtreeCursor *pCsr = (RtreeCursor *)cur;
128687 return (pCsr->pNode==0);
128691 ** The r-tree constraint passed as the second argument to this function is
128692 ** guaranteed to be a MATCH constraint.
128694 static int testRtreeGeom(
128695 Rtree *pRtree, /* R-Tree object */
128696 RtreeConstraint *pConstraint, /* MATCH constraint to test */
128697 RtreeCell *pCell, /* Cell to test */
128698 int *pbRes /* OUT: Test result */
128700 int i;
128701 double aCoord[RTREE_MAX_DIMENSIONS*2];
128702 int nCoord = pRtree->nDim*2;
128704 assert( pConstraint->op==RTREE_MATCH );
128705 assert( pConstraint->pGeom );
128707 for(i=0; i<nCoord; i++){
128708 aCoord[i] = DCOORD(pCell->aCoord[i]);
128710 return pConstraint->xGeom(pConstraint->pGeom, nCoord, aCoord, pbRes);
128714 ** Cursor pCursor currently points to a cell in a non-leaf page.
128715 ** Set *pbEof to true if the sub-tree headed by the cell is filtered
128716 ** (excluded) by the constraints in the pCursor->aConstraint[]
128717 ** array, or false otherwise.
128719 ** Return SQLITE_OK if successful or an SQLite error code if an error
128720 ** occurs within a geometry callback.
128722 static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
128723 RtreeCell cell;
128724 int ii;
128725 int bRes = 0;
128726 int rc = SQLITE_OK;
128728 nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
128729 for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){
128730 RtreeConstraint *p = &pCursor->aConstraint[ii];
128731 double cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
128732 double cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
128734 assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
128735 || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
128738 switch( p->op ){
128739 case RTREE_LE: case RTREE_LT:
128740 bRes = p->rValue<cell_min;
128741 break;
128743 case RTREE_GE: case RTREE_GT:
128744 bRes = p->rValue>cell_max;
128745 break;
128747 case RTREE_EQ:
128748 bRes = (p->rValue>cell_max || p->rValue<cell_min);
128749 break;
128751 default: {
128752 assert( p->op==RTREE_MATCH );
128753 rc = testRtreeGeom(pRtree, p, &cell, &bRes);
128754 bRes = !bRes;
128755 break;
128760 *pbEof = bRes;
128761 return rc;
128765 ** Test if the cell that cursor pCursor currently points to
128766 ** would be filtered (excluded) by the constraints in the
128767 ** pCursor->aConstraint[] array. If so, set *pbEof to true before
128768 ** returning. If the cell is not filtered (excluded) by the constraints,
128769 ** set pbEof to zero.
128771 ** Return SQLITE_OK if successful or an SQLite error code if an error
128772 ** occurs within a geometry callback.
128774 ** This function assumes that the cell is part of a leaf node.
128776 static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
128777 RtreeCell cell;
128778 int ii;
128779 *pbEof = 0;
128781 nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
128782 for(ii=0; ii<pCursor->nConstraint; ii++){
128783 RtreeConstraint *p = &pCursor->aConstraint[ii];
128784 double coord = DCOORD(cell.aCoord[p->iCoord]);
128785 int res;
128786 assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
128787 || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
128789 switch( p->op ){
128790 case RTREE_LE: res = (coord<=p->rValue); break;
128791 case RTREE_LT: res = (coord<p->rValue); break;
128792 case RTREE_GE: res = (coord>=p->rValue); break;
128793 case RTREE_GT: res = (coord>p->rValue); break;
128794 case RTREE_EQ: res = (coord==p->rValue); break;
128795 default: {
128796 int rc;
128797 assert( p->op==RTREE_MATCH );
128798 rc = testRtreeGeom(pRtree, p, &cell, &res);
128799 if( rc!=SQLITE_OK ){
128800 return rc;
128802 break;
128806 if( !res ){
128807 *pbEof = 1;
128808 return SQLITE_OK;
128812 return SQLITE_OK;
128816 ** Cursor pCursor currently points at a node that heads a sub-tree of
128817 ** height iHeight (if iHeight==0, then the node is a leaf). Descend
128818 ** to point to the left-most cell of the sub-tree that matches the
128819 ** configured constraints.
128821 static int descendToCell(
128822 Rtree *pRtree,
128823 RtreeCursor *pCursor,
128824 int iHeight,
128825 int *pEof /* OUT: Set to true if cannot descend */
128827 int isEof;
128828 int rc;
128829 int ii;
128830 RtreeNode *pChild;
128831 sqlite3_int64 iRowid;
128833 RtreeNode *pSavedNode = pCursor->pNode;
128834 int iSavedCell = pCursor->iCell;
128836 assert( iHeight>=0 );
128838 if( iHeight==0 ){
128839 rc = testRtreeEntry(pRtree, pCursor, &isEof);
128840 }else{
128841 rc = testRtreeCell(pRtree, pCursor, &isEof);
128843 if( rc!=SQLITE_OK || isEof || iHeight==0 ){
128844 goto descend_to_cell_out;
128847 iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
128848 rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
128849 if( rc!=SQLITE_OK ){
128850 goto descend_to_cell_out;
128853 nodeRelease(pRtree, pCursor->pNode);
128854 pCursor->pNode = pChild;
128855 isEof = 1;
128856 for(ii=0; isEof && ii<NCELL(pChild); ii++){
128857 pCursor->iCell = ii;
128858 rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof);
128859 if( rc!=SQLITE_OK ){
128860 goto descend_to_cell_out;
128864 if( isEof ){
128865 assert( pCursor->pNode==pChild );
128866 nodeReference(pSavedNode);
128867 nodeRelease(pRtree, pChild);
128868 pCursor->pNode = pSavedNode;
128869 pCursor->iCell = iSavedCell;
128872 descend_to_cell_out:
128873 *pEof = isEof;
128874 return rc;
128878 ** One of the cells in node pNode is guaranteed to have a 64-bit
128879 ** integer value equal to iRowid. Return the index of this cell.
128881 static int nodeRowidIndex(
128882 Rtree *pRtree,
128883 RtreeNode *pNode,
128884 i64 iRowid,
128885 int *piIndex
128887 int ii;
128888 int nCell = NCELL(pNode);
128889 for(ii=0; ii<nCell; ii++){
128890 if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
128891 *piIndex = ii;
128892 return SQLITE_OK;
128895 return SQLITE_CORRUPT_VTAB;
128899 ** Return the index of the cell containing a pointer to node pNode
128900 ** in its parent. If pNode is the root node, return -1.
128902 static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
128903 RtreeNode *pParent = pNode->pParent;
128904 if( pParent ){
128905 return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
128907 *piIndex = -1;
128908 return SQLITE_OK;
128912 ** Rtree virtual table module xNext method.
128914 static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
128915 Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
128916 RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
128917 int rc = SQLITE_OK;
128919 /* RtreeCursor.pNode must not be NULL. If is is NULL, then this cursor is
128920 ** already at EOF. It is against the rules to call the xNext() method of
128921 ** a cursor that has already reached EOF.
128923 assert( pCsr->pNode );
128925 if( pCsr->iStrategy==1 ){
128926 /* This "scan" is a direct lookup by rowid. There is no next entry. */
128927 nodeRelease(pRtree, pCsr->pNode);
128928 pCsr->pNode = 0;
128929 }else{
128930 /* Move to the next entry that matches the configured constraints. */
128931 int iHeight = 0;
128932 while( pCsr->pNode ){
128933 RtreeNode *pNode = pCsr->pNode;
128934 int nCell = NCELL(pNode);
128935 for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){
128936 int isEof;
128937 rc = descendToCell(pRtree, pCsr, iHeight, &isEof);
128938 if( rc!=SQLITE_OK || !isEof ){
128939 return rc;
128942 pCsr->pNode = pNode->pParent;
128943 rc = nodeParentIndex(pRtree, pNode, &pCsr->iCell);
128944 if( rc!=SQLITE_OK ){
128945 return rc;
128947 nodeReference(pCsr->pNode);
128948 nodeRelease(pRtree, pNode);
128949 iHeight++;
128953 return rc;
128957 ** Rtree virtual table module xRowid method.
128959 static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
128960 Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
128961 RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
128963 assert(pCsr->pNode);
128964 *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
128966 return SQLITE_OK;
128970 ** Rtree virtual table module xColumn method.
128972 static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
128973 Rtree *pRtree = (Rtree *)cur->pVtab;
128974 RtreeCursor *pCsr = (RtreeCursor *)cur;
128976 if( i==0 ){
128977 i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
128978 sqlite3_result_int64(ctx, iRowid);
128979 }else{
128980 RtreeCoord c;
128981 nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c);
128982 if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
128983 sqlite3_result_double(ctx, c.f);
128984 }else{
128985 assert( pRtree->eCoordType==RTREE_COORD_INT32 );
128986 sqlite3_result_int(ctx, c.i);
128990 return SQLITE_OK;
128994 ** Use nodeAcquire() to obtain the leaf node containing the record with
128995 ** rowid iRowid. If successful, set *ppLeaf to point to the node and
128996 ** return SQLITE_OK. If there is no such record in the table, set
128997 ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
128998 ** to zero and return an SQLite error code.
129000 static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){
129001 int rc;
129002 *ppLeaf = 0;
129003 sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
129004 if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
129005 i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
129006 rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
129007 sqlite3_reset(pRtree->pReadRowid);
129008 }else{
129009 rc = sqlite3_reset(pRtree->pReadRowid);
129011 return rc;
129015 ** This function is called to configure the RtreeConstraint object passed
129016 ** as the second argument for a MATCH constraint. The value passed as the
129017 ** first argument to this function is the right-hand operand to the MATCH
129018 ** operator.
129020 static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
129021 RtreeMatchArg *p;
129022 sqlite3_rtree_geometry *pGeom;
129023 int nBlob;
129025 /* Check that value is actually a blob. */
129026 if( !sqlite3_value_type(pValue)==SQLITE_BLOB ) return SQLITE_ERROR;
129028 /* Check that the blob is roughly the right size. */
129029 nBlob = sqlite3_value_bytes(pValue);
129030 if( nBlob<(int)sizeof(RtreeMatchArg)
129031 || ((nBlob-sizeof(RtreeMatchArg))%sizeof(double))!=0
129033 return SQLITE_ERROR;
129036 pGeom = (sqlite3_rtree_geometry *)sqlite3_malloc(
129037 sizeof(sqlite3_rtree_geometry) + nBlob
129039 if( !pGeom ) return SQLITE_NOMEM;
129040 memset(pGeom, 0, sizeof(sqlite3_rtree_geometry));
129041 p = (RtreeMatchArg *)&pGeom[1];
129043 memcpy(p, sqlite3_value_blob(pValue), nBlob);
129044 if( p->magic!=RTREE_GEOMETRY_MAGIC
129045 || nBlob!=(int)(sizeof(RtreeMatchArg) + (p->nParam-1)*sizeof(double))
129047 sqlite3_free(pGeom);
129048 return SQLITE_ERROR;
129051 pGeom->pContext = p->pContext;
129052 pGeom->nParam = p->nParam;
129053 pGeom->aParam = p->aParam;
129055 pCons->xGeom = p->xGeom;
129056 pCons->pGeom = pGeom;
129057 return SQLITE_OK;
129061 ** Rtree virtual table module xFilter method.
129063 static int rtreeFilter(
129064 sqlite3_vtab_cursor *pVtabCursor,
129065 int idxNum, const char *idxStr,
129066 int argc, sqlite3_value **argv
129068 Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
129069 RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
129071 RtreeNode *pRoot = 0;
129072 int ii;
129073 int rc = SQLITE_OK;
129075 rtreeReference(pRtree);
129077 freeCursorConstraints(pCsr);
129078 pCsr->iStrategy = idxNum;
129080 if( idxNum==1 ){
129081 /* Special case - lookup by rowid. */
129082 RtreeNode *pLeaf; /* Leaf on which the required cell resides */
129083 i64 iRowid = sqlite3_value_int64(argv[0]);
129084 rc = findLeafNode(pRtree, iRowid, &pLeaf);
129085 pCsr->pNode = pLeaf;
129086 if( pLeaf ){
129087 assert( rc==SQLITE_OK );
129088 rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &pCsr->iCell);
129090 }else{
129091 /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
129092 ** with the configured constraints.
129094 if( argc>0 ){
129095 pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
129096 pCsr->nConstraint = argc;
129097 if( !pCsr->aConstraint ){
129098 rc = SQLITE_NOMEM;
129099 }else{
129100 memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
129101 assert( (idxStr==0 && argc==0)
129102 || (idxStr && (int)strlen(idxStr)==argc*2) );
129103 for(ii=0; ii<argc; ii++){
129104 RtreeConstraint *p = &pCsr->aConstraint[ii];
129105 p->op = idxStr[ii*2];
129106 p->iCoord = idxStr[ii*2+1]-'a';
129107 if( p->op==RTREE_MATCH ){
129108 /* A MATCH operator. The right-hand-side must be a blob that
129109 ** can be cast into an RtreeMatchArg object. One created using
129110 ** an sqlite3_rtree_geometry_callback() SQL user function.
129112 rc = deserializeGeometry(argv[ii], p);
129113 if( rc!=SQLITE_OK ){
129114 break;
129116 }else{
129117 p->rValue = sqlite3_value_double(argv[ii]);
129123 if( rc==SQLITE_OK ){
129124 pCsr->pNode = 0;
129125 rc = nodeAcquire(pRtree, 1, 0, &pRoot);
129127 if( rc==SQLITE_OK ){
129128 int isEof = 1;
129129 int nCell = NCELL(pRoot);
129130 pCsr->pNode = pRoot;
129131 for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCell<nCell; pCsr->iCell++){
129132 assert( pCsr->pNode==pRoot );
129133 rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof);
129134 if( !isEof ){
129135 break;
129138 if( rc==SQLITE_OK && isEof ){
129139 assert( pCsr->pNode==pRoot );
129140 nodeRelease(pRtree, pRoot);
129141 pCsr->pNode = 0;
129143 assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) );
129147 rtreeRelease(pRtree);
129148 return rc;
129152 ** Rtree virtual table module xBestIndex method. There are three
129153 ** table scan strategies to choose from (in order from most to
129154 ** least desirable):
129156 ** idxNum idxStr Strategy
129157 ** ------------------------------------------------
129158 ** 1 Unused Direct lookup by rowid.
129159 ** 2 See below R-tree query or full-table scan.
129160 ** ------------------------------------------------
129162 ** If strategy 1 is used, then idxStr is not meaningful. If strategy
129163 ** 2 is used, idxStr is formatted to contain 2 bytes for each
129164 ** constraint used. The first two bytes of idxStr correspond to
129165 ** the constraint in sqlite3_index_info.aConstraintUsage[] with
129166 ** (argvIndex==1) etc.
129168 ** The first of each pair of bytes in idxStr identifies the constraint
129169 ** operator as follows:
129171 ** Operator Byte Value
129172 ** ----------------------
129173 ** = 0x41 ('A')
129174 ** <= 0x42 ('B')
129175 ** < 0x43 ('C')
129176 ** >= 0x44 ('D')
129177 ** > 0x45 ('E')
129178 ** MATCH 0x46 ('F')
129179 ** ----------------------
129181 ** The second of each pair of bytes identifies the coordinate column
129182 ** to which the constraint applies. The leftmost coordinate column
129183 ** is 'a', the second from the left 'b' etc.
129185 static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
129186 int rc = SQLITE_OK;
129187 int ii;
129189 int iIdx = 0;
129190 char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
129191 memset(zIdxStr, 0, sizeof(zIdxStr));
129192 UNUSED_PARAMETER(tab);
129194 assert( pIdxInfo->idxStr==0 );
129195 for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
129196 struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
129198 if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
129199 /* We have an equality constraint on the rowid. Use strategy 1. */
129200 int jj;
129201 for(jj=0; jj<ii; jj++){
129202 pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
129203 pIdxInfo->aConstraintUsage[jj].omit = 0;
129205 pIdxInfo->idxNum = 1;
129206 pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
129207 pIdxInfo->aConstraintUsage[jj].omit = 1;
129209 /* This strategy involves a two rowid lookups on an B-Tree structures
129210 ** and then a linear search of an R-Tree node. This should be
129211 ** considered almost as quick as a direct rowid lookup (for which
129212 ** sqlite uses an internal cost of 0.0).
129214 pIdxInfo->estimatedCost = 10.0;
129215 return SQLITE_OK;
129218 if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
129219 u8 op;
129220 switch( p->op ){
129221 case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
129222 case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
129223 case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
129224 case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
129225 case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
129226 default:
129227 assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
129228 op = RTREE_MATCH;
129229 break;
129231 zIdxStr[iIdx++] = op;
129232 zIdxStr[iIdx++] = p->iColumn - 1 + 'a';
129233 pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
129234 pIdxInfo->aConstraintUsage[ii].omit = 1;
129238 pIdxInfo->idxNum = 2;
129239 pIdxInfo->needToFreeIdxStr = 1;
129240 if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
129241 return SQLITE_NOMEM;
129243 assert( iIdx>=0 );
129244 pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1));
129245 return rc;
129249 ** Return the N-dimensional volumn of the cell stored in *p.
129251 static float cellArea(Rtree *pRtree, RtreeCell *p){
129252 float area = 1.0;
129253 int ii;
129254 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
129255 area = (float)(area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])));
129257 return area;
129261 ** Return the margin length of cell p. The margin length is the sum
129262 ** of the objects size in each dimension.
129264 static float cellMargin(Rtree *pRtree, RtreeCell *p){
129265 float margin = 0.0;
129266 int ii;
129267 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
129268 margin += (float)(DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
129270 return margin;
129274 ** Store the union of cells p1 and p2 in p1.
129276 static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
129277 int ii;
129278 if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
129279 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
129280 p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
129281 p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
129283 }else{
129284 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
129285 p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
129286 p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
129292 ** Return true if the area covered by p2 is a subset of the area covered
129293 ** by p1. False otherwise.
129295 static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
129296 int ii;
129297 int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
129298 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
129299 RtreeCoord *a1 = &p1->aCoord[ii];
129300 RtreeCoord *a2 = &p2->aCoord[ii];
129301 if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
129302 || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
129304 return 0;
129307 return 1;
129311 ** Return the amount cell p would grow by if it were unioned with pCell.
129313 static float cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
129314 float area;
129315 RtreeCell cell;
129316 memcpy(&cell, p, sizeof(RtreeCell));
129317 area = cellArea(pRtree, &cell);
129318 cellUnion(pRtree, &cell, pCell);
129319 return (cellArea(pRtree, &cell)-area);
129322 #if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT
129323 static float cellOverlap(
129324 Rtree *pRtree,
129325 RtreeCell *p,
129326 RtreeCell *aCell,
129327 int nCell,
129328 int iExclude
129330 int ii;
129331 float overlap = 0.0;
129332 for(ii=0; ii<nCell; ii++){
129333 #if VARIANT_RSTARTREE_CHOOSESUBTREE
129334 if( ii!=iExclude )
129335 #else
129336 assert( iExclude==-1 );
129337 UNUSED_PARAMETER(iExclude);
129338 #endif
129340 int jj;
129341 float o = 1.0;
129342 for(jj=0; jj<(pRtree->nDim*2); jj+=2){
129343 double x1;
129344 double x2;
129346 x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
129347 x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
129349 if( x2<x1 ){
129350 o = 0.0;
129351 break;
129352 }else{
129353 o = o * (float)(x2-x1);
129356 overlap += o;
129359 return overlap;
129361 #endif
129363 #if VARIANT_RSTARTREE_CHOOSESUBTREE
129364 static float cellOverlapEnlargement(
129365 Rtree *pRtree,
129366 RtreeCell *p,
129367 RtreeCell *pInsert,
129368 RtreeCell *aCell,
129369 int nCell,
129370 int iExclude
129372 double before;
129373 double after;
129374 before = cellOverlap(pRtree, p, aCell, nCell, iExclude);
129375 cellUnion(pRtree, p, pInsert);
129376 after = cellOverlap(pRtree, p, aCell, nCell, iExclude);
129377 return (float)(after-before);
129379 #endif
129383 ** This function implements the ChooseLeaf algorithm from Gutman[84].
129384 ** ChooseSubTree in r*tree terminology.
129386 static int ChooseLeaf(
129387 Rtree *pRtree, /* Rtree table */
129388 RtreeCell *pCell, /* Cell to insert into rtree */
129389 int iHeight, /* Height of sub-tree rooted at pCell */
129390 RtreeNode **ppLeaf /* OUT: Selected leaf page */
129392 int rc;
129393 int ii;
129394 RtreeNode *pNode;
129395 rc = nodeAcquire(pRtree, 1, 0, &pNode);
129397 for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
129398 int iCell;
129399 sqlite3_int64 iBest = 0;
129401 float fMinGrowth = 0.0;
129402 float fMinArea = 0.0;
129403 #if VARIANT_RSTARTREE_CHOOSESUBTREE
129404 float fMinOverlap = 0.0;
129405 float overlap;
129406 #endif
129408 int nCell = NCELL(pNode);
129409 RtreeCell cell;
129410 RtreeNode *pChild;
129412 RtreeCell *aCell = 0;
129414 #if VARIANT_RSTARTREE_CHOOSESUBTREE
129415 if( ii==(pRtree->iDepth-1) ){
129416 int jj;
129417 aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell);
129418 if( !aCell ){
129419 rc = SQLITE_NOMEM;
129420 nodeRelease(pRtree, pNode);
129421 pNode = 0;
129422 continue;
129424 for(jj=0; jj<nCell; jj++){
129425 nodeGetCell(pRtree, pNode, jj, &aCell[jj]);
129428 #endif
129430 /* Select the child node which will be enlarged the least if pCell
129431 ** is inserted into it. Resolve ties by choosing the entry with
129432 ** the smallest area.
129434 for(iCell=0; iCell<nCell; iCell++){
129435 int bBest = 0;
129436 float growth;
129437 float area;
129438 nodeGetCell(pRtree, pNode, iCell, &cell);
129439 growth = cellGrowth(pRtree, &cell, pCell);
129440 area = cellArea(pRtree, &cell);
129442 #if VARIANT_RSTARTREE_CHOOSESUBTREE
129443 if( ii==(pRtree->iDepth-1) ){
129444 overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
129445 }else{
129446 overlap = 0.0;
129448 if( (iCell==0)
129449 || (overlap<fMinOverlap)
129450 || (overlap==fMinOverlap && growth<fMinGrowth)
129451 || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
129453 bBest = 1;
129454 fMinOverlap = overlap;
129456 #else
129457 if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
129458 bBest = 1;
129460 #endif
129461 if( bBest ){
129462 fMinGrowth = growth;
129463 fMinArea = area;
129464 iBest = cell.iRowid;
129468 sqlite3_free(aCell);
129469 rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
129470 nodeRelease(pRtree, pNode);
129471 pNode = pChild;
129474 *ppLeaf = pNode;
129475 return rc;
129479 ** A cell with the same content as pCell has just been inserted into
129480 ** the node pNode. This function updates the bounding box cells in
129481 ** all ancestor elements.
129483 static int AdjustTree(
129484 Rtree *pRtree, /* Rtree table */
129485 RtreeNode *pNode, /* Adjust ancestry of this node. */
129486 RtreeCell *pCell /* This cell was just inserted */
129488 RtreeNode *p = pNode;
129489 while( p->pParent ){
129490 RtreeNode *pParent = p->pParent;
129491 RtreeCell cell;
129492 int iCell;
129494 if( nodeParentIndex(pRtree, p, &iCell) ){
129495 return SQLITE_CORRUPT_VTAB;
129498 nodeGetCell(pRtree, pParent, iCell, &cell);
129499 if( !cellContains(pRtree, &cell, pCell) ){
129500 cellUnion(pRtree, &cell, pCell);
129501 nodeOverwriteCell(pRtree, pParent, &cell, iCell);
129504 p = pParent;
129506 return SQLITE_OK;
129510 ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
129512 static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
129513 sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
129514 sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
129515 sqlite3_step(pRtree->pWriteRowid);
129516 return sqlite3_reset(pRtree->pWriteRowid);
129520 ** Write mapping (iNode->iPar) to the <rtree>_parent table.
129522 static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
129523 sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
129524 sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
129525 sqlite3_step(pRtree->pWriteParent);
129526 return sqlite3_reset(pRtree->pWriteParent);
129529 static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
129531 #if VARIANT_GUTTMAN_LINEAR_SPLIT
129533 ** Implementation of the linear variant of the PickNext() function from
129534 ** Guttman[84].
129536 static RtreeCell *LinearPickNext(
129537 Rtree *pRtree,
129538 RtreeCell *aCell,
129539 int nCell,
129540 RtreeCell *pLeftBox,
129541 RtreeCell *pRightBox,
129542 int *aiUsed
129544 int ii;
129545 for(ii=0; aiUsed[ii]; ii++);
129546 aiUsed[ii] = 1;
129547 return &aCell[ii];
129551 ** Implementation of the linear variant of the PickSeeds() function from
129552 ** Guttman[84].
129554 static void LinearPickSeeds(
129555 Rtree *pRtree,
129556 RtreeCell *aCell,
129557 int nCell,
129558 int *piLeftSeed,
129559 int *piRightSeed
129561 int i;
129562 int iLeftSeed = 0;
129563 int iRightSeed = 1;
129564 float maxNormalInnerWidth = 0.0;
129566 /* Pick two "seed" cells from the array of cells. The algorithm used
129567 ** here is the LinearPickSeeds algorithm from Gutman[1984]. The
129568 ** indices of the two seed cells in the array are stored in local
129569 ** variables iLeftSeek and iRightSeed.
129571 for(i=0; i<pRtree->nDim; i++){
129572 float x1 = DCOORD(aCell[0].aCoord[i*2]);
129573 float x2 = DCOORD(aCell[0].aCoord[i*2+1]);
129574 float x3 = x1;
129575 float x4 = x2;
129576 int jj;
129578 int iCellLeft = 0;
129579 int iCellRight = 0;
129581 for(jj=1; jj<nCell; jj++){
129582 float left = DCOORD(aCell[jj].aCoord[i*2]);
129583 float right = DCOORD(aCell[jj].aCoord[i*2+1]);
129585 if( left<x1 ) x1 = left;
129586 if( right>x4 ) x4 = right;
129587 if( left>x3 ){
129588 x3 = left;
129589 iCellRight = jj;
129591 if( right<x2 ){
129592 x2 = right;
129593 iCellLeft = jj;
129597 if( x4!=x1 ){
129598 float normalwidth = (x3 - x2) / (x4 - x1);
129599 if( normalwidth>maxNormalInnerWidth ){
129600 iLeftSeed = iCellLeft;
129601 iRightSeed = iCellRight;
129606 *piLeftSeed = iLeftSeed;
129607 *piRightSeed = iRightSeed;
129609 #endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */
129611 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
129613 ** Implementation of the quadratic variant of the PickNext() function from
129614 ** Guttman[84].
129616 static RtreeCell *QuadraticPickNext(
129617 Rtree *pRtree,
129618 RtreeCell *aCell,
129619 int nCell,
129620 RtreeCell *pLeftBox,
129621 RtreeCell *pRightBox,
129622 int *aiUsed
129624 #define FABS(a) ((a)<0.0?-1.0*(a):(a))
129626 int iSelect = -1;
129627 float fDiff;
129628 int ii;
129629 for(ii=0; ii<nCell; ii++){
129630 if( aiUsed[ii]==0 ){
129631 float left = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
129632 float right = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
129633 float diff = FABS(right-left);
129634 if( iSelect<0 || diff>fDiff ){
129635 fDiff = diff;
129636 iSelect = ii;
129640 aiUsed[iSelect] = 1;
129641 return &aCell[iSelect];
129645 ** Implementation of the quadratic variant of the PickSeeds() function from
129646 ** Guttman[84].
129648 static void QuadraticPickSeeds(
129649 Rtree *pRtree,
129650 RtreeCell *aCell,
129651 int nCell,
129652 int *piLeftSeed,
129653 int *piRightSeed
129655 int ii;
129656 int jj;
129658 int iLeftSeed = 0;
129659 int iRightSeed = 1;
129660 float fWaste = 0.0;
129662 for(ii=0; ii<nCell; ii++){
129663 for(jj=ii+1; jj<nCell; jj++){
129664 float right = cellArea(pRtree, &aCell[jj]);
129665 float growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]);
129666 float waste = growth - right;
129668 if( waste>fWaste ){
129669 iLeftSeed = ii;
129670 iRightSeed = jj;
129671 fWaste = waste;
129676 *piLeftSeed = iLeftSeed;
129677 *piRightSeed = iRightSeed;
129679 #endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */
129682 ** Arguments aIdx, aDistance and aSpare all point to arrays of size
129683 ** nIdx. The aIdx array contains the set of integers from 0 to
129684 ** (nIdx-1) in no particular order. This function sorts the values
129685 ** in aIdx according to the indexed values in aDistance. For
129686 ** example, assuming the inputs:
129688 ** aIdx = { 0, 1, 2, 3 }
129689 ** aDistance = { 5.0, 2.0, 7.0, 6.0 }
129691 ** this function sets the aIdx array to contain:
129693 ** aIdx = { 0, 1, 2, 3 }
129695 ** The aSpare array is used as temporary working space by the
129696 ** sorting algorithm.
129698 static void SortByDistance(
129699 int *aIdx,
129700 int nIdx,
129701 float *aDistance,
129702 int *aSpare
129704 if( nIdx>1 ){
129705 int iLeft = 0;
129706 int iRight = 0;
129708 int nLeft = nIdx/2;
129709 int nRight = nIdx-nLeft;
129710 int *aLeft = aIdx;
129711 int *aRight = &aIdx[nLeft];
129713 SortByDistance(aLeft, nLeft, aDistance, aSpare);
129714 SortByDistance(aRight, nRight, aDistance, aSpare);
129716 memcpy(aSpare, aLeft, sizeof(int)*nLeft);
129717 aLeft = aSpare;
129719 while( iLeft<nLeft || iRight<nRight ){
129720 if( iLeft==nLeft ){
129721 aIdx[iLeft+iRight] = aRight[iRight];
129722 iRight++;
129723 }else if( iRight==nRight ){
129724 aIdx[iLeft+iRight] = aLeft[iLeft];
129725 iLeft++;
129726 }else{
129727 float fLeft = aDistance[aLeft[iLeft]];
129728 float fRight = aDistance[aRight[iRight]];
129729 if( fLeft<fRight ){
129730 aIdx[iLeft+iRight] = aLeft[iLeft];
129731 iLeft++;
129732 }else{
129733 aIdx[iLeft+iRight] = aRight[iRight];
129734 iRight++;
129739 #if 0
129740 /* Check that the sort worked */
129742 int jj;
129743 for(jj=1; jj<nIdx; jj++){
129744 float left = aDistance[aIdx[jj-1]];
129745 float right = aDistance[aIdx[jj]];
129746 assert( left<=right );
129749 #endif
129754 ** Arguments aIdx, aCell and aSpare all point to arrays of size
129755 ** nIdx. The aIdx array contains the set of integers from 0 to
129756 ** (nIdx-1) in no particular order. This function sorts the values
129757 ** in aIdx according to dimension iDim of the cells in aCell. The
129758 ** minimum value of dimension iDim is considered first, the
129759 ** maximum used to break ties.
129761 ** The aSpare array is used as temporary working space by the
129762 ** sorting algorithm.
129764 static void SortByDimension(
129765 Rtree *pRtree,
129766 int *aIdx,
129767 int nIdx,
129768 int iDim,
129769 RtreeCell *aCell,
129770 int *aSpare
129772 if( nIdx>1 ){
129774 int iLeft = 0;
129775 int iRight = 0;
129777 int nLeft = nIdx/2;
129778 int nRight = nIdx-nLeft;
129779 int *aLeft = aIdx;
129780 int *aRight = &aIdx[nLeft];
129782 SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
129783 SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
129785 memcpy(aSpare, aLeft, sizeof(int)*nLeft);
129786 aLeft = aSpare;
129787 while( iLeft<nLeft || iRight<nRight ){
129788 double xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
129789 double xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
129790 double xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
129791 double xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
129792 if( (iLeft!=nLeft) && ((iRight==nRight)
129793 || (xleft1<xright1)
129794 || (xleft1==xright1 && xleft2<xright2)
129796 aIdx[iLeft+iRight] = aLeft[iLeft];
129797 iLeft++;
129798 }else{
129799 aIdx[iLeft+iRight] = aRight[iRight];
129800 iRight++;
129804 #if 0
129805 /* Check that the sort worked */
129807 int jj;
129808 for(jj=1; jj<nIdx; jj++){
129809 float xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
129810 float xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
129811 float xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
129812 float xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
129813 assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
129816 #endif
129820 #if VARIANT_RSTARTREE_SPLIT
129822 ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
129824 static int splitNodeStartree(
129825 Rtree *pRtree,
129826 RtreeCell *aCell,
129827 int nCell,
129828 RtreeNode *pLeft,
129829 RtreeNode *pRight,
129830 RtreeCell *pBboxLeft,
129831 RtreeCell *pBboxRight
129833 int **aaSorted;
129834 int *aSpare;
129835 int ii;
129837 int iBestDim = 0;
129838 int iBestSplit = 0;
129839 float fBestMargin = 0.0;
129841 int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
129843 aaSorted = (int **)sqlite3_malloc(nByte);
129844 if( !aaSorted ){
129845 return SQLITE_NOMEM;
129848 aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
129849 memset(aaSorted, 0, nByte);
129850 for(ii=0; ii<pRtree->nDim; ii++){
129851 int jj;
129852 aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
129853 for(jj=0; jj<nCell; jj++){
129854 aaSorted[ii][jj] = jj;
129856 SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
129859 for(ii=0; ii<pRtree->nDim; ii++){
129860 float margin = 0.0;
129861 float fBestOverlap = 0.0;
129862 float fBestArea = 0.0;
129863 int iBestLeft = 0;
129864 int nLeft;
129867 nLeft=RTREE_MINCELLS(pRtree);
129868 nLeft<=(nCell-RTREE_MINCELLS(pRtree));
129869 nLeft++
129871 RtreeCell left;
129872 RtreeCell right;
129873 int kk;
129874 float overlap;
129875 float area;
129877 memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
129878 memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
129879 for(kk=1; kk<(nCell-1); kk++){
129880 if( kk<nLeft ){
129881 cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
129882 }else{
129883 cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
129886 margin += cellMargin(pRtree, &left);
129887 margin += cellMargin(pRtree, &right);
129888 overlap = cellOverlap(pRtree, &left, &right, 1, -1);
129889 area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
129890 if( (nLeft==RTREE_MINCELLS(pRtree))
129891 || (overlap<fBestOverlap)
129892 || (overlap==fBestOverlap && area<fBestArea)
129894 iBestLeft = nLeft;
129895 fBestOverlap = overlap;
129896 fBestArea = area;
129900 if( ii==0 || margin<fBestMargin ){
129901 iBestDim = ii;
129902 fBestMargin = margin;
129903 iBestSplit = iBestLeft;
129907 memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
129908 memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
129909 for(ii=0; ii<nCell; ii++){
129910 RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
129911 RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
129912 RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
129913 nodeInsertCell(pRtree, pTarget, pCell);
129914 cellUnion(pRtree, pBbox, pCell);
129917 sqlite3_free(aaSorted);
129918 return SQLITE_OK;
129920 #endif
129922 #if VARIANT_GUTTMAN_SPLIT
129924 ** Implementation of the regular R-tree SplitNode from Guttman[1984].
129926 static int splitNodeGuttman(
129927 Rtree *pRtree,
129928 RtreeCell *aCell,
129929 int nCell,
129930 RtreeNode *pLeft,
129931 RtreeNode *pRight,
129932 RtreeCell *pBboxLeft,
129933 RtreeCell *pBboxRight
129935 int iLeftSeed = 0;
129936 int iRightSeed = 1;
129937 int *aiUsed;
129938 int i;
129940 aiUsed = sqlite3_malloc(sizeof(int)*nCell);
129941 if( !aiUsed ){
129942 return SQLITE_NOMEM;
129944 memset(aiUsed, 0, sizeof(int)*nCell);
129946 PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed);
129948 memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell));
129949 memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell));
129950 nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]);
129951 nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]);
129952 aiUsed[iLeftSeed] = 1;
129953 aiUsed[iRightSeed] = 1;
129955 for(i=nCell-2; i>0; i--){
129956 RtreeCell *pNext;
129957 pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed);
129958 float diff =
129959 cellGrowth(pRtree, pBboxLeft, pNext) -
129960 cellGrowth(pRtree, pBboxRight, pNext)
129962 if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i)
129963 || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i))
129965 nodeInsertCell(pRtree, pRight, pNext);
129966 cellUnion(pRtree, pBboxRight, pNext);
129967 }else{
129968 nodeInsertCell(pRtree, pLeft, pNext);
129969 cellUnion(pRtree, pBboxLeft, pNext);
129973 sqlite3_free(aiUsed);
129974 return SQLITE_OK;
129976 #endif
129978 static int updateMapping(
129979 Rtree *pRtree,
129980 i64 iRowid,
129981 RtreeNode *pNode,
129982 int iHeight
129984 int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
129985 xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
129986 if( iHeight>0 ){
129987 RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
129988 if( pChild ){
129989 nodeRelease(pRtree, pChild->pParent);
129990 nodeReference(pNode);
129991 pChild->pParent = pNode;
129994 return xSetMapping(pRtree, iRowid, pNode->iNode);
129997 static int SplitNode(
129998 Rtree *pRtree,
129999 RtreeNode *pNode,
130000 RtreeCell *pCell,
130001 int iHeight
130003 int i;
130004 int newCellIsRight = 0;
130006 int rc = SQLITE_OK;
130007 int nCell = NCELL(pNode);
130008 RtreeCell *aCell;
130009 int *aiUsed;
130011 RtreeNode *pLeft = 0;
130012 RtreeNode *pRight = 0;
130014 RtreeCell leftbbox;
130015 RtreeCell rightbbox;
130017 /* Allocate an array and populate it with a copy of pCell and
130018 ** all cells from node pLeft. Then zero the original node.
130020 aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
130021 if( !aCell ){
130022 rc = SQLITE_NOMEM;
130023 goto splitnode_out;
130025 aiUsed = (int *)&aCell[nCell+1];
130026 memset(aiUsed, 0, sizeof(int)*(nCell+1));
130027 for(i=0; i<nCell; i++){
130028 nodeGetCell(pRtree, pNode, i, &aCell[i]);
130030 nodeZero(pRtree, pNode);
130031 memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
130032 nCell++;
130034 if( pNode->iNode==1 ){
130035 pRight = nodeNew(pRtree, pNode);
130036 pLeft = nodeNew(pRtree, pNode);
130037 pRtree->iDepth++;
130038 pNode->isDirty = 1;
130039 writeInt16(pNode->zData, pRtree->iDepth);
130040 }else{
130041 pLeft = pNode;
130042 pRight = nodeNew(pRtree, pLeft->pParent);
130043 nodeReference(pLeft);
130046 if( !pLeft || !pRight ){
130047 rc = SQLITE_NOMEM;
130048 goto splitnode_out;
130051 memset(pLeft->zData, 0, pRtree->iNodeSize);
130052 memset(pRight->zData, 0, pRtree->iNodeSize);
130054 rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
130055 if( rc!=SQLITE_OK ){
130056 goto splitnode_out;
130059 /* Ensure both child nodes have node numbers assigned to them by calling
130060 ** nodeWrite(). Node pRight always needs a node number, as it was created
130061 ** by nodeNew() above. But node pLeft sometimes already has a node number.
130062 ** In this case avoid the all to nodeWrite().
130064 if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
130065 || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
130067 goto splitnode_out;
130070 rightbbox.iRowid = pRight->iNode;
130071 leftbbox.iRowid = pLeft->iNode;
130073 if( pNode->iNode==1 ){
130074 rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
130075 if( rc!=SQLITE_OK ){
130076 goto splitnode_out;
130078 }else{
130079 RtreeNode *pParent = pLeft->pParent;
130080 int iCell;
130081 rc = nodeParentIndex(pRtree, pLeft, &iCell);
130082 if( rc==SQLITE_OK ){
130083 nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
130084 rc = AdjustTree(pRtree, pParent, &leftbbox);
130086 if( rc!=SQLITE_OK ){
130087 goto splitnode_out;
130090 if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
130091 goto splitnode_out;
130094 for(i=0; i<NCELL(pRight); i++){
130095 i64 iRowid = nodeGetRowid(pRtree, pRight, i);
130096 rc = updateMapping(pRtree, iRowid, pRight, iHeight);
130097 if( iRowid==pCell->iRowid ){
130098 newCellIsRight = 1;
130100 if( rc!=SQLITE_OK ){
130101 goto splitnode_out;
130104 if( pNode->iNode==1 ){
130105 for(i=0; i<NCELL(pLeft); i++){
130106 i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
130107 rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
130108 if( rc!=SQLITE_OK ){
130109 goto splitnode_out;
130112 }else if( newCellIsRight==0 ){
130113 rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
130116 if( rc==SQLITE_OK ){
130117 rc = nodeRelease(pRtree, pRight);
130118 pRight = 0;
130120 if( rc==SQLITE_OK ){
130121 rc = nodeRelease(pRtree, pLeft);
130122 pLeft = 0;
130125 splitnode_out:
130126 nodeRelease(pRtree, pRight);
130127 nodeRelease(pRtree, pLeft);
130128 sqlite3_free(aCell);
130129 return rc;
130133 ** If node pLeaf is not the root of the r-tree and its pParent pointer is
130134 ** still NULL, load all ancestor nodes of pLeaf into memory and populate
130135 ** the pLeaf->pParent chain all the way up to the root node.
130137 ** This operation is required when a row is deleted (or updated - an update
130138 ** is implemented as a delete followed by an insert). SQLite provides the
130139 ** rowid of the row to delete, which can be used to find the leaf on which
130140 ** the entry resides (argument pLeaf). Once the leaf is located, this
130141 ** function is called to determine its ancestry.
130143 static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
130144 int rc = SQLITE_OK;
130145 RtreeNode *pChild = pLeaf;
130146 while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
130147 int rc2 = SQLITE_OK; /* sqlite3_reset() return code */
130148 sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
130149 rc = sqlite3_step(pRtree->pReadParent);
130150 if( rc==SQLITE_ROW ){
130151 RtreeNode *pTest; /* Used to test for reference loops */
130152 i64 iNode; /* Node number of parent node */
130154 /* Before setting pChild->pParent, test that we are not creating a
130155 ** loop of references (as we would if, say, pChild==pParent). We don't
130156 ** want to do this as it leads to a memory leak when trying to delete
130157 ** the referenced counted node structures.
130159 iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
130160 for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
130161 if( !pTest ){
130162 rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
130165 rc = sqlite3_reset(pRtree->pReadParent);
130166 if( rc==SQLITE_OK ) rc = rc2;
130167 if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
130168 pChild = pChild->pParent;
130170 return rc;
130173 static int deleteCell(Rtree *, RtreeNode *, int, int);
130175 static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
130176 int rc;
130177 int rc2;
130178 RtreeNode *pParent = 0;
130179 int iCell;
130181 assert( pNode->nRef==1 );
130183 /* Remove the entry in the parent cell. */
130184 rc = nodeParentIndex(pRtree, pNode, &iCell);
130185 if( rc==SQLITE_OK ){
130186 pParent = pNode->pParent;
130187 pNode->pParent = 0;
130188 rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
130190 rc2 = nodeRelease(pRtree, pParent);
130191 if( rc==SQLITE_OK ){
130192 rc = rc2;
130194 if( rc!=SQLITE_OK ){
130195 return rc;
130198 /* Remove the xxx_node entry. */
130199 sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
130200 sqlite3_step(pRtree->pDeleteNode);
130201 if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
130202 return rc;
130205 /* Remove the xxx_parent entry. */
130206 sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
130207 sqlite3_step(pRtree->pDeleteParent);
130208 if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
130209 return rc;
130212 /* Remove the node from the in-memory hash table and link it into
130213 ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
130215 nodeHashDelete(pRtree, pNode);
130216 pNode->iNode = iHeight;
130217 pNode->pNext = pRtree->pDeleted;
130218 pNode->nRef++;
130219 pRtree->pDeleted = pNode;
130221 return SQLITE_OK;
130224 static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
130225 RtreeNode *pParent = pNode->pParent;
130226 int rc = SQLITE_OK;
130227 if( pParent ){
130228 int ii;
130229 int nCell = NCELL(pNode);
130230 RtreeCell box; /* Bounding box for pNode */
130231 nodeGetCell(pRtree, pNode, 0, &box);
130232 for(ii=1; ii<nCell; ii++){
130233 RtreeCell cell;
130234 nodeGetCell(pRtree, pNode, ii, &cell);
130235 cellUnion(pRtree, &box, &cell);
130237 box.iRowid = pNode->iNode;
130238 rc = nodeParentIndex(pRtree, pNode, &ii);
130239 if( rc==SQLITE_OK ){
130240 nodeOverwriteCell(pRtree, pParent, &box, ii);
130241 rc = fixBoundingBox(pRtree, pParent);
130244 return rc;
130248 ** Delete the cell at index iCell of node pNode. After removing the
130249 ** cell, adjust the r-tree data structure if required.
130251 static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
130252 RtreeNode *pParent;
130253 int rc;
130255 if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
130256 return rc;
130259 /* Remove the cell from the node. This call just moves bytes around
130260 ** the in-memory node image, so it cannot fail.
130262 nodeDeleteCell(pRtree, pNode, iCell);
130264 /* If the node is not the tree root and now has less than the minimum
130265 ** number of cells, remove it from the tree. Otherwise, update the
130266 ** cell in the parent node so that it tightly contains the updated
130267 ** node.
130269 pParent = pNode->pParent;
130270 assert( pParent || pNode->iNode==1 );
130271 if( pParent ){
130272 if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
130273 rc = removeNode(pRtree, pNode, iHeight);
130274 }else{
130275 rc = fixBoundingBox(pRtree, pNode);
130279 return rc;
130282 static int Reinsert(
130283 Rtree *pRtree,
130284 RtreeNode *pNode,
130285 RtreeCell *pCell,
130286 int iHeight
130288 int *aOrder;
130289 int *aSpare;
130290 RtreeCell *aCell;
130291 float *aDistance;
130292 int nCell;
130293 float aCenterCoord[RTREE_MAX_DIMENSIONS];
130294 int iDim;
130295 int ii;
130296 int rc = SQLITE_OK;
130298 memset(aCenterCoord, 0, sizeof(float)*RTREE_MAX_DIMENSIONS);
130300 nCell = NCELL(pNode)+1;
130302 /* Allocate the buffers used by this operation. The allocation is
130303 ** relinquished before this function returns.
130305 aCell = (RtreeCell *)sqlite3_malloc(nCell * (
130306 sizeof(RtreeCell) + /* aCell array */
130307 sizeof(int) + /* aOrder array */
130308 sizeof(int) + /* aSpare array */
130309 sizeof(float) /* aDistance array */
130311 if( !aCell ){
130312 return SQLITE_NOMEM;
130314 aOrder = (int *)&aCell[nCell];
130315 aSpare = (int *)&aOrder[nCell];
130316 aDistance = (float *)&aSpare[nCell];
130318 for(ii=0; ii<nCell; ii++){
130319 if( ii==(nCell-1) ){
130320 memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
130321 }else{
130322 nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
130324 aOrder[ii] = ii;
130325 for(iDim=0; iDim<pRtree->nDim; iDim++){
130326 aCenterCoord[iDim] += (float)DCOORD(aCell[ii].aCoord[iDim*2]);
130327 aCenterCoord[iDim] += (float)DCOORD(aCell[ii].aCoord[iDim*2+1]);
130330 for(iDim=0; iDim<pRtree->nDim; iDim++){
130331 aCenterCoord[iDim] = (float)(aCenterCoord[iDim]/((float)nCell*2.0));
130334 for(ii=0; ii<nCell; ii++){
130335 aDistance[ii] = 0.0;
130336 for(iDim=0; iDim<pRtree->nDim; iDim++){
130337 float coord = (float)(DCOORD(aCell[ii].aCoord[iDim*2+1]) -
130338 DCOORD(aCell[ii].aCoord[iDim*2]));
130339 aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
130343 SortByDistance(aOrder, nCell, aDistance, aSpare);
130344 nodeZero(pRtree, pNode);
130346 for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
130347 RtreeCell *p = &aCell[aOrder[ii]];
130348 nodeInsertCell(pRtree, pNode, p);
130349 if( p->iRowid==pCell->iRowid ){
130350 if( iHeight==0 ){
130351 rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
130352 }else{
130353 rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
130357 if( rc==SQLITE_OK ){
130358 rc = fixBoundingBox(pRtree, pNode);
130360 for(; rc==SQLITE_OK && ii<nCell; ii++){
130361 /* Find a node to store this cell in. pNode->iNode currently contains
130362 ** the height of the sub-tree headed by the cell.
130364 RtreeNode *pInsert;
130365 RtreeCell *p = &aCell[aOrder[ii]];
130366 rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
130367 if( rc==SQLITE_OK ){
130368 int rc2;
130369 rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
130370 rc2 = nodeRelease(pRtree, pInsert);
130371 if( rc==SQLITE_OK ){
130372 rc = rc2;
130377 sqlite3_free(aCell);
130378 return rc;
130382 ** Insert cell pCell into node pNode. Node pNode is the head of a
130383 ** subtree iHeight high (leaf nodes have iHeight==0).
130385 static int rtreeInsertCell(
130386 Rtree *pRtree,
130387 RtreeNode *pNode,
130388 RtreeCell *pCell,
130389 int iHeight
130391 int rc = SQLITE_OK;
130392 if( iHeight>0 ){
130393 RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
130394 if( pChild ){
130395 nodeRelease(pRtree, pChild->pParent);
130396 nodeReference(pNode);
130397 pChild->pParent = pNode;
130400 if( nodeInsertCell(pRtree, pNode, pCell) ){
130401 #if VARIANT_RSTARTREE_REINSERT
130402 if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
130403 rc = SplitNode(pRtree, pNode, pCell, iHeight);
130404 }else{
130405 pRtree->iReinsertHeight = iHeight;
130406 rc = Reinsert(pRtree, pNode, pCell, iHeight);
130408 #else
130409 rc = SplitNode(pRtree, pNode, pCell, iHeight);
130410 #endif
130411 }else{
130412 rc = AdjustTree(pRtree, pNode, pCell);
130413 if( rc==SQLITE_OK ){
130414 if( iHeight==0 ){
130415 rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
130416 }else{
130417 rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
130421 return rc;
130424 static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
130425 int ii;
130426 int rc = SQLITE_OK;
130427 int nCell = NCELL(pNode);
130429 for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
130430 RtreeNode *pInsert;
130431 RtreeCell cell;
130432 nodeGetCell(pRtree, pNode, ii, &cell);
130434 /* Find a node to store this cell in. pNode->iNode currently contains
130435 ** the height of the sub-tree headed by the cell.
130437 rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
130438 if( rc==SQLITE_OK ){
130439 int rc2;
130440 rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
130441 rc2 = nodeRelease(pRtree, pInsert);
130442 if( rc==SQLITE_OK ){
130443 rc = rc2;
130447 return rc;
130451 ** Select a currently unused rowid for a new r-tree record.
130453 static int newRowid(Rtree *pRtree, i64 *piRowid){
130454 int rc;
130455 sqlite3_bind_null(pRtree->pWriteRowid, 1);
130456 sqlite3_bind_null(pRtree->pWriteRowid, 2);
130457 sqlite3_step(pRtree->pWriteRowid);
130458 rc = sqlite3_reset(pRtree->pWriteRowid);
130459 *piRowid = sqlite3_last_insert_rowid(pRtree->db);
130460 return rc;
130464 ** Remove the entry with rowid=iDelete from the r-tree structure.
130466 static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
130467 int rc; /* Return code */
130468 RtreeNode *pLeaf; /* Leaf node containing record iDelete */
130469 int iCell; /* Index of iDelete cell in pLeaf */
130470 RtreeNode *pRoot; /* Root node of rtree structure */
130473 /* Obtain a reference to the root node to initialise Rtree.iDepth */
130474 rc = nodeAcquire(pRtree, 1, 0, &pRoot);
130476 /* Obtain a reference to the leaf node that contains the entry
130477 ** about to be deleted.
130479 if( rc==SQLITE_OK ){
130480 rc = findLeafNode(pRtree, iDelete, &pLeaf);
130483 /* Delete the cell in question from the leaf node. */
130484 if( rc==SQLITE_OK ){
130485 int rc2;
130486 rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
130487 if( rc==SQLITE_OK ){
130488 rc = deleteCell(pRtree, pLeaf, iCell, 0);
130490 rc2 = nodeRelease(pRtree, pLeaf);
130491 if( rc==SQLITE_OK ){
130492 rc = rc2;
130496 /* Delete the corresponding entry in the <rtree>_rowid table. */
130497 if( rc==SQLITE_OK ){
130498 sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
130499 sqlite3_step(pRtree->pDeleteRowid);
130500 rc = sqlite3_reset(pRtree->pDeleteRowid);
130503 /* Check if the root node now has exactly one child. If so, remove
130504 ** it, schedule the contents of the child for reinsertion and
130505 ** reduce the tree height by one.
130507 ** This is equivalent to copying the contents of the child into
130508 ** the root node (the operation that Gutman's paper says to perform
130509 ** in this scenario).
130511 if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
130512 int rc2;
130513 RtreeNode *pChild;
130514 i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
130515 rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
130516 if( rc==SQLITE_OK ){
130517 rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
130519 rc2 = nodeRelease(pRtree, pChild);
130520 if( rc==SQLITE_OK ) rc = rc2;
130521 if( rc==SQLITE_OK ){
130522 pRtree->iDepth--;
130523 writeInt16(pRoot->zData, pRtree->iDepth);
130524 pRoot->isDirty = 1;
130528 /* Re-insert the contents of any underfull nodes removed from the tree. */
130529 for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
130530 if( rc==SQLITE_OK ){
130531 rc = reinsertNodeContent(pRtree, pLeaf);
130533 pRtree->pDeleted = pLeaf->pNext;
130534 sqlite3_free(pLeaf);
130537 /* Release the reference to the root node. */
130538 if( rc==SQLITE_OK ){
130539 rc = nodeRelease(pRtree, pRoot);
130540 }else{
130541 nodeRelease(pRtree, pRoot);
130544 return rc;
130548 ** The xUpdate method for rtree module virtual tables.
130550 static int rtreeUpdate(
130551 sqlite3_vtab *pVtab,
130552 int nData,
130553 sqlite3_value **azData,
130554 sqlite_int64 *pRowid
130556 Rtree *pRtree = (Rtree *)pVtab;
130557 int rc = SQLITE_OK;
130558 RtreeCell cell; /* New cell to insert if nData>1 */
130559 int bHaveRowid = 0; /* Set to 1 after new rowid is determined */
130561 rtreeReference(pRtree);
130562 assert(nData>=1);
130564 /* Constraint handling. A write operation on an r-tree table may return
130565 ** SQLITE_CONSTRAINT for two reasons:
130567 ** 1. A duplicate rowid value, or
130568 ** 2. The supplied data violates the "x2>=x1" constraint.
130570 ** In the first case, if the conflict-handling mode is REPLACE, then
130571 ** the conflicting row can be removed before proceeding. In the second
130572 ** case, SQLITE_CONSTRAINT must be returned regardless of the
130573 ** conflict-handling mode specified by the user.
130575 if( nData>1 ){
130576 int ii;
130578 /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
130579 assert( nData==(pRtree->nDim*2 + 3) );
130580 if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
130581 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
130582 cell.aCoord[ii].f = (float)sqlite3_value_double(azData[ii+3]);
130583 cell.aCoord[ii+1].f = (float)sqlite3_value_double(azData[ii+4]);
130584 if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
130585 rc = SQLITE_CONSTRAINT;
130586 goto constraint;
130589 }else{
130590 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
130591 cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
130592 cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
130593 if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
130594 rc = SQLITE_CONSTRAINT;
130595 goto constraint;
130600 /* If a rowid value was supplied, check if it is already present in
130601 ** the table. If so, the constraint has failed. */
130602 if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){
130603 cell.iRowid = sqlite3_value_int64(azData[2]);
130604 if( sqlite3_value_type(azData[0])==SQLITE_NULL
130605 || sqlite3_value_int64(azData[0])!=cell.iRowid
130607 int steprc;
130608 sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
130609 steprc = sqlite3_step(pRtree->pReadRowid);
130610 rc = sqlite3_reset(pRtree->pReadRowid);
130611 if( SQLITE_ROW==steprc ){
130612 if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
130613 rc = rtreeDeleteRowid(pRtree, cell.iRowid);
130614 }else{
130615 rc = SQLITE_CONSTRAINT;
130616 goto constraint;
130620 bHaveRowid = 1;
130624 /* If azData[0] is not an SQL NULL value, it is the rowid of a
130625 ** record to delete from the r-tree table. The following block does
130626 ** just that.
130628 if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
130629 rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));
130632 /* If the azData[] array contains more than one element, elements
130633 ** (azData[2]..azData[argc-1]) contain a new record to insert into
130634 ** the r-tree structure.
130636 if( rc==SQLITE_OK && nData>1 ){
130637 /* Insert the new record into the r-tree */
130638 RtreeNode *pLeaf;
130640 /* Figure out the rowid of the new row. */
130641 if( bHaveRowid==0 ){
130642 rc = newRowid(pRtree, &cell.iRowid);
130644 *pRowid = cell.iRowid;
130646 if( rc==SQLITE_OK ){
130647 rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
130649 if( rc==SQLITE_OK ){
130650 int rc2;
130651 pRtree->iReinsertHeight = -1;
130652 rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
130653 rc2 = nodeRelease(pRtree, pLeaf);
130654 if( rc==SQLITE_OK ){
130655 rc = rc2;
130660 constraint:
130661 rtreeRelease(pRtree);
130662 return rc;
130666 ** The xRename method for rtree module virtual tables.
130668 static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
130669 Rtree *pRtree = (Rtree *)pVtab;
130670 int rc = SQLITE_NOMEM;
130671 char *zSql = sqlite3_mprintf(
130672 "ALTER TABLE %Q.'%q_node' RENAME TO \"%w_node\";"
130673 "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
130674 "ALTER TABLE %Q.'%q_rowid' RENAME TO \"%w_rowid\";"
130675 , pRtree->zDb, pRtree->zName, zNewName
130676 , pRtree->zDb, pRtree->zName, zNewName
130677 , pRtree->zDb, pRtree->zName, zNewName
130679 if( zSql ){
130680 rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
130681 sqlite3_free(zSql);
130683 return rc;
130686 static sqlite3_module rtreeModule = {
130687 0, /* iVersion */
130688 rtreeCreate, /* xCreate - create a table */
130689 rtreeConnect, /* xConnect - connect to an existing table */
130690 rtreeBestIndex, /* xBestIndex - Determine search strategy */
130691 rtreeDisconnect, /* xDisconnect - Disconnect from a table */
130692 rtreeDestroy, /* xDestroy - Drop a table */
130693 rtreeOpen, /* xOpen - open a cursor */
130694 rtreeClose, /* xClose - close a cursor */
130695 rtreeFilter, /* xFilter - configure scan constraints */
130696 rtreeNext, /* xNext - advance a cursor */
130697 rtreeEof, /* xEof */
130698 rtreeColumn, /* xColumn - read data */
130699 rtreeRowid, /* xRowid - read data */
130700 rtreeUpdate, /* xUpdate - write data */
130701 0, /* xBegin - begin transaction */
130702 0, /* xSync - sync transaction */
130703 0, /* xCommit - commit transaction */
130704 0, /* xRollback - rollback transaction */
130705 0, /* xFindFunction - function overloading */
130706 rtreeRename, /* xRename - rename the table */
130707 0, /* xSavepoint */
130708 0, /* xRelease */
130709 0 /* xRollbackTo */
130712 static int rtreeSqlInit(
130713 Rtree *pRtree,
130714 sqlite3 *db,
130715 const char *zDb,
130716 const char *zPrefix,
130717 int isCreate
130719 int rc = SQLITE_OK;
130721 #define N_STATEMENT 9
130722 static const char *azSql[N_STATEMENT] = {
130723 /* Read and write the xxx_node table */
130724 "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
130725 "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
130726 "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
130728 /* Read and write the xxx_rowid table */
130729 "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
130730 "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
130731 "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
130733 /* Read and write the xxx_parent table */
130734 "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
130735 "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
130736 "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
130738 sqlite3_stmt **appStmt[N_STATEMENT];
130739 int i;
130741 pRtree->db = db;
130743 if( isCreate ){
130744 char *zCreate = sqlite3_mprintf(
130745 "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
130746 "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
130747 "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);"
130748 "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
130749 zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
130751 if( !zCreate ){
130752 return SQLITE_NOMEM;
130754 rc = sqlite3_exec(db, zCreate, 0, 0, 0);
130755 sqlite3_free(zCreate);
130756 if( rc!=SQLITE_OK ){
130757 return rc;
130761 appStmt[0] = &pRtree->pReadNode;
130762 appStmt[1] = &pRtree->pWriteNode;
130763 appStmt[2] = &pRtree->pDeleteNode;
130764 appStmt[3] = &pRtree->pReadRowid;
130765 appStmt[4] = &pRtree->pWriteRowid;
130766 appStmt[5] = &pRtree->pDeleteRowid;
130767 appStmt[6] = &pRtree->pReadParent;
130768 appStmt[7] = &pRtree->pWriteParent;
130769 appStmt[8] = &pRtree->pDeleteParent;
130771 for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
130772 char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
130773 if( zSql ){
130774 rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0);
130775 }else{
130776 rc = SQLITE_NOMEM;
130778 sqlite3_free(zSql);
130781 return rc;
130785 ** The second argument to this function contains the text of an SQL statement
130786 ** that returns a single integer value. The statement is compiled and executed
130787 ** using database connection db. If successful, the integer value returned
130788 ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
130789 ** code is returned and the value of *piVal after returning is not defined.
130791 static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
130792 int rc = SQLITE_NOMEM;
130793 if( zSql ){
130794 sqlite3_stmt *pStmt = 0;
130795 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
130796 if( rc==SQLITE_OK ){
130797 if( SQLITE_ROW==sqlite3_step(pStmt) ){
130798 *piVal = sqlite3_column_int(pStmt, 0);
130800 rc = sqlite3_finalize(pStmt);
130803 return rc;
130807 ** This function is called from within the xConnect() or xCreate() method to
130808 ** determine the node-size used by the rtree table being created or connected
130809 ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
130810 ** Otherwise, an SQLite error code is returned.
130812 ** If this function is being called as part of an xConnect(), then the rtree
130813 ** table already exists. In this case the node-size is determined by inspecting
130814 ** the root node of the tree.
130816 ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
130817 ** This ensures that each node is stored on a single database page. If the
130818 ** database page-size is so large that more than RTREE_MAXCELLS entries
130819 ** would fit in a single node, use a smaller node-size.
130821 static int getNodeSize(
130822 sqlite3 *db, /* Database handle */
130823 Rtree *pRtree, /* Rtree handle */
130824 int isCreate /* True for xCreate, false for xConnect */
130826 int rc;
130827 char *zSql;
130828 if( isCreate ){
130829 int iPageSize = 0;
130830 zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
130831 rc = getIntFromStmt(db, zSql, &iPageSize);
130832 if( rc==SQLITE_OK ){
130833 pRtree->iNodeSize = iPageSize-64;
130834 if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
130835 pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
130838 }else{
130839 zSql = sqlite3_mprintf(
130840 "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
130841 pRtree->zDb, pRtree->zName
130843 rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
130846 sqlite3_free(zSql);
130847 return rc;
130851 ** This function is the implementation of both the xConnect and xCreate
130852 ** methods of the r-tree virtual table.
130854 ** argv[0] -> module name
130855 ** argv[1] -> database name
130856 ** argv[2] -> table name
130857 ** argv[...] -> column names...
130859 static int rtreeInit(
130860 sqlite3 *db, /* Database connection */
130861 void *pAux, /* One of the RTREE_COORD_* constants */
130862 int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */
130863 sqlite3_vtab **ppVtab, /* OUT: New virtual table */
130864 char **pzErr, /* OUT: Error message, if any */
130865 int isCreate /* True for xCreate, false for xConnect */
130867 int rc = SQLITE_OK;
130868 Rtree *pRtree;
130869 int nDb; /* Length of string argv[1] */
130870 int nName; /* Length of string argv[2] */
130871 int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
130873 const char *aErrMsg[] = {
130874 0, /* 0 */
130875 "Wrong number of columns for an rtree table", /* 1 */
130876 "Too few columns for an rtree table", /* 2 */
130877 "Too many columns for an rtree table" /* 3 */
130880 int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
130881 if( aErrMsg[iErr] ){
130882 *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
130883 return SQLITE_ERROR;
130886 sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
130888 /* Allocate the sqlite3_vtab structure */
130889 nDb = strlen(argv[1]);
130890 nName = strlen(argv[2]);
130891 pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
130892 if( !pRtree ){
130893 return SQLITE_NOMEM;
130895 memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
130896 pRtree->nBusy = 1;
130897 pRtree->base.pModule = &rtreeModule;
130898 pRtree->zDb = (char *)&pRtree[1];
130899 pRtree->zName = &pRtree->zDb[nDb+1];
130900 pRtree->nDim = (argc-4)/2;
130901 pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
130902 pRtree->eCoordType = eCoordType;
130903 memcpy(pRtree->zDb, argv[1], nDb);
130904 memcpy(pRtree->zName, argv[2], nName);
130906 /* Figure out the node size to use. */
130907 rc = getNodeSize(db, pRtree, isCreate);
130909 /* Create/Connect to the underlying relational database schema. If
130910 ** that is successful, call sqlite3_declare_vtab() to configure
130911 ** the r-tree table schema.
130913 if( rc==SQLITE_OK ){
130914 if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
130915 *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
130916 }else{
130917 char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
130918 char *zTmp;
130919 int ii;
130920 for(ii=4; zSql && ii<argc; ii++){
130921 zTmp = zSql;
130922 zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
130923 sqlite3_free(zTmp);
130925 if( zSql ){
130926 zTmp = zSql;
130927 zSql = sqlite3_mprintf("%s);", zTmp);
130928 sqlite3_free(zTmp);
130930 if( !zSql ){
130931 rc = SQLITE_NOMEM;
130932 }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
130933 *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
130935 sqlite3_free(zSql);
130939 if( rc==SQLITE_OK ){
130940 *ppVtab = (sqlite3_vtab *)pRtree;
130941 }else{
130942 rtreeRelease(pRtree);
130944 return rc;
130949 ** Implementation of a scalar function that decodes r-tree nodes to
130950 ** human readable strings. This can be used for debugging and analysis.
130952 ** The scalar function takes two arguments, a blob of data containing
130953 ** an r-tree node, and the number of dimensions the r-tree indexes.
130954 ** For a two-dimensional r-tree structure called "rt", to deserialize
130955 ** all nodes, a statement like:
130957 ** SELECT rtreenode(2, data) FROM rt_node;
130959 ** The human readable string takes the form of a Tcl list with one
130960 ** entry for each cell in the r-tree node. Each entry is itself a
130961 ** list, containing the 8-byte rowid/pageno followed by the
130962 ** <num-dimension>*2 coordinates.
130964 static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
130965 char *zText = 0;
130966 RtreeNode node;
130967 Rtree tree;
130968 int ii;
130970 UNUSED_PARAMETER(nArg);
130971 memset(&node, 0, sizeof(RtreeNode));
130972 memset(&tree, 0, sizeof(Rtree));
130973 tree.nDim = sqlite3_value_int(apArg[0]);
130974 tree.nBytesPerCell = 8 + 8 * tree.nDim;
130975 node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
130977 for(ii=0; ii<NCELL(&node); ii++){
130978 char zCell[512];
130979 int nCell = 0;
130980 RtreeCell cell;
130981 int jj;
130983 nodeGetCell(&tree, &node, ii, &cell);
130984 sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
130985 nCell = strlen(zCell);
130986 for(jj=0; jj<tree.nDim*2; jj++){
130987 sqlite3_snprintf(512-nCell,&zCell[nCell]," %f",(double)cell.aCoord[jj].f);
130988 nCell = strlen(zCell);
130991 if( zText ){
130992 char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
130993 sqlite3_free(zText);
130994 zText = zTextNew;
130995 }else{
130996 zText = sqlite3_mprintf("{%s}", zCell);
131000 sqlite3_result_text(ctx, zText, -1, sqlite3_free);
131003 static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
131004 UNUSED_PARAMETER(nArg);
131005 if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
131006 || sqlite3_value_bytes(apArg[0])<2
131008 sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
131009 }else{
131010 u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
131011 sqlite3_result_int(ctx, readInt16(zBlob));
131016 ** Register the r-tree module with database handle db. This creates the
131017 ** virtual table module "rtree" and the debugging/analysis scalar
131018 ** function "rtreenode".
131020 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
131021 const int utf8 = SQLITE_UTF8;
131022 int rc;
131024 rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
131025 if( rc==SQLITE_OK ){
131026 rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
131028 if( rc==SQLITE_OK ){
131029 void *c = (void *)RTREE_COORD_REAL32;
131030 rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
131032 if( rc==SQLITE_OK ){
131033 void *c = (void *)RTREE_COORD_INT32;
131034 rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
131037 return rc;
131041 ** A version of sqlite3_free() that can be used as a callback. This is used
131042 ** in two places - as the destructor for the blob value returned by the
131043 ** invocation of a geometry function, and as the destructor for the geometry
131044 ** functions themselves.
131046 static void doSqlite3Free(void *p){
131047 sqlite3_free(p);
131051 ** Each call to sqlite3_rtree_geometry_callback() creates an ordinary SQLite
131052 ** scalar user function. This C function is the callback used for all such
131053 ** registered SQL functions.
131055 ** The scalar user functions return a blob that is interpreted by r-tree
131056 ** table MATCH operators.
131058 static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
131059 RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
131060 RtreeMatchArg *pBlob;
131061 int nBlob;
131063 nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(double);
131064 pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
131065 if( !pBlob ){
131066 sqlite3_result_error_nomem(ctx);
131067 }else{
131068 int i;
131069 pBlob->magic = RTREE_GEOMETRY_MAGIC;
131070 pBlob->xGeom = pGeomCtx->xGeom;
131071 pBlob->pContext = pGeomCtx->pContext;
131072 pBlob->nParam = nArg;
131073 for(i=0; i<nArg; i++){
131074 pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
131076 sqlite3_result_blob(ctx, pBlob, nBlob, doSqlite3Free);
131081 ** Register a new geometry function for use with the r-tree MATCH operator.
131083 SQLITE_API int sqlite3_rtree_geometry_callback(
131084 sqlite3 *db,
131085 const char *zGeom,
131086 int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *),
131087 void *pContext
131089 RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
131091 /* Allocate and populate the context object. */
131092 pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
131093 if( !pGeomCtx ) return SQLITE_NOMEM;
131094 pGeomCtx->xGeom = xGeom;
131095 pGeomCtx->pContext = pContext;
131097 /* Create the new user-function. Register a destructor function to delete
131098 ** the context object when it is no longer required. */
131099 return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
131100 (void *)pGeomCtx, geomCallback, 0, 0, doSqlite3Free
131104 #if !SQLITE_CORE
131105 SQLITE_API int sqlite3_extension_init(
131106 sqlite3 *db,
131107 char **pzErrMsg,
131108 const sqlite3_api_routines *pApi
131110 SQLITE_EXTENSION_INIT2(pApi)
131111 return sqlite3RtreeInit(db);
131113 #endif
131115 #endif
131117 /************** End of rtree.c ***********************************************/
131118 /************** Begin file icu.c *********************************************/
131120 ** 2007 May 6
131122 ** The author disclaims copyright to this source code. In place of
131123 ** a legal notice, here is a blessing:
131125 ** May you do good and not evil.
131126 ** May you find forgiveness for yourself and forgive others.
131127 ** May you share freely, never taking more than you give.
131129 *************************************************************************
131130 ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
131132 ** This file implements an integration between the ICU library
131133 ** ("International Components for Unicode", an open-source library
131134 ** for handling unicode data) and SQLite. The integration uses
131135 ** ICU to provide the following to SQLite:
131137 ** * An implementation of the SQL regexp() function (and hence REGEXP
131138 ** operator) using the ICU uregex_XX() APIs.
131140 ** * Implementations of the SQL scalar upper() and lower() functions
131141 ** for case mapping.
131143 ** * Integration of ICU and SQLite collation seqences.
131145 ** * An implementation of the LIKE operator that uses ICU to
131146 ** provide case-independent matching.
131149 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
131151 /* Include ICU headers */
131152 #include <unicode/utypes.h>
131153 #include <unicode/uregex.h>
131154 #include <unicode/ustring.h>
131155 #include <unicode/ucol.h>
131157 /* #include <assert.h> */
131159 #ifndef SQLITE_CORE
131160 SQLITE_EXTENSION_INIT1
131161 #else
131162 #endif
131165 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
131166 ** operator.
131168 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
131169 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
131170 #endif
131173 ** Version of sqlite3_free() that is always a function, never a macro.
131175 static void xFree(void *p){
131176 sqlite3_free(p);
131180 ** Compare two UTF-8 strings for equality where the first string is
131181 ** a "LIKE" expression. Return true (1) if they are the same and
131182 ** false (0) if they are different.
131184 static int icuLikeCompare(
131185 const uint8_t *zPattern, /* LIKE pattern */
131186 const uint8_t *zString, /* The UTF-8 string to compare against */
131187 const UChar32 uEsc /* The escape character */
131189 static const int MATCH_ONE = (UChar32)'_';
131190 static const int MATCH_ALL = (UChar32)'%';
131192 int iPattern = 0; /* Current byte index in zPattern */
131193 int iString = 0; /* Current byte index in zString */
131195 int prevEscape = 0; /* True if the previous character was uEsc */
131197 while( zPattern[iPattern]!=0 ){
131199 /* Read (and consume) the next character from the input pattern. */
131200 UChar32 uPattern;
131201 U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
131202 assert(uPattern!=0);
131204 /* There are now 4 possibilities:
131206 ** 1. uPattern is an unescaped match-all character "%",
131207 ** 2. uPattern is an unescaped match-one character "_",
131208 ** 3. uPattern is an unescaped escape character, or
131209 ** 4. uPattern is to be handled as an ordinary character
131211 if( !prevEscape && uPattern==MATCH_ALL ){
131212 /* Case 1. */
131213 uint8_t c;
131215 /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
131216 ** MATCH_ALL. For each MATCH_ONE, skip one character in the
131217 ** test string.
131219 while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
131220 if( c==MATCH_ONE ){
131221 if( zString[iString]==0 ) return 0;
131222 U8_FWD_1_UNSAFE(zString, iString);
131224 iPattern++;
131227 if( zPattern[iPattern]==0 ) return 1;
131229 while( zString[iString] ){
131230 if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
131231 return 1;
131233 U8_FWD_1_UNSAFE(zString, iString);
131235 return 0;
131237 }else if( !prevEscape && uPattern==MATCH_ONE ){
131238 /* Case 2. */
131239 if( zString[iString]==0 ) return 0;
131240 U8_FWD_1_UNSAFE(zString, iString);
131242 }else if( !prevEscape && uPattern==uEsc){
131243 /* Case 3. */
131244 prevEscape = 1;
131246 }else{
131247 /* Case 4. */
131248 UChar32 uString;
131249 U8_NEXT_UNSAFE(zString, iString, uString);
131250 uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
131251 uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
131252 if( uString!=uPattern ){
131253 return 0;
131255 prevEscape = 0;
131259 return zString[iString]==0;
131263 ** Implementation of the like() SQL function. This function implements
131264 ** the build-in LIKE operator. The first argument to the function is the
131265 ** pattern and the second argument is the string. So, the SQL statements:
131267 ** A LIKE B
131269 ** is implemented as like(B, A). If there is an escape character E,
131271 ** A LIKE B ESCAPE E
131273 ** is mapped to like(B, A, E).
131275 static void icuLikeFunc(
131276 sqlite3_context *context,
131277 int argc,
131278 sqlite3_value **argv
131280 const unsigned char *zA = sqlite3_value_text(argv[0]);
131281 const unsigned char *zB = sqlite3_value_text(argv[1]);
131282 UChar32 uEsc = 0;
131284 /* Limit the length of the LIKE or GLOB pattern to avoid problems
131285 ** of deep recursion and N*N behavior in patternCompare().
131287 if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
131288 sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
131289 return;
131293 if( argc==3 ){
131294 /* The escape character string must consist of a single UTF-8 character.
131295 ** Otherwise, return an error.
131297 int nE= sqlite3_value_bytes(argv[2]);
131298 const unsigned char *zE = sqlite3_value_text(argv[2]);
131299 int i = 0;
131300 if( zE==0 ) return;
131301 U8_NEXT(zE, i, nE, uEsc);
131302 if( i!=nE){
131303 sqlite3_result_error(context,
131304 "ESCAPE expression must be a single character", -1);
131305 return;
131309 if( zA && zB ){
131310 sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
131315 ** This function is called when an ICU function called from within
131316 ** the implementation of an SQL scalar function returns an error.
131318 ** The scalar function context passed as the first argument is
131319 ** loaded with an error message based on the following two args.
131321 static void icuFunctionError(
131322 sqlite3_context *pCtx, /* SQLite scalar function context */
131323 const char *zName, /* Name of ICU function that failed */
131324 UErrorCode e /* Error code returned by ICU function */
131326 char zBuf[128];
131327 sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
131328 zBuf[127] = '\0';
131329 sqlite3_result_error(pCtx, zBuf, -1);
131333 ** Function to delete compiled regexp objects. Registered as
131334 ** a destructor function with sqlite3_set_auxdata().
131336 static void icuRegexpDelete(void *p){
131337 URegularExpression *pExpr = (URegularExpression *)p;
131338 uregex_close(pExpr);
131342 ** Implementation of SQLite REGEXP operator. This scalar function takes
131343 ** two arguments. The first is a regular expression pattern to compile
131344 ** the second is a string to match against that pattern. If either
131345 ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
131346 ** is 1 if the string matches the pattern, or 0 otherwise.
131348 ** SQLite maps the regexp() function to the regexp() operator such
131349 ** that the following two are equivalent:
131351 ** zString REGEXP zPattern
131352 ** regexp(zPattern, zString)
131354 ** Uses the following ICU regexp APIs:
131356 ** uregex_open()
131357 ** uregex_matches()
131358 ** uregex_close()
131360 static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
131361 UErrorCode status = U_ZERO_ERROR;
131362 URegularExpression *pExpr;
131363 UBool res;
131364 const UChar *zString = sqlite3_value_text16(apArg[1]);
131366 (void)nArg; /* Unused parameter */
131368 /* If the left hand side of the regexp operator is NULL,
131369 ** then the result is also NULL.
131371 if( !zString ){
131372 return;
131375 pExpr = sqlite3_get_auxdata(p, 0);
131376 if( !pExpr ){
131377 const UChar *zPattern = sqlite3_value_text16(apArg[0]);
131378 if( !zPattern ){
131379 return;
131381 pExpr = uregex_open(zPattern, -1, 0, 0, &status);
131383 if( U_SUCCESS(status) ){
131384 sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
131385 }else{
131386 assert(!pExpr);
131387 icuFunctionError(p, "uregex_open", status);
131388 return;
131392 /* Configure the text that the regular expression operates on. */
131393 uregex_setText(pExpr, zString, -1, &status);
131394 if( !U_SUCCESS(status) ){
131395 icuFunctionError(p, "uregex_setText", status);
131396 return;
131399 /* Attempt the match */
131400 res = uregex_matches(pExpr, 0, &status);
131401 if( !U_SUCCESS(status) ){
131402 icuFunctionError(p, "uregex_matches", status);
131403 return;
131406 /* Set the text that the regular expression operates on to a NULL
131407 ** pointer. This is not really necessary, but it is tidier than
131408 ** leaving the regular expression object configured with an invalid
131409 ** pointer after this function returns.
131411 uregex_setText(pExpr, 0, 0, &status);
131413 /* Return 1 or 0. */
131414 sqlite3_result_int(p, res ? 1 : 0);
131418 ** Implementations of scalar functions for case mapping - upper() and
131419 ** lower(). Function upper() converts its input to upper-case (ABC).
131420 ** Function lower() converts to lower-case (abc).
131422 ** ICU provides two types of case mapping, "general" case mapping and
131423 ** "language specific". Refer to ICU documentation for the differences
131424 ** between the two.
131426 ** To utilise "general" case mapping, the upper() or lower() scalar
131427 ** functions are invoked with one argument:
131429 ** upper('ABC') -> 'abc'
131430 ** lower('abc') -> 'ABC'
131432 ** To access ICU "language specific" case mapping, upper() or lower()
131433 ** should be invoked with two arguments. The second argument is the name
131434 ** of the locale to use. Passing an empty string ("") or SQL NULL value
131435 ** as the second argument is the same as invoking the 1 argument version
131436 ** of upper() or lower().
131438 ** lower('I', 'en_us') -> 'i'
131439 ** lower('I', 'tr_tr') -> 'ı' (small dotless i)
131441 ** http://www.icu-project.org/userguide/posix.html#case_mappings
131443 static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
131444 const UChar *zInput;
131445 UChar *zOutput;
131446 int nInput;
131447 int nOutput;
131449 UErrorCode status = U_ZERO_ERROR;
131450 const char *zLocale = 0;
131452 assert(nArg==1 || nArg==2);
131453 if( nArg==2 ){
131454 zLocale = (const char *)sqlite3_value_text(apArg[1]);
131457 zInput = sqlite3_value_text16(apArg[0]);
131458 if( !zInput ){
131459 return;
131461 nInput = sqlite3_value_bytes16(apArg[0]);
131463 nOutput = nInput * 2 + 2;
131464 zOutput = sqlite3_malloc(nOutput);
131465 if( !zOutput ){
131466 return;
131469 if( sqlite3_user_data(p) ){
131470 u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
131471 }else{
131472 u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
131475 if( !U_SUCCESS(status) ){
131476 icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
131477 return;
131480 sqlite3_result_text16(p, zOutput, -1, xFree);
131484 ** Collation sequence destructor function. The pCtx argument points to
131485 ** a UCollator structure previously allocated using ucol_open().
131487 static void icuCollationDel(void *pCtx){
131488 UCollator *p = (UCollator *)pCtx;
131489 ucol_close(p);
131493 ** Collation sequence comparison function. The pCtx argument points to
131494 ** a UCollator structure previously allocated using ucol_open().
131496 static int icuCollationColl(
131497 void *pCtx,
131498 int nLeft,
131499 const void *zLeft,
131500 int nRight,
131501 const void *zRight
131503 UCollationResult res;
131504 UCollator *p = (UCollator *)pCtx;
131505 res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
131506 switch( res ){
131507 case UCOL_LESS: return -1;
131508 case UCOL_GREATER: return +1;
131509 case UCOL_EQUAL: return 0;
131511 assert(!"Unexpected return value from ucol_strcoll()");
131512 return 0;
131516 ** Implementation of the scalar function icu_load_collation().
131518 ** This scalar function is used to add ICU collation based collation
131519 ** types to an SQLite database connection. It is intended to be called
131520 ** as follows:
131522 ** SELECT icu_load_collation(<locale>, <collation-name>);
131524 ** Where <locale> is a string containing an ICU locale identifier (i.e.
131525 ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
131526 ** collation sequence to create.
131528 static void icuLoadCollation(
131529 sqlite3_context *p,
131530 int nArg,
131531 sqlite3_value **apArg
131533 sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
131534 UErrorCode status = U_ZERO_ERROR;
131535 const char *zLocale; /* Locale identifier - (eg. "jp_JP") */
131536 const char *zName; /* SQL Collation sequence name (eg. "japanese") */
131537 UCollator *pUCollator; /* ICU library collation object */
131538 int rc; /* Return code from sqlite3_create_collation_x() */
131540 assert(nArg==2);
131541 zLocale = (const char *)sqlite3_value_text(apArg[0]);
131542 zName = (const char *)sqlite3_value_text(apArg[1]);
131544 if( !zLocale || !zName ){
131545 return;
131548 pUCollator = ucol_open(zLocale, &status);
131549 if( !U_SUCCESS(status) ){
131550 icuFunctionError(p, "ucol_open", status);
131551 return;
131553 assert(p);
131555 rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
131556 icuCollationColl, icuCollationDel
131558 if( rc!=SQLITE_OK ){
131559 ucol_close(pUCollator);
131560 sqlite3_result_error(p, "Error registering collation function", -1);
131565 ** Register the ICU extension functions with database db.
131567 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
131568 struct IcuScalar {
131569 const char *zName; /* Function name */
131570 int nArg; /* Number of arguments */
131571 int enc; /* Optimal text encoding */
131572 void *pContext; /* sqlite3_user_data() context */
131573 void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
131574 } scalars[] = {
131575 {"regexp", 2, SQLITE_ANY, 0, icuRegexpFunc},
131577 {"lower", 1, SQLITE_UTF16, 0, icuCaseFunc16},
131578 {"lower", 2, SQLITE_UTF16, 0, icuCaseFunc16},
131579 {"upper", 1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
131580 {"upper", 2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
131582 {"lower", 1, SQLITE_UTF8, 0, icuCaseFunc16},
131583 {"lower", 2, SQLITE_UTF8, 0, icuCaseFunc16},
131584 {"upper", 1, SQLITE_UTF8, (void*)1, icuCaseFunc16},
131585 {"upper", 2, SQLITE_UTF8, (void*)1, icuCaseFunc16},
131587 {"like", 2, SQLITE_UTF8, 0, icuLikeFunc},
131588 {"like", 3, SQLITE_UTF8, 0, icuLikeFunc},
131590 {"icu_load_collation", 2, SQLITE_UTF8, (void*)db, icuLoadCollation},
131593 int rc = SQLITE_OK;
131594 int i;
131596 for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
131597 struct IcuScalar *p = &scalars[i];
131598 rc = sqlite3_create_function(
131599 db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
131603 return rc;
131606 #if !SQLITE_CORE
131607 SQLITE_API int sqlite3_extension_init(
131608 sqlite3 *db,
131609 char **pzErrMsg,
131610 const sqlite3_api_routines *pApi
131612 SQLITE_EXTENSION_INIT2(pApi)
131613 return sqlite3IcuInit(db);
131615 #endif
131617 #endif
131619 /************** End of icu.c *************************************************/
131620 /************** Begin file fts3_icu.c ****************************************/
131622 ** 2007 June 22
131624 ** The author disclaims copyright to this source code. In place of
131625 ** a legal notice, here is a blessing:
131627 ** May you do good and not evil.
131628 ** May you find forgiveness for yourself and forgive others.
131629 ** May you share freely, never taking more than you give.
131631 *************************************************************************
131632 ** This file implements a tokenizer for fts3 based on the ICU library.
131634 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
131635 #ifdef SQLITE_ENABLE_ICU
131637 /* #include <assert.h> */
131638 /* #include <string.h> */
131640 #include <unicode/ubrk.h>
131641 /* #include <unicode/ucol.h> */
131642 /* #include <unicode/ustring.h> */
131643 #include <unicode/utf16.h>
131645 typedef struct IcuTokenizer IcuTokenizer;
131646 typedef struct IcuCursor IcuCursor;
131648 struct IcuTokenizer {
131649 sqlite3_tokenizer base;
131650 char *zLocale;
131653 struct IcuCursor {
131654 sqlite3_tokenizer_cursor base;
131656 UBreakIterator *pIter; /* ICU break-iterator object */
131657 int nChar; /* Number of UChar elements in pInput */
131658 UChar *aChar; /* Copy of input using utf-16 encoding */
131659 int *aOffset; /* Offsets of each character in utf-8 input */
131661 int nBuffer;
131662 char *zBuffer;
131664 int iToken;
131668 ** Create a new tokenizer instance.
131670 static int icuCreate(
131671 int argc, /* Number of entries in argv[] */
131672 const char * const *argv, /* Tokenizer creation arguments */
131673 sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
131675 IcuTokenizer *p;
131676 int n = 0;
131678 if( argc>0 ){
131679 n = strlen(argv[0])+1;
131681 p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
131682 if( !p ){
131683 return SQLITE_NOMEM;
131685 memset(p, 0, sizeof(IcuTokenizer));
131687 if( n ){
131688 p->zLocale = (char *)&p[1];
131689 memcpy(p->zLocale, argv[0], n);
131692 *ppTokenizer = (sqlite3_tokenizer *)p;
131694 return SQLITE_OK;
131698 ** Destroy a tokenizer
131700 static int icuDestroy(sqlite3_tokenizer *pTokenizer){
131701 IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
131702 sqlite3_free(p);
131703 return SQLITE_OK;
131707 ** Prepare to begin tokenizing a particular string. The input
131708 ** string to be tokenized is pInput[0..nBytes-1]. A cursor
131709 ** used to incrementally tokenize this string is returned in
131710 ** *ppCursor.
131712 static int icuOpen(
131713 sqlite3_tokenizer *pTokenizer, /* The tokenizer */
131714 const char *zInput, /* Input string */
131715 int nInput, /* Length of zInput in bytes */
131716 sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
131718 IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
131719 IcuCursor *pCsr;
131721 const int32_t opt = U_FOLD_CASE_DEFAULT;
131722 UErrorCode status = U_ZERO_ERROR;
131723 int nChar;
131725 UChar32 c;
131726 int iInput = 0;
131727 int iOut = 0;
131729 *ppCursor = 0;
131731 if( nInput<0 ){
131732 nInput = strlen(zInput);
131734 nChar = nInput+1;
131735 pCsr = (IcuCursor *)sqlite3_malloc(
131736 sizeof(IcuCursor) + /* IcuCursor */
131737 nChar * sizeof(UChar) + /* IcuCursor.aChar[] */
131738 (nChar+1) * sizeof(int) /* IcuCursor.aOffset[] */
131740 if( !pCsr ){
131741 return SQLITE_NOMEM;
131743 memset(pCsr, 0, sizeof(IcuCursor));
131744 pCsr->aChar = (UChar *)&pCsr[1];
131745 pCsr->aOffset = (int *)&pCsr->aChar[nChar];
131747 pCsr->aOffset[iOut] = iInput;
131748 U8_NEXT(zInput, iInput, nInput, c);
131749 while( c>0 ){
131750 int isError = 0;
131751 c = u_foldCase(c, opt);
131752 U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
131753 if( isError ){
131754 sqlite3_free(pCsr);
131755 return SQLITE_ERROR;
131757 pCsr->aOffset[iOut] = iInput;
131759 if( iInput<nInput ){
131760 U8_NEXT(zInput, iInput, nInput, c);
131761 }else{
131762 c = 0;
131766 pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
131767 if( !U_SUCCESS(status) ){
131768 sqlite3_free(pCsr);
131769 return SQLITE_ERROR;
131771 pCsr->nChar = iOut;
131773 ubrk_first(pCsr->pIter);
131774 *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
131775 return SQLITE_OK;
131779 ** Close a tokenization cursor previously opened by a call to icuOpen().
131781 static int icuClose(sqlite3_tokenizer_cursor *pCursor){
131782 IcuCursor *pCsr = (IcuCursor *)pCursor;
131783 ubrk_close(pCsr->pIter);
131784 sqlite3_free(pCsr->zBuffer);
131785 sqlite3_free(pCsr);
131786 return SQLITE_OK;
131790 ** Extract the next token from a tokenization cursor.
131792 static int icuNext(
131793 sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
131794 const char **ppToken, /* OUT: *ppToken is the token text */
131795 int *pnBytes, /* OUT: Number of bytes in token */
131796 int *piStartOffset, /* OUT: Starting offset of token */
131797 int *piEndOffset, /* OUT: Ending offset of token */
131798 int *piPosition /* OUT: Position integer of token */
131800 IcuCursor *pCsr = (IcuCursor *)pCursor;
131802 int iStart = 0;
131803 int iEnd = 0;
131804 int nByte = 0;
131806 while( iStart==iEnd ){
131807 UChar32 c;
131809 iStart = ubrk_current(pCsr->pIter);
131810 iEnd = ubrk_next(pCsr->pIter);
131811 if( iEnd==UBRK_DONE ){
131812 return SQLITE_DONE;
131815 while( iStart<iEnd ){
131816 int iWhite = iStart;
131817 U8_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
131818 if( u_isspace(c) ){
131819 iStart = iWhite;
131820 }else{
131821 break;
131824 assert(iStart<=iEnd);
131828 UErrorCode status = U_ZERO_ERROR;
131829 if( nByte ){
131830 char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
131831 if( !zNew ){
131832 return SQLITE_NOMEM;
131834 pCsr->zBuffer = zNew;
131835 pCsr->nBuffer = nByte;
131838 u_strToUTF8(
131839 pCsr->zBuffer, pCsr->nBuffer, &nByte, /* Output vars */
131840 &pCsr->aChar[iStart], iEnd-iStart, /* Input vars */
131841 &status /* Output success/failure */
131843 } while( nByte>pCsr->nBuffer );
131845 *ppToken = pCsr->zBuffer;
131846 *pnBytes = nByte;
131847 *piStartOffset = pCsr->aOffset[iStart];
131848 *piEndOffset = pCsr->aOffset[iEnd];
131849 *piPosition = pCsr->iToken++;
131851 return SQLITE_OK;
131855 ** The set of routines that implement the simple tokenizer
131857 static const sqlite3_tokenizer_module icuTokenizerModule = {
131858 0, /* iVersion */
131859 icuCreate, /* xCreate */
131860 icuDestroy, /* xCreate */
131861 icuOpen, /* xOpen */
131862 icuClose, /* xClose */
131863 icuNext, /* xNext */
131867 ** Set *ppModule to point at the implementation of the ICU tokenizer.
131869 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
131870 sqlite3_tokenizer_module const**ppModule
131872 *ppModule = &icuTokenizerModule;
131875 #endif /* defined(SQLITE_ENABLE_ICU) */
131876 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
131878 /************** End of fts3_icu.c ********************************************/